UNPKG

@nebula.js/stardust

Version:

Product and framework agnostic integration API for Qlik's Associative Engine

19,340 lines 564 kB
/*
* @nebula.js/stardust v2.12.0
* Copyright (c) 2022 QlikTech International AB
* Released under the MIT license.
*/

import React, { useState as useState$1, useEffect as useEffect$1, useReducer, forwardRef, useMemo as useMemo$1, useImperativeHandle as useImperativeHandle$1, useCallback, useLayoutEffect as useLayoutEffect$1, createElement, PureComponent, useRef, useContext } from 'react';
import ReactDOM from 'react-dom';
import { withThemeCreator, createGenerateClassName, StylesProvider, ThemeProvider, makeStyles, useTheme as useTheme$1 } from '@material-ui/styles';
import { Checkbox, Radio, Grid, FormControlLabel, Typography, IconButton, makeStyles as makeStyles$1, Popover, MenuList, MenuItem, ListItemIcon, Divider, OutlinedInput, InputAdornment, Badge, List, ListItem, Button, Box, Icon, CircularProgress, Paper } from '@material-ui/core';

var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

function getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

var runtime = {exports: {}};

/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

(function (module) {
	var runtime = (function (exports) {

	  var Op = Object.prototype;
	  var hasOwn = Op.hasOwnProperty;
	  var undefined$1; // More compressible than void 0.
	  var $Symbol = typeof Symbol === "function" ? Symbol : {};
	  var iteratorSymbol = $Symbol.iterator || "@@iterator";
	  var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
	  var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";

	  function define(obj, key, value) {
	    Object.defineProperty(obj, key, {
	      value: value,
	      enumerable: true,
	      configurable: true,
	      writable: true
	    });
	    return obj[key];
	  }
	  try {
	    // IE 8 has a broken Object.defineProperty that only works on DOM objects.
	    define({}, "");
	  } catch (err) {
	    define = function(obj, key, value) {
	      return obj[key] = value;
	    };
	  }

	  function wrap(innerFn, outerFn, self, tryLocsList) {
	    // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
	    var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
	    var generator = Object.create(protoGenerator.prototype);
	    var context = new Context(tryLocsList || []);

	    // The ._invoke method unifies the implementations of the .next,
	    // .throw, and .return methods.
	    generator._invoke = makeInvokeMethod(innerFn, self, context);

	    return generator;
	  }
	  exports.wrap = wrap;

	  // Try/catch helper to minimize deoptimizations. Returns a completion
	  // record like context.tryEntries[i].completion. This interface could
	  // have been (and was previously) designed to take a closure to be
	  // invoked without arguments, but in all the cases we care about we
	  // already have an existing method we want to call, so there's no need
	  // to create a new function object. We can even get away with assuming
	  // the method takes exactly one argument, since that happens to be true
	  // in every case, so we don't have to touch the arguments object. The
	  // only additional allocation required is the completion record, which
	  // has a stable shape and so hopefully should be cheap to allocate.
	  function tryCatch(fn, obj, arg) {
	    try {
	      return { type: "normal", arg: fn.call(obj, arg) };
	    } catch (err) {
	      return { type: "throw", arg: err };
	    }
	  }

	  var GenStateSuspendedStart = "suspendedStart";
	  var GenStateSuspendedYield = "suspendedYield";
	  var GenStateExecuting = "executing";
	  var GenStateCompleted = "completed";

	  // Returning this object from the innerFn has the same effect as
	  // breaking out of the dispatch switch statement.
	  var ContinueSentinel = {};

	  // Dummy constructor functions that we use as the .constructor and
	  // .constructor.prototype properties for functions that return Generator
	  // objects. For full spec compliance, you may wish to configure your
	  // minifier not to mangle the names of these two functions.
	  function Generator() {}
	  function GeneratorFunction() {}
	  function GeneratorFunctionPrototype() {}

	  // This is a polyfill for %IteratorPrototype% for environments that
	  // don't natively support it.
	  var IteratorPrototype = {};
	  define(IteratorPrototype, iteratorSymbol, function () {
	    return this;
	  });

	  var getProto = Object.getPrototypeOf;
	  var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
	  if (NativeIteratorPrototype &&
	      NativeIteratorPrototype !== Op &&
	      hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
	    // This environment has a native %IteratorPrototype%; use it instead
	    // of the polyfill.
	    IteratorPrototype = NativeIteratorPrototype;
	  }

	  var Gp = GeneratorFunctionPrototype.prototype =
	    Generator.prototype = Object.create(IteratorPrototype);
	  GeneratorFunction.prototype = GeneratorFunctionPrototype;
	  define(Gp, "constructor", GeneratorFunctionPrototype);
	  define(GeneratorFunctionPrototype, "constructor", GeneratorFunction);
	  GeneratorFunction.displayName = define(
	    GeneratorFunctionPrototype,
	    toStringTagSymbol,
	    "GeneratorFunction"
	  );

	  // Helper for defining the .next, .throw, and .return methods of the
	  // Iterator interface in terms of a single ._invoke method.
	  function defineIteratorMethods(prototype) {
	    ["next", "throw", "return"].forEach(function(method) {
	      define(prototype, method, function(arg) {
	        return this._invoke(method, arg);
	      });
	    });
	  }

	  exports.isGeneratorFunction = function(genFun) {
	    var ctor = typeof genFun === "function" && genFun.constructor;
	    return ctor
	      ? ctor === GeneratorFunction ||
	        // For the native GeneratorFunction constructor, the best we can
	        // do is to check its .name property.
	        (ctor.displayName || ctor.name) === "GeneratorFunction"
	      : false;
	  };

	  exports.mark = function(genFun) {
	    if (Object.setPrototypeOf) {
	      Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
	    } else {
	      genFun.__proto__ = GeneratorFunctionPrototype;
	      define(genFun, toStringTagSymbol, "GeneratorFunction");
	    }
	    genFun.prototype = Object.create(Gp);
	    return genFun;
	  };

	  // Within the body of any async function, `await x` is transformed to
	  // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
	  // `hasOwn.call(value, "__await")` to determine if the yielded value is
	  // meant to be awaited.
	  exports.awrap = function(arg) {
	    return { __await: arg };
	  };

	  function AsyncIterator(generator, PromiseImpl) {
	    function invoke(method, arg, resolve, reject) {
	      var record = tryCatch(generator[method], generator, arg);
	      if (record.type === "throw") {
	        reject(record.arg);
	      } else {
	        var result = record.arg;
	        var value = result.value;
	        if (value &&
	            typeof value === "object" &&
	            hasOwn.call(value, "__await")) {
	          return PromiseImpl.resolve(value.__await).then(function(value) {
	            invoke("next", value, resolve, reject);
	          }, function(err) {
	            invoke("throw", err, resolve, reject);
	          });
	        }

	        return PromiseImpl.resolve(value).then(function(unwrapped) {
	          // When a yielded Promise is resolved, its final value becomes
	          // the .value of the Promise<{value,done}> result for the
	          // current iteration.
	          result.value = unwrapped;
	          resolve(result);
	        }, function(error) {
	          // If a rejected Promise was yielded, throw the rejection back
	          // into the async generator function so it can be handled there.
	          return invoke("throw", error, resolve, reject);
	        });
	      }
	    }

	    var previousPromise;

	    function enqueue(method, arg) {
	      function callInvokeWithMethodAndArg() {
	        return new PromiseImpl(function(resolve, reject) {
	          invoke(method, arg, resolve, reject);
	        });
	      }

	      return previousPromise =
	        // If enqueue has been called before, then we want to wait until
	        // all previous Promises have been resolved before calling invoke,
	        // so that results are always delivered in the correct order. If
	        // enqueue has not been called before, then it is important to
	        // call invoke immediately, without waiting on a callback to fire,
	        // so that the async generator function has the opportunity to do
	        // any necessary setup in a predictable way. This predictability
	        // is why the Promise constructor synchronously invokes its
	        // executor callback, and why async functions synchronously
	        // execute code before the first await. Since we implement simple
	        // async functions in terms of async generators, it is especially
	        // important to get this right, even though it requires care.
	        previousPromise ? previousPromise.then(
	          callInvokeWithMethodAndArg,
	          // Avoid propagating failures to Promises returned by later
	          // invocations of the iterator.
	          callInvokeWithMethodAndArg
	        ) : callInvokeWithMethodAndArg();
	    }

	    // Define the unified helper method that is used to implement .next,
	    // .throw, and .return (see defineIteratorMethods).
	    this._invoke = enqueue;
	  }

	  defineIteratorMethods(AsyncIterator.prototype);
	  define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
	    return this;
	  });
	  exports.AsyncIterator = AsyncIterator;

	  // Note that simple async functions are implemented on top of
	  // AsyncIterator objects; they just return a Promise for the value of
	  // the final result produced by the iterator.
	  exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
	    if (PromiseImpl === void 0) PromiseImpl = Promise;

	    var iter = new AsyncIterator(
	      wrap(innerFn, outerFn, self, tryLocsList),
	      PromiseImpl
	    );

	    return exports.isGeneratorFunction(outerFn)
	      ? iter // If outerFn is a generator, return the full iterator.
	      : iter.next().then(function(result) {
	          return result.done ? result.value : iter.next();
	        });
	  };

	  function makeInvokeMethod(innerFn, self, context) {
	    var state = GenStateSuspendedStart;

	    return function invoke(method, arg) {
	      if (state === GenStateExecuting) {
	        throw new Error("Generator is already running");
	      }

	      if (state === GenStateCompleted) {
	        if (method === "throw") {
	          throw arg;
	        }

	        // Be forgiving, per 25.3.3.3.3 of the spec:
	        // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
	        return doneResult();
	      }

	      context.method = method;
	      context.arg = arg;

	      while (true) {
	        var delegate = context.delegate;
	        if (delegate) {
	          var delegateResult = maybeInvokeDelegate(delegate, context);
	          if (delegateResult) {
	            if (delegateResult === ContinueSentinel) continue;
	            return delegateResult;
	          }
	        }

	        if (context.method === "next") {
	          // Setting context._sent for legacy support of Babel's
	          // function.sent implementation.
	          context.sent = context._sent = context.arg;

	        } else if (context.method === "throw") {
	          if (state === GenStateSuspendedStart) {
	            state = GenStateCompleted;
	            throw context.arg;
	          }

	          context.dispatchException(context.arg);

	        } else if (context.method === "return") {
	          context.abrupt("return", context.arg);
	        }

	        state = GenStateExecuting;

	        var record = tryCatch(innerFn, self, context);
	        if (record.type === "normal") {
	          // If an exception is thrown from innerFn, we leave state ===
	          // GenStateExecuting and loop back for another invocation.
	          state = context.done
	            ? GenStateCompleted
	            : GenStateSuspendedYield;

	          if (record.arg === ContinueSentinel) {
	            continue;
	          }

	          return {
	            value: record.arg,
	            done: context.done
	          };

	        } else if (record.type === "throw") {
	          state = GenStateCompleted;
	          // Dispatch the exception by looping back around to the
	          // context.dispatchException(context.arg) call above.
	          context.method = "throw";
	          context.arg = record.arg;
	        }
	      }
	    };
	  }

	  // Call delegate.iterator[context.method](context.arg) and handle the
	  // result, either by returning a { value, done } result from the
	  // delegate iterator, or by modifying context.method and context.arg,
	  // setting context.delegate to null, and returning the ContinueSentinel.
	  function maybeInvokeDelegate(delegate, context) {
	    var method = delegate.iterator[context.method];
	    if (method === undefined$1) {
	      // A .throw or .return when the delegate iterator has no .throw
	      // method always terminates the yield* loop.
	      context.delegate = null;

	      if (context.method === "throw") {
	        // Note: ["return"] must be used for ES3 parsing compatibility.
	        if (delegate.iterator["return"]) {
	          // If the delegate iterator has a return method, give it a
	          // chance to clean up.
	          context.method = "return";
	          context.arg = undefined$1;
	          maybeInvokeDelegate(delegate, context);

	          if (context.method === "throw") {
	            // If maybeInvokeDelegate(context) changed context.method from
	            // "return" to "throw", let that override the TypeError below.
	            return ContinueSentinel;
	          }
	        }

	        context.method = "throw";
	        context.arg = new TypeError(
	          "The iterator does not provide a 'throw' method");
	      }

	      return ContinueSentinel;
	    }

	    var record = tryCatch(method, delegate.iterator, context.arg);

	    if (record.type === "throw") {
	      context.method = "throw";
	      context.arg = record.arg;
	      context.delegate = null;
	      return ContinueSentinel;
	    }

	    var info = record.arg;

	    if (! info) {
	      context.method = "throw";
	      context.arg = new TypeError("iterator result is not an object");
	      context.delegate = null;
	      return ContinueSentinel;
	    }

	    if (info.done) {
	      // Assign the result of the finished delegate to the temporary
	      // variable specified by delegate.resultName (see delegateYield).
	      context[delegate.resultName] = info.value;

	      // Resume execution at the desired location (see delegateYield).
	      context.next = delegate.nextLoc;

	      // If context.method was "throw" but the delegate handled the
	      // exception, let the outer generator proceed normally. If
	      // context.method was "next", forget context.arg since it has been
	      // "consumed" by the delegate iterator. If context.method was
	      // "return", allow the original .return call to continue in the
	      // outer generator.
	      if (context.method !== "return") {
	        context.method = "next";
	        context.arg = undefined$1;
	      }

	    } else {
	      // Re-yield the result returned by the delegate method.
	      return info;
	    }

	    // The delegate iterator is finished, so forget it and continue with
	    // the outer generator.
	    context.delegate = null;
	    return ContinueSentinel;
	  }

	  // Define Generator.prototype.{next,throw,return} in terms of the
	  // unified ._invoke helper method.
	  defineIteratorMethods(Gp);

	  define(Gp, toStringTagSymbol, "Generator");

	  // A Generator should always return itself as the iterator object when the
	  // @@iterator function is called on it. Some browsers' implementations of the
	  // iterator prototype chain incorrectly implement this, causing the Generator
	  // object to not be returned from this call. This ensures that doesn't happen.
	  // See https://github.com/facebook/regenerator/issues/274 for more details.
	  define(Gp, iteratorSymbol, function() {
	    return this;
	  });

	  define(Gp, "toString", function() {
	    return "[object Generator]";
	  });

	  function pushTryEntry(locs) {
	    var entry = { tryLoc: locs[0] };

	    if (1 in locs) {
	      entry.catchLoc = locs[1];
	    }

	    if (2 in locs) {
	      entry.finallyLoc = locs[2];
	      entry.afterLoc = locs[3];
	    }

	    this.tryEntries.push(entry);
	  }

	  function resetTryEntry(entry) {
	    var record = entry.completion || {};
	    record.type = "normal";
	    delete record.arg;
	    entry.completion = record;
	  }

	  function Context(tryLocsList) {
	    // The root entry object (effectively a try statement without a catch
	    // or a finally block) gives us a place to store values thrown from
	    // locations where there is no enclosing try statement.
	    this.tryEntries = [{ tryLoc: "root" }];
	    tryLocsList.forEach(pushTryEntry, this);
	    this.reset(true);
	  }

	  exports.keys = function(object) {
	    var keys = [];
	    for (var key in object) {
	      keys.push(key);
	    }
	    keys.reverse();

	    // Rather than returning an object with a next method, we keep
	    // things simple and return the next function itself.
	    return function next() {
	      while (keys.length) {
	        var key = keys.pop();
	        if (key in object) {
	          next.value = key;
	          next.done = false;
	          return next;
	        }
	      }

	      // To avoid creating an additional object, we just hang the .value
	      // and .done properties off the next function object itself. This
	      // also ensures that the minifier will not anonymize the function.
	      next.done = true;
	      return next;
	    };
	  };

	  function values(iterable) {
	    if (iterable) {
	      var iteratorMethod = iterable[iteratorSymbol];
	      if (iteratorMethod) {
	        return iteratorMethod.call(iterable);
	      }

	      if (typeof iterable.next === "function") {
	        return iterable;
	      }

	      if (!isNaN(iterable.length)) {
	        var i = -1, next = function next() {
	          while (++i < iterable.length) {
	            if (hasOwn.call(iterable, i)) {
	              next.value = iterable[i];
	              next.done = false;
	              return next;
	            }
	          }

	          next.value = undefined$1;
	          next.done = true;

	          return next;
	        };

	        return next.next = next;
	      }
	    }

	    // Return an iterator with no values.
	    return { next: doneResult };
	  }
	  exports.values = values;

	  function doneResult() {
	    return { value: undefined$1, done: true };
	  }

	  Context.prototype = {
	    constructor: Context,

	    reset: function(skipTempReset) {
	      this.prev = 0;
	      this.next = 0;
	      // Resetting context._sent for legacy support of Babel's
	      // function.sent implementation.
	      this.sent = this._sent = undefined$1;
	      this.done = false;
	      this.delegate = null;

	      this.method = "next";
	      this.arg = undefined$1;

	      this.tryEntries.forEach(resetTryEntry);

	      if (!skipTempReset) {
	        for (var name in this) {
	          // Not sure about the optimal order of these conditions:
	          if (name.charAt(0) === "t" &&
	              hasOwn.call(this, name) &&
	              !isNaN(+name.slice(1))) {
	            this[name] = undefined$1;
	          }
	        }
	      }
	    },

	    stop: function() {
	      this.done = true;

	      var rootEntry = this.tryEntries[0];
	      var rootRecord = rootEntry.completion;
	      if (rootRecord.type === "throw") {
	        throw rootRecord.arg;
	      }

	      return this.rval;
	    },

	    dispatchException: function(exception) {
	      if (this.done) {
	        throw exception;
	      }

	      var context = this;
	      function handle(loc, caught) {
	        record.type = "throw";
	        record.arg = exception;
	        context.next = loc;

	        if (caught) {
	          // If the dispatched exception was caught by a catch block,
	          // then let that catch block handle the exception normally.
	          context.method = "next";
	          context.arg = undefined$1;
	        }

	        return !! caught;
	      }

	      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
	        var entry = this.tryEntries[i];
	        var record = entry.completion;

	        if (entry.tryLoc === "root") {
	          // Exception thrown outside of any try block that could handle
	          // it, so set the completion value of the entire function to
	          // throw the exception.
	          return handle("end");
	        }

	        if (entry.tryLoc <= this.prev) {
	          var hasCatch = hasOwn.call(entry, "catchLoc");
	          var hasFinally = hasOwn.call(entry, "finallyLoc");

	          if (hasCatch && hasFinally) {
	            if (this.prev < entry.catchLoc) {
	              return handle(entry.catchLoc, true);
	            } else if (this.prev < entry.finallyLoc) {
	              return handle(entry.finallyLoc);
	            }

	          } else if (hasCatch) {
	            if (this.prev < entry.catchLoc) {
	              return handle(entry.catchLoc, true);
	            }

	          } else if (hasFinally) {
	            if (this.prev < entry.finallyLoc) {
	              return handle(entry.finallyLoc);
	            }

	          } else {
	            throw new Error("try statement without catch or finally");
	          }
	        }
	      }
	    },

	    abrupt: function(type, arg) {
	      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
	        var entry = this.tryEntries[i];
	        if (entry.tryLoc <= this.prev &&
	            hasOwn.call(entry, "finallyLoc") &&
	            this.prev < entry.finallyLoc) {
	          var finallyEntry = entry;
	          break;
	        }
	      }

	      if (finallyEntry &&
	          (type === "break" ||
	           type === "continue") &&
	          finallyEntry.tryLoc <= arg &&
	          arg <= finallyEntry.finallyLoc) {
	        // Ignore the finally entry if control is not jumping to a
	        // location outside the try/catch block.
	        finallyEntry = null;
	      }

	      var record = finallyEntry ? finallyEntry.completion : {};
	      record.type = type;
	      record.arg = arg;

	      if (finallyEntry) {
	        this.method = "next";
	        this.next = finallyEntry.finallyLoc;
	        return ContinueSentinel;
	      }

	      return this.complete(record);
	    },

	    complete: function(record, afterLoc) {
	      if (record.type === "throw") {
	        throw record.arg;
	      }

	      if (record.type === "break" ||
	          record.type === "continue") {
	        this.next = record.arg;
	      } else if (record.type === "return") {
	        this.rval = this.arg = record.arg;
	        this.method = "return";
	        this.next = "end";
	      } else if (record.type === "normal" && afterLoc) {
	        this.next = afterLoc;
	      }

	      return ContinueSentinel;
	    },

	    finish: function(finallyLoc) {
	      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
	        var entry = this.tryEntries[i];
	        if (entry.finallyLoc === finallyLoc) {
	          this.complete(entry.completion, entry.afterLoc);
	          resetTryEntry(entry);
	          return ContinueSentinel;
	        }
	      }
	    },

	    "catch": function(tryLoc) {
	      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
	        var entry = this.tryEntries[i];
	        if (entry.tryLoc === tryLoc) {
	          var record = entry.completion;
	          if (record.type === "throw") {
	            var thrown = record.arg;
	            resetTryEntry(entry);
	          }
	          return thrown;
	        }
	      }

	      // The context.catch method must only be called with a location
	      // argument that corresponds to a known catch block.
	      throw new Error("illegal catch attempt");
	    },

	    delegateYield: function(iterable, resultName, nextLoc) {
	      this.delegate = {
	        iterator: values(iterable),
	        resultName: resultName,
	        nextLoc: nextLoc
	      };

	      if (this.method === "next") {
	        // Deliberately forget the last sent value so that we don't
	        // accidentally pass it on to the delegate.
	        this.arg = undefined$1;
	      }

	      return ContinueSentinel;
	    }
	  };

	  // Regardless of whether this script is executing as a CommonJS module
	  // or not, return the runtime object so that we can declare the variable
	  // regeneratorRuntime in the outer scope, which allows this module to be
	  // injected easily by `bin/regenerator --include-runtime script.js`.
	  return exports;

	}(
	  // If this script is executing as a CommonJS module, use module.exports
	  // as the regeneratorRuntime namespace. Otherwise create a new empty
	  // object. Either way, the resulting object will be used to initialize
	  // the regeneratorRuntime variable at the top of this file.
	  module.exports 
	));

	try {
	  regeneratorRuntime = runtime;
	} catch (accidentalStrictMode) {
	  // This module should not be running in strict mode, so the above
	  // assignment should always work unless something is misconfigured. Just
	  // in case runtime.js accidentally runs in strict mode, in modern engines
	  // we can explicitly access globalThis. In older engines we can escape
	  // strict mode using a global Function call. This could conceivably fail
	  // if a Content Security Policy forbids using Function, but in that case
	  // the proper solution is to fix the accidental strict mode problem. If
	  // you've misconfigured your bundler to force strict mode and applied a
	  // CSP to forbid Function, and you're not willing to fix either of those
	  // problems, please detail your unique predicament in a GitHub issue.
	  if (typeof globalThis === "object") {
	    globalThis.regeneratorRuntime = runtime;
	  } else {
	    Function("r", "regeneratorRuntime = r")(runtime);
	  }
	}
} (runtime));

function ownKeys(object, enumerableOnly) {
  var keys = Object.keys(object);

  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    enumerableOnly && (symbols = symbols.filter(function (sym) {
      return Object.getOwnPropertyDescriptor(object, sym).enumerable;
    })), keys.push.apply(keys, symbols);
  }

  return keys;
}

function _objectSpread2(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
      _defineProperty$2(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }

  return target;
}

function _defineProperty$2(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function _extends$4() {
  _extends$4 = Object.assign || function (target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];

      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }

    return target;
  };

  return _extends$4.apply(this, arguments);
}

function _objectWithoutPropertiesLoose$1(source, excluded) {
  if (source == null) return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i;

  for (i = 0; i < sourceKeys.length; i++) {
    key = sourceKeys[i];
    if (excluded.indexOf(key) >= 0) continue;
    target[key] = source[key];
  }

  return target;
}

function _objectWithoutProperties$1(source, excluded) {
  if (source == null) return {};

  var target = _objectWithoutPropertiesLoose$1(source, excluded);

  var key, i;

  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);

    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key = sourceSymbolKeys[i];
      if (excluded.indexOf(key) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
      target[key] = source[key];
    }
  }

  return target;
}

const format = function () {
  let message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  let args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  const arr = typeof args === 'string' || typeof args === 'number' ? [args] : args;
  return message.replace(/\{(\d+)\}/g, (match, number) => typeof arr[number] !== 'undefined' ? arr[number] : match);
};

function translator() {
  let {
    initial = 'en-US',
    fallback = 'en-US'
  } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  const dictionaries = {};
  let currentLocale = initial;
  /**
   * @class Translator
   */

  const api =
  /** @lends Translator# */
  {
    language: lang => {
      if (lang) {
        currentLocale = lang;
      }

      return currentLocale;
    },

    /**
     * Registers a string in multiple locales
     * @param {object} item
     * @param {string} item.id
     * @param {object<string,string>} item.locale
     * @example
     * translator.add({
     *   id: 'company.hello_user',
     *   locale: {
     *     'en-US': 'Hello {0}',
     *     'sv-SE': 'Hej {0}'
     *   }
     * });
     * translator.get('company.hello_user', ['John']); // Hello John
     */
    add: item => {
      // TODO - disallow override?
      const {
        id,
        locale
      } = item;
      Object.keys(locale).forEach(lang => {
        if (!dictionaries[lang]) {
          dictionaries[lang] = {};
        }

        dictionaries[lang][id] = locale[lang];
      });
    },

    /**
     * Translates a string for current locale.
     * @param {string} str - ID of the registered string.
     * @param {Array<string>=} args - Values passed down for string interpolation.
     * @returns {string} The translated string.
     */
    get(str, args) {
      let v;

      if (dictionaries[currentLocale] && typeof dictionaries[currentLocale][str] !== 'undefined') {
        v = dictionaries[currentLocale][str];
      } else if (dictionaries[fallback] && typeof dictionaries[fallback][str] !== 'undefined') {
        v = dictionaries[fallback][str];
      } else {
        v = str;
      }

      return typeof args !== 'undefined' ? format(v, args) : v;
    }

  };
  return api;
}

const locale = function () {
  let {
    initial = 'en-US',
    fallback = 'en-US'
  } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  const t = translator({
    initial,
    fallback
  });
  return {
    translator: t
  };
};

var Cancel$1 = {
	id: "Cancel",
	locale: {
		"de-DE": "Abbrechen",
		"en-US": "Cancel",
		"es-ES": "Cancelar",
		"fr-FR": "Annuler",
		"it-IT": "Annulla",
		"ja-JP": "キャンセル",
		"ko-KR": "취소",
		"nl-NL": "Annuleren",
		"pl-PL": "Anuluj",
		"pt-BR": "Cancelar",
		"ru-RU": "Отмена",
		"sv-SE": "Avbryt",
		"tr-TR": "İptal",
		"zh-CN": "取消",
		"zh-TW": "取消"
	}
};
var CurrentSelections_All = {
	id: "CurrentSelections.All",
	locale: {
		"de-DE": "ALLES",
		"en-US": "ALL",
		"es-ES": "TODOS",
		"fr-FR": "TOUS",
		"it-IT": "TUTTI",
		"ja-JP": "すべて",
		"ko-KR": "모두",
		"nl-NL": "ALLE",
		"pl-PL": "WSZYSTKO",
		"pt-BR": "TODOS",
		"ru-RU": "ВСЕ",
		"sv-SE": "ALLA",
		"tr-TR": "TÜMÜ",
		"zh-CN": "全部",
		"zh-TW": "全部"
	}
};
var CurrentSelections_Of = {
	id: "CurrentSelections.Of",
	locale: {
		"de-DE": "{0} von {1}",
		"en-US": "{0} of {1}",
		"es-ES": "{0} de {1}",
		"fr-FR": "{0} sur {1}",
		"it-IT": "{0} di {1}",
		"ja-JP": "{0}/ {1}",
		"ko-KR": "{0} / {1}",
		"nl-NL": "{0} van {1}",
		"pl-PL": "{0} z {1}",
		"pt-BR": "{0} de {1}",
		"ru-RU": "{0} из {1}",
		"sv-SE": "{0} av {1}",
		"tr-TR": "{0} / {1}",
		"zh-CN": "{0}/ {1}",
		"zh-TW": "{0}/ {1}"
	}
};
var Listbox_Lock = {
	id: "Listbox.Lock",
	locale: {
		"de-DE": "Auswahlen sperren",
		"en-US": "Lock selections",
		"es-ES": "Bloquear selecciones",
		"fr-FR": "Verrouiller les sélections",
		"it-IT": "Blocca selezioni",
		"ja-JP": "選択をロック",
		"ko-KR": "선택 내용 잠금",
		"nl-NL": "Selecties vergrendelen",
		"pl-PL": "Zablokuj wybory",
		"pt-BR": "Bloquear seleções",
		"ru-RU": "Заблокировать выборки",
		"sv-SE": "Lås urval",
		"tr-TR": "Seçimleri kilitle",
		"zh-CN": "锁定选择项",
		"zh-TW": "鎖定選項"
	}
};
var Listbox_Search = {
	id: "Listbox.Search",
	locale: {
		"de-DE": "In Listenfeld suchen",
		"en-US": "Search in listbox",
		"es-ES": "Buscar en cuadro de lista",
		"fr-FR": "Rechercher dans la liste de sélection",
		"it-IT": "Cerca nella casella di elenco",
		"ja-JP": "リストボックス内を検索",
		"ko-KR": "목록 상자에서 검색",
		"nl-NL": "Zoeken in keuzelijst",
		"pl-PL": "Wyszukaj w liście wartości",
		"pt-BR": "Pesquisar na caixa de listagem",
		"ru-RU": "Поиск в списке",
		"sv-SE": "Sök i listruta",
		"tr-TR": "Liste kutusunda ara",
		"zh-CN": "在列表框中搜索",
		"zh-TW": "在清單方塊中搜尋"
	}
};
var Listbox_Unlock = {
	id: "Listbox.Unlock",
	locale: {
		"de-DE": "Auswahlen entsperren",
		"en-US": "Unlock selections",
		"es-ES": "Desbloquear selecciones",
		"fr-FR": "Déverrouiller les sélections",
		"it-IT": "Sblocca selezioni",
		"ja-JP": "選択をロック解除",
		"ko-KR": "선택 내용 잠금 해제",
		"nl-NL": "Selecties ontgrendelen",
		"pl-PL": "Odblokuj wybory",
		"pt-BR": "Desbloquear seleções",
		"ru-RU": "Разблокировать выборки",
		"sv-SE": "Lås upp urval",
		"tr-TR": "Seçimlerin kilidini aç",
		"zh-CN": "将选择项解锁",
		"zh-TW": "解鎖選項"
	}
};
var Menu_More = {
	id: "Menu.More",
	locale: {
		"de-DE": "Mehr",
		"en-US": "More",
		"es-ES": "Más",
		"fr-FR": "Plus",
		"it-IT": "Altro",
		"ja-JP": "詳細",
		"ko-KR": "자세히",
		"nl-NL": "Meer",
		"pl-PL": "Więcej",
		"pt-BR": "Mais",
		"ru-RU": "Дополнительно",
		"sv-SE": "Mer",
		"tr-TR": "Daha fazla",
		"zh-CN": "更多",
		"zh-TW": "更多"
	}
};
var Navigate_Back = {
	id: "Navigate.Back",
	locale: {
		"de-DE": "Schritt zurück",
		"en-US": "Step back",
		"es-ES": "Atrás",
		"fr-FR": "Retour en arrière",
		"it-IT": "Torna indietro",
		"ja-JP": "1 段階戻る",
		"ko-KR": "이전 단계",
		"nl-NL": "Stap terug",
		"pl-PL": "Krok do tyłu",
		"pt-BR": "Voltar uma etapa",
		"ru-RU": "Шаг назад",
		"sv-SE": "Gå bakåt",
		"tr-TR": "Bir adım geri",
		"zh-CN": "后退",
		"zh-TW": "倒退"
	}
};
var Navigate_Forward = {
	id: "Navigate.Forward",
	locale: {
		"de-DE": "Schritt vor",
		"en-US": "Step forward",
		"es-ES": "Avanzar",
		"fr-FR": "Étape suivante",
		"it-IT": "Vai avanti",
		"ja-JP": "1段階進む",
		"ko-KR": "다음 단계",
		"nl-NL": "Stap vooruit",
		"pl-PL": "Krok do przodu",
		"pt-BR": "Avançar uma etapa",
		"ru-RU": "Шаг вперед",
		"sv-SE": "Gå framåt",
		"tr-TR": "Bir adım ileri",
		"zh-CN": "前进",
		"zh-TW": "前進"
	}
};
var OK = {
	id: "OK",
	locale: {
		"de-DE": "OK",
		"en-US": "OK",
		"es-ES": "Aceptar",
		"fr-FR": "OK",
		"it-IT": "OK",
		"ja-JP": "OK",
		"ko-KR": "확인",
		"nl-NL": "OK",
		"pl-PL": "OK",
		"pt-BR": "OK",
		"ru-RU": "ОК",
		"sv-SE": "OK",
		"tr-TR": "Tamam",
		"zh-CN": "确定",
		"zh-TW": "確定"
	}
};
var Object_Update_Active = {
	id: "Object.Update.Active",
	locale: {
		"de-DE": "Laden von Daten",
		"en-US": "Updating data",
		"es-ES": "Cargando datos",
		"fr-FR": "Chargement de données en cours",
		"it-IT": "Caricamento dati in corso",
		"ja-JP": "データのロード中",
		"ko-KR": "데이터 로드 중",
		"nl-NL": "Gegevens worden geladen",
		"pl-PL": "Ładowanie danych",
		"pt-BR": "Carregando dados",
		"ru-RU": "Загрузка данных",
		"sv-SE": "Laddar data",
		"tr-TR": "Veriler yükleniyor",
		"zh-CN": "加载数据",
		"zh-TW": "正在載入資料"
	}
};
var Object_Update_Cancelled = {
	id: "Object.Update.Cancelled",
	locale: {
		"de-DE": "Datenaktualisierung wurde abgebrochen",
		"en-US": "Data update was cancelled",
		"es-ES": "Se ha cancelado la actualización de datos",
		"fr-FR": "Mise à jour des données annulée",
		"it-IT": "Aggiornamento dati annullato",
		"ja-JP": "データの更新がキャンセルされました",
		"ko-KR": "데이터 업데이트가 취소되었습니다.",
		"nl-NL": "Gegevensupdate is geannuleerd",
		"pl-PL": "Aktualizacja danych została anulowana",
		"pt-BR": "A atualização de dados foi cancelada",
		"ru-RU": "Обновление данных отменено",
		"sv-SE": "Datauppdateringen avbröts.",
		"tr-TR": "Veri güncelleştirme iptal edildi",
		"zh-CN": "数据更新已取消",
		"zh-TW": "資料更新已取消"
	}
};
var Retry$1 = {
	id: "Retry",
	locale: {
		"de-DE": "Wiederholen",
		"en-US": "Retry",
		"es-ES": "Intentar de nuevo",
		"fr-FR": "Réessayer",
		"it-IT": "Riprova",
		"ja-JP": "再試行",
		"ko-KR": "다시 시도",
		"nl-NL": "Opnieuw",
		"pl-PL": "Ponów próbę",
		"pt-BR": "Tentar novamente",
		"ru-RU": "Повторить попытку",
		"sv-SE": "Försök igen",
		"tr-TR": "Yeniden dene",
		"zh-CN": "重试",
		"zh-TW": "重試"
	}
};
var Selection_Cancel = {
	id: "Selection.Cancel",
	locale: {
		"de-DE": "Auswahl abbrechen",
		"en-US": "Cancel selection",
		"es-ES": "Cancelar selección",
		"fr-FR": "Annuler la sélection",
		"it-IT": "Annulla selezione",
		"ja-JP": "選択のキャンセル",
		"ko-KR": "선택 취소",
		"nl-NL": "Selectie annuleren",
		"pl-PL": "Anuluj selekcję",
		"pt-BR": "Cancelar seleção",
		"ru-RU": "Отменить выборку",
		"sv-SE": "Avbryt urval",
		"tr-TR": "Seçimi iptal et",
		"zh-CN": "取消选择",
		"zh-TW": "取消選取"
	}
};
var Selection_Clear = {
	id: "Selection.Clear",
	locale: {
		"de-DE": "Auswahl löschen",
		"en-US": "Clear selection",
		"es-ES": "Borrar selección",
		"fr-FR": "Effacer la sélection",
		"it-IT": "Cancella selezione",
		"ja-JP": "選択をクリア",
		"ko-KR": "선택 해제",
		"nl-NL": "Selectie wissen",
		"pl-PL": "Wyczyść selekcję",
		"pt-BR": "Limpar seleção",
		"ru-RU": "Очистить выбор",
		"sv-SE": "Rensa urval",
		"tr-TR": "Seçimi temizle",
		"zh-CN": "清除选择",
		"zh-TW": "清除選項"
	}
};
var Selection_ClearAll = {
	id: "Selection.ClearAll",
	locale: {
		"de-DE": "Alle Auswahlen löschen",
		"en-US": "Clear all selections",
		"es-ES": "Borrar todas las selecciones",
		"fr-FR": "Effacer toutes les sélections",
		"it-IT": "Cancella tutte le selezioni",
		"ja-JP": "選択をすべてクリアする",
		"ko-KR": "모든 선택 해제",
		"nl-NL": "Alle selecties wissen",
		"pl-PL": "Wyczyść wszystkie selekcje",
		"pt-BR": "Limpar todas as seleções",
		"ru-RU": "Очистить от всех выборок",
		"sv-SE": "Radera alla urval",
		"tr-TR": "Tüm seçimleri temizle",
		"zh-CN": "清除所有选择项",
		"zh-TW": "清除所有選項"
	}
};
var Selection_ClearAllStates = {
	id: "Selection.ClearAllStates",
	locale: {
		"de-DE": "Alle Status löschen",
		"en-US": "Clear all states",
		"es-ES": "Borrar todos los estados",
		"fr-FR": "Effacer tous les états",
		"it-IT": "Cancella tutti gli stati",
		"ja-JP": "全ステートをクリア",
		"ko-KR": "모든 상태 지우기",
		"nl-NL": "Alle states wissen",
		"pl-PL": "Wyczyść wszystkie stany",
		"pt-BR": "Limpar todos os estados",
		"ru-RU": "Очистить все состояния",
		"sv-SE": "Rensa alla tillstånd",
		"tr-TR": "Tüm durumları temizle",
		"zh-CN": "清除所有状态",
		"zh-TW": "清除所有狀態"
	}
};
var Selection_Confirm = {
	id: "Selection.Confirm",
	locale: {
		"de-DE": "Auswahl bestätigen",
		"en-US": "Confirm selection",
		"es-ES": "Confirmar selección",
		"fr-FR": "Confirmer la sélection",
		"it-IT": "Conferma selezione",
		"ja-JP": "選択の確認",
		"ko-KR": "선택 확인",
		"nl-NL": "Selectie bevestigen",
		"pl-PL": "Potwierdź selekcję",
		"pt-BR": "Confirmar seleção",
		"ru-RU": "Подтвердить выборку",
		"sv-SE": "Bekräfta urval",
		"tr-TR": "Seçimi onayla",
		"zh-CN": "确认选择",
		"zh-TW": "確認選取"
	}
};
var Selection_Menu = {
	id: "Selection.Menu",
	locale: {
		"de-DE": "Auswahlmenü",
		"en-US": "Selection menu",
		"es-ES": "Menú de selección",
		"fr-FR": "Menu Sélection",
		"it-IT": "Menu Selezione",
		"ja-JP": "選択メニュー",
		"ko-KR": "선택 메뉴",
		"nl-NL": "Selectiemenu",
		"pl-PL": "Menu selekcji",
		"pt-BR": "Menu de seleção",
		"ru-RU": "Меню \"Выборка\"",
		"sv-SE": "Urvalsmeny",
		"tr-TR": "Seçim menüsü",
		"zh-CN": "选择菜单",
		"zh-TW": "選項功能表"
	}
};
var Selection_SelectAll = {
	id: "Selection.SelectAll",
	locale: {
		"de-DE": "Alle auswählen",
		"en-US": "Select all",
		"es-ES": "Seleccionar todo",
		"fr-FR": "Sélectionner tout",
		"it-IT": "Seleziona tutto",
		"ja-JP": "すべて選択",
		"ko-KR": "모두 선택",
		"nl-NL": "Alles selecteren",
		"pl-PL": "Wybierz wszystko",
		"pt-BR": "Selecionar todos",
		"ru-RU": "Выбрать все",
		"sv-SE": "Välj alla",
		"tr-TR": "Tümünü seç",
		"zh-CN": "全选",
		"zh-TW": "全選"
	}
};
var Selection_SelectAlternative = {
	id: "Selection.SelectAlternative",
	locale: {
		"de-DE": "Alternative Werte auswählen",
		"en-US": "Select alternative",
		"es-ES": "Seleccionar alternativos",
		"fr-FR": "Sélectionner des valeurs alternatives",
		"it-IT": "Seleziona alternativi",
		"ja-JP": "代替値を選択",
		"ko-KR": "대안 선택",
		"nl-NL": "Alternatief selecteren",
		"pl-PL": "Wybierz alternatywę",
		"pt-BR": "Selecionar alternativa",
		"ru-RU": "Выбрать альтернативные",
		"sv-SE": "Välj alternativ",
		"tr-TR": "Alternatifi seç",
		"zh-CN": "选择替代项",
		"zh-TW": "選取替代選項"
	}
};
var Selection_SelectExcluded = {
	id: "Selection.SelectExcluded",
	locale: {
		"de-DE": "Ausgeschlossene Werte auswählen",
		"en-US": "Select excluded",
		"es-ES": "Seleccionar excluidos",
		"fr-FR": "Sélectionner les valeurs exclues",
		"it-IT": "Seleziona esclusi",
		"ja-JP": "除外値を選択",
		"ko-KR": "제외 항목 선택",
		"nl-NL": "Uitgesloten waarden selecteren",
		"pl-PL": "Wybierz wykluczone",
		"pt-BR": "Selecionar excluído",
		"ru-RU": "Выбрать исключенные",
		"sv-SE": "Välj uteslutna",
		"tr-TR": "Hariç tutulanı seç",
		"zh-CN": "选择排除项",
		"zh-TW": "選取排除值"
	}
};
var Selection_SelectPossible = {
	id: "Selection.SelectPossible",
	locale: {
		"de-DE": "Wählbare Werte auswählen",
		"en-US": "Select possible",
		"es-ES": "Seleccionar posibles",
		"fr-FR": "Sélectionner les valeurs possibles",
		"it-IT": "Seleziona possibili",
		"ja-JP": "絞込値を選択",
		"ko-KR": "사용 가능 항목 선택",
		"nl-NL": "Mogelijke waarden selecteren",
		"pl-PL": "Wybierz możliwe",
		"pt-BR": "Selecionar possível",
		"ru-RU": "Выбрать возможные",
		"sv-SE": "Välj möjliga",
		"tr-TR": "Olasıyı seç",
		"zh-CN": "选择可能值",
		"zh-TW": "選取可能值"
	}
};
var Visualization_Incomplete = {
	id: "Visualization.Incomplete",
	locale: {
		"de-DE": "Unvollständige Visualisierung",
		"en-US": "Incomplete visualization",
		"es-ES": "Visualización incompleta",
		"fr-FR": "Visualisation incomplète",
		"it-IT": "Visualizzazione incompleta",
		"ja-JP": "未完了のビジュアライゼーション",
		"ko-KR": "완료되지 않은 시각화",
		"nl-NL": "Onvolledige visualisatie",
		"pl-PL": "Niekompletna wizualizacja",
		"pt-BR": "Visualização incompleta",
		"ru-RU": "Незавершенная визуализация",
		"sv-SE": "Ofullständig visualisering",
		"tr-TR": "Tamamlanmamış görselleştirme",
		"zh-CN": "不完整的可视化",
		"zh-TW": "視覺化未完成"
	}
};
var Visualization_Incomplete_Dimensions = {
	id: "Visualization.Incomplete.Dimensions",
	locale: {
		"de-DE": "{0} von {1} Dimensionen",
		"en-US": "{0} of {1} dimensions",
		"es-ES": "{0} de {1} dimensiones",
		"fr-FR": "{0} dimensions sur {1}",
		"it-IT": "{0} di {1} dimensioni",
		"ja-JP": "{0} / {1} 軸",
		"ko-KR": "{1} 차원의 {0}",
		"nl-NL": "{0} van {1} dimensies",
		"pl-PL": "{0} z {1} wymiarów",
		"pt-BR": "{0} de {1} dimensões",
		"ru-RU": "Измерения: {0} из {1}",
		"sv-SE": "{0} av {1} dimensioner",
		"tr-TR": "{0}/{1} boyut",
		"zh-CN": "{0} / {1} 个维度",
		"zh-TW": "{1} 個維度中的 {0} 個"
	}
};
var Visualization_Incomplete_Measures = {
	id: "Visualization.Incomplete.Measures",
	locale: {
		"de-DE": "{0} von {1} Kennzahlen",
		"en-US": "{0} of {1} measures",
		"es-ES": "{0} de {1} medidas",
		"fr-FR": "{0} mesures sur {1}",
		"it-IT": "{0} di {1} misure",
		"ja-JP": "{0} / {1} メジャー",
		"ko-KR": "{1} 측정값의 {0}",
		"nl-NL": "{0} van {1} metingen",
		"pl-PL": "{0} z {1} miar",
		"pt-BR": "{0} de {1} medidas",
		"ru-RU": "Меры: {0} из {1}",
		"sv-SE": "{0} av {1} mått",
		"tr-TR": "{0}/{1} hesaplama",
		"zh-CN": "{0} / {1} 个度量",
		"zh-TW": "{1} 個量值中的 {0} 個"
	}
};
var Visualization_Invalid_Dimension = {
	id: "Visualization.Invalid.Dimension",
	locale: {
		"de-DE": "Ungültige Dimension",
		"en-US": "Invalid dimension",
		"es-ES": "Dimensión no válida",
		"fr-FR": "Dimension non valide",
		"it-IT": "Dimensione non valida",
		"ja-JP": "無効な軸です",
		"ko-KR": "잘못된 차원",
		"nl-NL": "Ongeldige dimensie",
		"pl-PL": "Nieprawidłowy wymiar",
		"pt-BR": "Dimensão inválida",
		"ru-RU": "Недопустимое измерение",
		"sv-SE": "Ogiltig dimension",
		"tr-TR": "Geçersiz boyut",
		"zh-CN": "无效维度",
		"zh-TW": "維度無效"
	}
};
var Visualization_Invalid_Measure = {
	id: "Visualization.Invalid.Measure",
	locale: {
		"de-DE": "Ungültige Kennzahl",
		"en-US": "Invalid measure",
		"es-ES": "Medida no válida",
		"fr-FR": "Mesure non valide",
		"it-IT": "Misura non valida",
		"ja-JP": "無効なメジャーです",
		"ko-KR": "잘못된 측정값",
		"nl-NL": "Ongeldige meting",
		"pl-PL": "Nieprawidłowa miara",
		"pt-BR": "Medida inválida",
		"ru-RU": "Недопустимая мера",
		"sv-SE": "Ogiltigt mått",
		"tr-TR": "Geçersiz hesaplama",
		"zh-CN": "无效度量项",
		"zh-TW": "量值無效"
	}
};
var Visualization_LayoutError = {
	id: "Visualization.LayoutError",
	locale: {
		"de-DE": "Fehler",
		"en-US": "Error",
		"es-ES": "Error",
		"fr-FR": "Erreur",
		"it-IT": "Errore",
		"ja-JP": "エラー",
		"ko-KR": "오류",
		"nl-NL": "Fout",
		"pl-PL": "Błąd",
		"pt-BR": "Erro",
		"ru-RU": "Ошибка",
		"sv-SE": "Fel",
		"tr-TR": "Hata",
		"zh-CN": "错误",
		"zh-TW": "錯誤"
	}
};
var Visualization_UnfulfilledCalculationCondition = {
	id: "Visualization.UnfulfilledCalculationCondition",
	locale: {
		"de-DE": "Die Berechnungsbedingung ist nicht erfüllt",
		"en-US": "The calculation condition is not fulfilled",
		"es-ES": "La condición de cálculo no se cumple",
		"fr-FR": "Condition de calcul non remplie",
		"it-IT": "La condizione di calcolo non è soddisfatta",
		"ja-JP": "演算実行条件が満たされていません",
		"ko-KR": "계산 조건이 충족되지 않았습니다.",
		"nl-NL": "Er is niet aan de berekeningsvoorwaarde voldaan",
		"pl-PL": "Warunek obliczenia nie jest spełniony",
		"pt-BR": "A condição de cálculo não foi atendida",
		"ru-RU": "Условие вычисления не выполнено",
		"sv-SE": "Beräkningsvillkoret uppfylls inte",
		"tr-TR": "Hesaplama koşulu yerine getirilmedi",
		"zh-CN": "不满足计算条件",
		"zh-TW": "不符計算條件"
	}
};
var all = {
	Cancel: Cancel$1,
	CurrentSelections_All: CurrentSelections_All,
	CurrentSelections_Of: CurrentSelections_Of,
	Listbox_Lock: Listbox_Lock,
	Listbox_Search: Listbox_Search,
	Listbox_Unlock: Listbox_Unlock,
	Menu_More: Menu_More,
	Navigate_Back: Navigate_Back,
	Navigate_Forward: Navigate_Forward,
	OK: OK,
	Object_Update_Active: Object_Update_Active,
	Object_Update_Cancelled: Object_Update_Cancelled,
	Retry: Retry$1,
	Selection_Cancel: Selection_Cancel,
	Selection_Clear: Selection_Clear,
	Selection_ClearAll: Selection_ClearAll,
	Selection_ClearAllStates: Selection_ClearAllStates,
	Selection_Confirm: Selection_Confirm,
	Selection_Menu: Selection_Menu,
	Selection_SelectAll: Selection_SelectAll,
	Selection_SelectAlternative: Selection_SelectAlternative,
	Selection_SelectExcluded: Selection_SelectExcluded,
	Selection_SelectPossible: Selection_SelectPossible,
	Visualization_Incomplete: Visualization_Incomplete,
	Visualization_Incomplete_Dimensions: Visualization_Incomplete_Dimensions,
	Visualization_Incomplete_Measures: Visualization_Incomplete_Measures,
	Visualization_Invalid_Dimension: Visualization_Invalid_Dimension,
	Visualization_Invalid_Measure: Visualization_Invalid_Measure,
	Visualization_LayoutError: Visualization_LayoutError,
	Visualization_UnfulfilledCalculationCondition: Visualization_UnfulfilledCalculationCondition
};

function appLocaleFn(language) {
  const l = locale({
    initial: language
  });
  Object.keys(all).forEach(key => {
    l.translator.add(all[key]);
  });
  return {
    translator: l.translator
  };
}

/**
 * Utility functions
 */

var util = {};

util.isObject = function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
};

util.isNumber = function isNumber(arg) {
  return typeof arg === 'number';
};

util.isUndefined = function isUndefined(arg) {
  return arg === void 0;
};

util.isFunction = function isFunction(arg){
  return typeof arg === 'function';
};


/**
 * EventEmitter class
 */

function EventEmitter() {
  EventEmitter.init.call(this);
}
var nodeEventEmitter = EventEmitter;

// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;

EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;

// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;

EventEmitter.init = function() {
  this._events = this._events || {};
  this._maxListeners = this._maxListeners || undefined;
};

// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
  if (!util.isNumber(n) || n < 0 || isNaN(n))
    throw TypeError('n must be a positive number');
  this._maxListeners = n;
  return this;
};

EventEmitter.prototype.emit = function(type) {
  var er, handler, len, args, i, listeners;

  if (!this._events)
    this._events = {};

  // If there is no 'error' event listener then throw.
  if (type === 'error' && !this._events.error) {
    er = arguments[1];
    if (er instanceof Error) {
      throw er; // Unhandled 'error' event
    } else {
      throw Error('Uncaught, unspecified "error" event.');
    }
  }

  handler = this._events[type];

  if (util.isUndefined(handler))
    return false;

  if (util.isFunction(handler)) {
    switch (arguments.length) {
      // fast cases
      case 1:
        handler.call(this);
        break;
      case 2:
        handler.call(this, arguments[1]);
        break;
      case 3:
        handler.call(this, arguments[1], arguments[2]);
        break;
      // slower
      default:
        len = arguments.length;
        args = new Array(len - 1);
        for (i = 1; i < len; i++)
          args[i - 1] = arguments[i];
        handler.apply(this, args);
    }
  } else if (util.isObject(handler)) {
    len = arguments.length;
    args = new Array(len - 1);
    for (i = 1; i < len; i++)
      args[i - 1] = arguments[i];

    listeners = handler.slice();
    len = listeners.length;
    for (i = 0; i < len; i++)
      listeners[i].apply(this, args);
  }

  return true;
};

EventEmitter.prototype.addListener = function(type, listener) {
  var m;

  if (!util.isFunction(listener))
    throw TypeError('listener must be a function');

  if (!this._events)
    this._events = {};

  // To avoid recursion in the case that type === "newListener"! Before
  // adding it to the listeners, first emit "newListener".
  if (this._events.newListener)
    this.emit('newListener', type,
              util.isFunction(listener.listener) ?
              listener.listener : listener);

  if (!this._events[type])
    // Optimize the case of one listener. Don't need the extra array object.
    this._events[type] = listener;
  else if (util.isObject(this._events[type]))
    // If we've already got an array, just append.
    this._events[type].push(listener);
  else
    // Adding the second element, need to change to array.
    this._events[type] = [this._events[type], listener];

  // Check for listener leak
  if (util.isObject(this._events[type]) && !this._events[type].warned) {
    var m;
    if (!util.isUndefined(this._maxListeners)) {
      m = this._maxListeners;
    } else {
      m = EventEmitter.defaultMaxListeners;
    }

    if (m && m > 0 && this._events[type].length > m) {
      this._events[type].warned = true;

      if (util.isFunction(console.error)) {
        console.error('(node) warning: possible EventEmitter memory ' +
                      'leak detected. %d listeners added. ' +
                      'Use emitter.setMaxListeners() to increase limit.',
                      this._events[type].length);
      }
      if (util.isFunction(console.trace))
        console.trace();
    }
  }

  return this;
};

EventEmitter.prototype.on = EventEmitter.prototype.addListener;

EventEmitter.prototype.once = function(type, listener) {
  if (!util.isFunction(listener))
    throw TypeError('listener must be a function');

  var fired = false;

  function g() {
    this.removeListener(type, g);

    if (!fired) {
      fired = true;
      listener.apply(this, arguments);
    }
  }

  g.listener = listener;
  this.on(type, g);

  return this;
};

// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
  var list, position, length, i;

  if (!util.isFunction(listener))
    throw TypeError('listener must be a function');

  if (!this._events || !this._events[type])
    return this;

  list = this._events[type];
  length = list.length;
  position = -1;

  if (list === listener ||
      (util.isFunction(list.listener) && list.listener === listener)) {
    delete this._events[type];
    if (this._events.removeListener)
      this.emit('removeListener', type, listener);

  } else if (util.isObject(list)) {
    for (i = length; i-- > 0;) {
      if (list[i] === listener ||
          (list[i].listener && list[i].listener === listener)) {
        position = i;
        break;
      }
    }

    if (position < 0)
      return this;

    if (list.length === 1) {
      list.length = 0;
      delete this._events[type];
    } else {
      list.splice(position, 1);
    }

    if (this._events.removeListener)
      this.emit('removeListener', type, listener);
  }

  return this;
};

EventEmitter.prototype.removeAllListeners = function(type) {
  var key, listeners;

  if (!this._events)
    return this;

  // not listening for removeListener, no need to emit
  if (!this._events.removeListener) {
    if (arguments.length === 0)
      this._events = {};
    else if (this._events[type])
      delete this._events[type];
    return this;
  }

  // emit removeListener for all listeners on all events
  if (arguments.length === 0) {
    for (key in this._events) {
      if (key === 'removeListener') continue;
      this.removeAllListeners(key);
    }
    this.removeAllListeners('removeListener');
    this._events = {};
    return this;
  }

  listeners = this._events[type];

  if (util.isFunction(listeners)) {
    this.removeListener(type, listeners);
  } else if (Array.isArray(listeners)) {
    // LIFO order
    while (listeners.length)
      this.removeListener(type, listeners[listeners.length - 1]);
  }
  delete this._events[type];

  return this;
};

EventEmitter.prototype.listeners = function(type) {
  var ret;
  if (!this._events || !this._events[type])
    ret = [];
  else if (util.isFunction(this._events[type]))
    ret = [this._events[type]];
  else
    ret = this._events[type].slice();
  return ret;
};

EventEmitter.listenerCount = function(emitter, type) {
  var ret;
  if (!emitter._events || !emitter._events[type])
    ret = 0;
  else if (util.isFunction(emitter._events[type]))
    ret = 1;
  else
    ret = emitter._events[type].length;
  return ret;
};

var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var defineProperty = Object.defineProperty;
var gOPD = Object.getOwnPropertyDescriptor;

var isArray$1 = function isArray(arr) {
	if (typeof Array.isArray === 'function') {
		return Array.isArray(arr);
	}

	return toStr.call(arr) === '[object Array]';
};

var isPlainObject$1 = function isPlainObject(obj) {
	if (!obj || toStr.call(obj) !== '[object Object]') {
		return false;
	}

	var hasOwnConstructor = hasOwn.call(obj, 'constructor');
	var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
	// Not own constructor property must be Object
	if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
		return false;
	}

	// Own properties are enumerated firstly, so to speed up,
	// if last one is own, then all properties are own.
	var key;
	for (key in obj) { /**/ }

	return typeof key === 'undefined' || hasOwn.call(obj, key);
};

// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
var setProperty = function setProperty(target, options) {
	if (defineProperty && options.name === '__proto__') {
		defineProperty(target, options.name, {
			enumerable: true,
			configurable: true,
			value: options.newValue,
			writable: true
		});
	} else {
		target[options.name] = options.newValue;
	}
};

// Return undefined instead of __proto__ if '__proto__' is not an own property
var getProperty = function getProperty(obj, name) {
	if (name === '__proto__') {
		if (!hasOwn.call(obj, name)) {
			return void 0;
		} else if (gOPD) {
			// In early versions of node, obj['__proto__'] is buggy when obj has
			// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
			return gOPD(obj, name).value;
		}
	}

	return obj[name];
};

var extend$2 = function extend() {
	var options, name, src, copy, copyIsArray, clone;
	var target = arguments[0];
	var i = 1;
	var length = arguments.length;
	var deep = false;

	// Handle a deep copy situation
	if (typeof target === 'boolean') {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}
	if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
		target = {};
	}

	for (; i < length; ++i) {
		options = arguments[i];
		// Only deal with non-null/undefined values
		if (options != null) {
			// Extend the base object
			for (name in options) {
				src = getProperty(target, name);
				copy = getProperty(options, name);

				// Prevent never-ending loop
				if (target !== copy) {
					// Recurse if we're merging plain objects or arrays
					if (deep && copy && (isPlainObject$1(copy) || (copyIsArray = isArray$1(copy)))) {
						if (copyIsArray) {
							copyIsArray = false;
							clone = src && isArray$1(src) ? src : [];
						} else {
							clone = src && isPlainObject$1(src) ? src : {};
						}

						// Never move original objects, clone them
						setProperty(target, { name: name, newValue: extend(deep, clone, copy) });

					// Don't bring in undefined values
					} else if (typeof copy !== 'undefined') {
						setProperty(target, { name: name, newValue: copy });
					}
				}
			}
		}
	}

	// Return the modified object
	return target;
};

var fontSize$1 = "13px";
var fontFamily$1 = "'Source Sans Pro', 'Arial', 'sans-serif'";
var backgroundColor = "transparent";
var dataColors = {
	primaryColor: "#26a0a7",
	othersColor: "#a5a5a5",
	errorColor: "#ff4444",
	nullColor: "#d2d2d2"
};
var scales = [
	{
		name: "Sequential Gradient",
		translation: "properties.colorScheme.sequential",
		type: "gradient",
		propertyValue: "sg",
		scale: [
			"#26a0a7",
			"#c7ea8b"
		]
	},
	{
		name: "Sequential Classes",
		translation: "properties.colorScheme.sequentialC",
		propertyValue: "sc",
		type: "class",
		scale: [
			"#26a0a7",
			"#c7ea8b"
		]
	},
	{
		name: "Diverging gradient",
		translation: "properties.colorScheme.diverging",
		propertyValue: "dg",
		type: "gradient",
		scale: [
			"#26a0a7",
			"#c3ea8c",
			"#ec983d"
		]
	},
	{
		name: "Diverging Classes",
		translation: "properties.colorScheme.divergingC",
		propertyValue: "dc",
		type: "class",
		scale: [
			"#26a0a7",
			"#c3ea8c",
			"#ec983d"
		]
	}
];
var palettes = {
	data: [
		{
			name: "12 Colors",
			translation: "properties.colorNumberOfColors.12",
			propertyValue: "12",
			type: "pyramid",
			scale: [
				[
					"#26A0A7"
				],
				[
					"#26A0A7",
					"#EC983D"
				],
				[
					"#26A0A7",
					"#CBE989",
					"#EC983D"
				],
				[
					"#26A0A7",
					"#79D69F",
					"#F9EC86",
					"#EC983D"
				],
				[
					"#26A0A7",
					"#79D69F",
					"#CBE989",
					"#F9EC86",
					"#EC983D"
				],
				[
					"#26A0A7",
					"#65D3DA",
					"#79D69F",
					"#CBE989",
					"#F9EC86",
					"#EC983D"
				],
				[
					"#26A0A7",
					"#65D3DA",
					"#79D69F",
					"#CBE989",
					"#F9EC86",
					"#EC983D",
					"#D76C6C"
				],
				[
					"#26A0A7",
					"#65D3DA",
					"#79D69F",
					"#CBE989",
					"#F9EC86",
					"#FAD144",
					"#EC983D",
					"#D76C6C"
				],
				[
					"#138185",
					"#26A0A7",
					"#65D3DA",
					"#79D69F",
					"#CBE989",
					"#F9EC86",
					"#FAD144",
					"#EC983D",
					"#D76C6C"
				],
				[
					"#138185",
					"#26A0A7",
					"#65D3DA",
					"#79D69F",
					"#CBE989",
					"#EBF898",
					"#F9EC86",
					"#FAD144",
					"#EC983D",
					"#D76C6C"
				],
				[
					"#138185",
					"#26A0A7",
					"#65D3DA",
					"#79D69F",
					"#CBE989",
					"#EBF898",
					"#F9EC86",
					"#FAD144",
					"#EC983D",
					"#D76C6C",
					"#A54343"
				],
				[
					"#138185",
					"#26A0A7",
					"#65D3DA",
					"#79D69F",
					"#70BA6E",
					"#CBE989",
					"#EBF898",
					"#F9EC86",
					"#FAD144",
					"#EC983D",
					"#D76C6C",
					"#A54343"
				]
			]
		}
	],
	ui: [
		{
			name: "Palette",
			colors: [
				"#b0afae",
				"#7b7a78",
				"#a54343",
				"#d76c6c",
				"#ec983d",
				"#ecc43d",
				"#f9ec86",
				"#cbe989",
				"#70ba6e",
				"#578b60",
				"#79d69f",
				"#26a0a7",
				"#138185",
				"#65d3da",
				"#ffffff",
				"#000000"
			]
		}
	]
};
var baseRawJSON = {
	fontSize: fontSize$1,
	fontFamily: fontFamily$1,
	backgroundColor: backgroundColor,
	dataColors: dataColors,
	scales: scales,
	palettes: palettes
};

var _variables$1 = {
	"@B20": "#333333",
	"@B35": "#595959",
	"@B45": "#737373",
	"@B50": "#808080",
	"@B60": "#999999",
	"@B80": "#cccccc",
	"@B90": "#e6e6e6",
	"@B98": "#fbfbfb",
	"@B100": "#ffffff",
	"@H1": "24px",
	"@H2": "18px",
	"@H3": "14px",
	"@H4": "13px",
	"@H5": "12px",
	"@H6": "10px"
};
var type$1 = "light";
var color$3 = "@B35";
var lightRawJSON = {
	_variables: _variables$1,
	type: type$1,
	color: color$3
};

var _variables = {
	"@B20": "#333333",
	"@B35": "#595959",
	"@B45": "#737373",
	"@B50": "#808080",
	"@B60": "#999999",
	"@B80": "#cccccc",
	"@B90": "#e6e6e6",
	"@B98": "#fbfbfb",
	"@B100": "#ffffff",
	"@H1": "24px",
	"@H2": "18px",
	"@H3": "14px",
	"@H4": "13px",
	"@H5": "12px",
	"@H6": "10px"
};
var type = "dark";
var color$2 = "@B98";
var darkRawJSON = {
	_variables: _variables,
	type: type,
	color: color$2
};

function setTheme(t, resolve) {
  const colorRawJSON = t.type === 'dark' ? darkRawJSON : lightRawJSON;
  const root = extend$2(true, {}, baseRawJSON, colorRawJSON); // avoid merging known array objects as it could cause issues if they are of different types (pyramid vs class) or length

  const rawThemeJSON = extend$2(true, {}, root, {
    scales: null,
    palettes: {
      data: null,
      ui: null
    }
  }, t);

  if (!rawThemeJSON.palettes.data || !rawThemeJSON.palettes.data.length) {
    rawThemeJSON.palettes.data = root.palettes.data;
  }

  if (!rawThemeJSON.palettes.ui || !rawThemeJSON.palettes.ui.length) {
    rawThemeJSON.palettes.ui = root.palettes.ui;
  }

  if (!rawThemeJSON.scales || !rawThemeJSON.scales.length) {
    rawThemeJSON.scales = root.scales;
  }

  const resolvedThemeJSON = resolve(rawThemeJSON);
  return resolvedThemeJSON;
}

/**
 * @interface Theme~ScalePalette
 * @property {string} key
 * @property {'gradient'|'class-pyramid'} type
 * @property {string[]|Array<Array<string>>} colors
 */

/**
 * @interface Theme~DataPalette
 * @property {string} key
 * @property {'pyramid'|'row'} type
 * @property {string[]|Array<Array<string>>} colors
 */

/**
 * @interface Theme~ColorPickerPalette
 * @property {string} key
 * @property {string[]} colors
 */
function theme$1(resolvedTheme) {
  let uiPalette;
  return {
    dataScales() {
      const pals = [];
      resolvedTheme.scales.forEach(s => {
        pals.push({
          key: s.propertyValue,
          name: s.name,
          translation: s.translation,
          scheme: true,
          // indicate that this is scheme that can be used to generate more colors
          type: s.type,
          // gradient, class, pyramid, row
          colors: s.scale
        });
      });
      return pals;
    },

    dataPalettes() {
      const pals = [];
      resolvedTheme.palettes.data.forEach(s => {
        pals.push({
          key: s.propertyValue,
          name: s.name,
          translation: s.translation,
          type: s.type,
          colors: s.scale
        });
      });
      return pals;
    },

    uiPalettes() {
      const pals = [];
      resolvedTheme.palettes.ui.forEach(s => {
        pals.push({
          key: 'ui',
          name: s.name,
          translation: s.translation,
          type: 'row',
          colors: s.colors
        });
      });
      return pals;
    },

    dataColors() {
      /** @interface Theme~DataColorSpecials */
      return (
        /** @lends Theme~DataColorSpecials */
        {
          /** @type {string} */
          primary: resolvedTheme.dataColors.primaryColor,

          /** @type {string} */
          nil: resolvedTheme.dataColors.nullColor,

          /** @type {string} */
          others: resolvedTheme.dataColors.othersColor
        }
      );
    },

    uiColor(c) {
      if (c.index < 0 || typeof c.index === 'undefined') {
        return c.color;
      }

      if (typeof uiPalette === 'undefined') {
        uiPalette = this.uiPalettes()[0] || false;
      }

      if (!uiPalette) {
        return c.color;
      }

      if (typeof uiPalette.colors[c.index] === 'undefined') {
        return c.color;
      }

      return uiPalette.colors[c.index];
    }

  };
}

function define(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
}

function extend$1(parent, definition) {
  var prototype = Object.create(parent.prototype);
  for (var key in definition) prototype[key] = definition[key];
  return prototype;
}

function Color() {}

var darker = 0.7;
var brighter = 1 / darker;

var reI = "\\s*([+-]?\\d+)\\s*",
    reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",
    reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
    reHex = /^#([0-9a-f]{3,8})$/,
    reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$"),
    reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$"),
    reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$"),
    reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$"),
    reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$"),
    reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");

var named = {
  aliceblue: 0xf0f8ff,
  antiquewhite: 0xfaebd7,
  aqua: 0x00ffff,
  aquamarine: 0x7fffd4,
  azure: 0xf0ffff,
  beige: 0xf5f5dc,
  bisque: 0xffe4c4,
  black: 0x000000,
  blanchedalmond: 0xffebcd,
  blue: 0x0000ff,
  blueviolet: 0x8a2be2,
  brown: 0xa52a2a,
  burlywood: 0xdeb887,
  cadetblue: 0x5f9ea0,
  chartreuse: 0x7fff00,
  chocolate: 0xd2691e,
  coral: 0xff7f50,
  cornflowerblue: 0x6495ed,
  cornsilk: 0xfff8dc,
  crimson: 0xdc143c,
  cyan: 0x00ffff,
  darkblue: 0x00008b,
  darkcyan: 0x008b8b,
  darkgoldenrod: 0xb8860b,
  darkgray: 0xa9a9a9,
  darkgreen: 0x006400,
  darkgrey: 0xa9a9a9,
  darkkhaki: 0xbdb76b,
  darkmagenta: 0x8b008b,
  darkolivegreen: 0x556b2f,
  darkorange: 0xff8c00,
  darkorchid: 0x9932cc,
  darkred: 0x8b0000,
  darksalmon: 0xe9967a,
  darkseagreen: 0x8fbc8f,
  darkslateblue: 0x483d8b,
  darkslategray: 0x2f4f4f,
  darkslategrey: 0x2f4f4f,
  darkturquoise: 0x00ced1,
  darkviolet: 0x9400d3,
  deeppink: 0xff1493,
  deepskyblue: 0x00bfff,
  dimgray: 0x696969,
  dimgrey: 0x696969,
  dodgerblue: 0x1e90ff,
  firebrick: 0xb22222,
  floralwhite: 0xfffaf0,
  forestgreen: 0x228b22,
  fuchsia: 0xff00ff,
  gainsboro: 0xdcdcdc,
  ghostwhite: 0xf8f8ff,
  gold: 0xffd700,
  goldenrod: 0xdaa520,
  gray: 0x808080,
  green: 0x008000,
  greenyellow: 0xadff2f,
  grey: 0x808080,
  honeydew: 0xf0fff0,
  hotpink: 0xff69b4,
  indianred: 0xcd5c5c,
  indigo: 0x4b0082,
  ivory: 0xfffff0,
  khaki: 0xf0e68c,
  lavender: 0xe6e6fa,
  lavenderblush: 0xfff0f5,
  lawngreen: 0x7cfc00,
  lemonchiffon: 0xfffacd,
  lightblue: 0xadd8e6,
  lightcoral: 0xf08080,
  lightcyan: 0xe0ffff,
  lightgoldenrodyellow: 0xfafad2,
  lightgray: 0xd3d3d3,
  lightgreen: 0x90ee90,
  lightgrey: 0xd3d3d3,
  lightpink: 0xffb6c1,
  lightsalmon: 0xffa07a,
  lightseagreen: 0x20b2aa,
  lightskyblue: 0x87cefa,
  lightslategray: 0x778899,
  lightslategrey: 0x778899,
  lightsteelblue: 0xb0c4de,
  lightyellow: 0xffffe0,
  lime: 0x00ff00,
  limegreen: 0x32cd32,
  linen: 0xfaf0e6,
  magenta: 0xff00ff,
  maroon: 0x800000,
  mediumaquamarine: 0x66cdaa,
  mediumblue: 0x0000cd,
  mediumorchid: 0xba55d3,
  mediumpurple: 0x9370db,
  mediumseagreen: 0x3cb371,
  mediumslateblue: 0x7b68ee,
  mediumspringgreen: 0x00fa9a,
  mediumturquoise: 0x48d1cc,
  mediumvioletred: 0xc71585,
  midnightblue: 0x191970,
  mintcream: 0xf5fffa,
  mistyrose: 0xffe4e1,
  moccasin: 0xffe4b5,
  navajowhite: 0xffdead,
  navy: 0x000080,
  oldlace: 0xfdf5e6,
  olive: 0x808000,
  olivedrab: 0x6b8e23,
  orange: 0xffa500,
  orangered: 0xff4500,
  orchid: 0xda70d6,
  palegoldenrod: 0xeee8aa,
  palegreen: 0x98fb98,
  paleturquoise: 0xafeeee,
  palevioletred: 0xdb7093,
  papayawhip: 0xffefd5,
  peachpuff: 0xffdab9,
  peru: 0xcd853f,
  pink: 0xffc0cb,
  plum: 0xdda0dd,
  powderblue: 0xb0e0e6,
  purple: 0x800080,
  rebeccapurple: 0x663399,
  red: 0xff0000,
  rosybrown: 0xbc8f8f,
  royalblue: 0x4169e1,
  saddlebrown: 0x8b4513,
  salmon: 0xfa8072,
  sandybrown: 0xf4a460,
  seagreen: 0x2e8b57,
  seashell: 0xfff5ee,
  sienna: 0xa0522d,
  silver: 0xc0c0c0,
  skyblue: 0x87ceeb,
  slateblue: 0x6a5acd,
  slategray: 0x708090,
  slategrey: 0x708090,
  snow: 0xfffafa,
  springgreen: 0x00ff7f,
  steelblue: 0x4682b4,
  tan: 0xd2b48c,
  teal: 0x008080,
  thistle: 0xd8bfd8,
  tomato: 0xff6347,
  turquoise: 0x40e0d0,
  violet: 0xee82ee,
  wheat: 0xf5deb3,
  white: 0xffffff,
  whitesmoke: 0xf5f5f5,
  yellow: 0xffff00,
  yellowgreen: 0x9acd32
};

define(Color, color$1, {
  copy: function(channels) {
    return Object.assign(new this.constructor, this, channels);
  },
  displayable: function() {
    return this.rgb().displayable();
  },
  hex: color_formatHex, // Deprecated! Use color.formatHex.
  formatHex: color_formatHex,
  formatHsl: color_formatHsl,
  formatRgb: color_formatRgb,
  toString: color_formatRgb
});

function color_formatHex() {
  return this.rgb().formatHex();
}

function color_formatHsl() {
  return hslConvert(this).formatHsl();
}

function color_formatRgb() {
  return this.rgb().formatRgb();
}

function color$1(format) {
  var m, l;
  format = (format + "").trim().toLowerCase();
  return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000
      : l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00
      : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000
      : l === 4 ? rgba((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000
      : null) // invalid hex
      : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
      : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
      : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
      : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
      : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
      : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
      : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins
      : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0)
      : null;
}

function rgbn(n) {
  return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
}

function rgba(r, g, b, a) {
  if (a <= 0) r = g = b = NaN;
  return new Rgb(r, g, b, a);
}

function rgbConvert(o) {
  if (!(o instanceof Color)) o = color$1(o);
  if (!o) return new Rgb;
  o = o.rgb();
  return new Rgb(o.r, o.g, o.b, o.opacity);
}

function rgb(r, g, b, opacity) {
  return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
}

function Rgb(r, g, b, opacity) {
  this.r = +r;
  this.g = +g;
  this.b = +b;
  this.opacity = +opacity;
}

define(Rgb, rgb, extend$1(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  rgb: function() {
    return this;
  },
  displayable: function() {
    return (-0.5 <= this.r && this.r < 255.5)
        && (-0.5 <= this.g && this.g < 255.5)
        && (-0.5 <= this.b && this.b < 255.5)
        && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: rgb_formatHex, // Deprecated! Use color.formatHex.
  formatHex: rgb_formatHex,
  formatRgb: rgb_formatRgb,
  toString: rgb_formatRgb
}));

function rgb_formatHex() {
  return "#" + hex(this.r) + hex(this.g) + hex(this.b);
}

function rgb_formatRgb() {
  var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
  return (a === 1 ? "rgb(" : "rgba(")
      + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
      + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
      + Math.max(0, Math.min(255, Math.round(this.b) || 0))
      + (a === 1 ? ")" : ", " + a + ")");
}

function hex(value) {
  value = Math.max(0, Math.min(255, Math.round(value) || 0));
  return (value < 16 ? "0" : "") + value.toString(16);
}

function hsla(h, s, l, a) {
  if (a <= 0) h = s = l = NaN;
  else if (l <= 0 || l >= 1) h = s = NaN;
  else if (s <= 0) h = NaN;
  return new Hsl(h, s, l, a);
}

function hslConvert(o) {
  if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Color)) o = color$1(o);
  if (!o) return new Hsl;
  if (o instanceof Hsl) return o;
  o = o.rgb();
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      min = Math.min(r, g, b),
      max = Math.max(r, g, b),
      h = NaN,
      s = max - min,
      l = (max + min) / 2;
  if (s) {
    if (r === max) h = (g - b) / s + (g < b) * 6;
    else if (g === max) h = (b - r) / s + 2;
    else h = (r - g) / s + 4;
    s /= l < 0.5 ? max + min : 2 - max - min;
    h *= 60;
  } else {
    s = l > 0 && l < 1 ? 0 : h;
  }
  return new Hsl(h, s, l, o.opacity);
}

function hsl(h, s, l, opacity) {
  return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
}

function Hsl(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

define(Hsl, hsl, extend$1(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  rgb: function() {
    var h = this.h % 360 + (this.h < 0) * 360,
        s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
        l = this.l,
        m2 = l + (l < 0.5 ? l : 1 - l) * s,
        m1 = 2 * l - m2;
    return new Rgb(
      hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
      hsl2rgb(h, m1, m2),
      hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
      this.opacity
    );
  },
  displayable: function() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s))
        && (0 <= this.l && this.l <= 1)
        && (0 <= this.opacity && this.opacity <= 1);
  },
  formatHsl: function() {
    var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
    return (a === 1 ? "hsl(" : "hsla(")
        + (this.h || 0) + ", "
        + (this.s || 0) * 100 + "%, "
        + (this.l || 0) * 100 + "%"
        + (a === 1 ? ")" : ", " + a + ")");
  }
}));

/* From FvD 13.37, CSS Color Module Level 3 */
function hsl2rgb(h, m1, m2) {
  return (h < 60 ? m1 + (m2 - m1) * h / 60
      : h < 180 ? m2
      : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
      : m1) * 255;
}

const radians = Math.PI / 180;
const degrees = 180 / Math.PI;

// https://observablehq.com/@mbostock/lab-and-rgb
const K = 18,
    Xn = 0.96422,
    Yn = 1,
    Zn = 0.82521,
    t0 = 4 / 29,
    t1 = 6 / 29,
    t2 = 3 * t1 * t1,
    t3 = t1 * t1 * t1;

function labConvert(o) {
  if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);
  if (o instanceof Hcl) return hcl2lab(o);
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r = rgb2lrgb(o.r),
      g = rgb2lrgb(o.g),
      b = rgb2lrgb(o.b),
      y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z;
  if (r === g && g === b) x = z = y; else {
    x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);
    z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);
  }
  return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);
}

function lab(l, a, b, opacity) {
  return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);
}

function Lab(l, a, b, opacity) {
  this.l = +l;
  this.a = +a;
  this.b = +b;
  this.opacity = +opacity;
}

define(Lab, lab, extend$1(Color, {
  brighter: function(k) {
    return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  darker: function(k) {
    return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  rgb: function() {
    var y = (this.l + 16) / 116,
        x = isNaN(this.a) ? y : y + this.a / 500,
        z = isNaN(this.b) ? y : y - this.b / 200;
    x = Xn * lab2xyz(x);
    y = Yn * lab2xyz(y);
    z = Zn * lab2xyz(z);
    return new Rgb(
      lrgb2rgb( 3.1338561 * x - 1.6168667 * y - 0.4906146 * z),
      lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),
      lrgb2rgb( 0.0719453 * x - 0.2289914 * y + 1.4052427 * z),
      this.opacity
    );
  }
}));

function xyz2lab(t) {
  return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;
}

function lab2xyz(t) {
  return t > t1 ? t * t * t : t2 * (t - t0);
}

function lrgb2rgb(x) {
  return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
}

function rgb2lrgb(x) {
  return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}

function hclConvert(o) {
  if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);
  if (!(o instanceof Lab)) o = labConvert(o);
  if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);
  var h = Math.atan2(o.b, o.a) * degrees;
  return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
}

function hcl(h, c, l, opacity) {
  return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
}

function Hcl(h, c, l, opacity) {
  this.h = +h;
  this.c = +c;
  this.l = +l;
  this.opacity = +opacity;
}

function hcl2lab(o) {
  if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);
  var h = o.h * radians;
  return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
}

define(Hcl, hcl, extend$1(Color, {
  brighter: function(k) {
    return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);
  },
  darker: function(k) {
    return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);
  },
  rgb: function() {
    return hcl2lab(this).rgb();
  }
}));

var A$1 = -0.14861,
    B$1 = +1.78277,
    C$1 = -0.29227,
    D$1 = -0.90649,
    E$1 = +1.97294,
    ED = E$1 * D$1,
    EB = E$1 * B$1,
    BC_DA = B$1 * C$1 - D$1 * A$1;

function cubehelixConvert(o) {
  if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),
      bl = b - l,
      k = (E$1 * (g - l) - C$1 * bl) / D$1,
      s = Math.sqrt(k * k + bl * bl) / (E$1 * l * (1 - l)), // NaN if l=0 or l=1
      h = s ? Math.atan2(k, bl) * degrees - 120 : NaN;
  return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
}

function cubehelix(h, s, l, opacity) {
  return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);
}

function Cubehelix(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

define(Cubehelix, cubehelix, extend$1(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
  },
  rgb: function() {
    var h = isNaN(this.h) ? 0 : (this.h + 120) * radians,
        l = +this.l,
        a = isNaN(this.s) ? 0 : this.s * l * (1 - l),
        cosh = Math.cos(h),
        sinh = Math.sin(h);
    return new Rgb(
      255 * (l + a * (A$1 * cosh + B$1 * sinh)),
      255 * (l + a * (C$1 * cosh + D$1 * sinh)),
      255 * (l + a * (E$1 * cosh)),
      this.opacity
    );
  }
}));

/**
 * Gets this mapping between the scaled value and the color parts
 * @ignore
 * @param {Number} scaledValue - A value between 0 and 1 representing a value in the data scaled between the max and min boundaries of the data. Values are clamped to 0 and 1.
 * @param {Number} numEdges - Number of parts that makes up this scale
 */

function limitFunction(scaledValue, numParts) {
  /*
   *	Color-Scale doesn't calculate exact color blends based of the scaled value. It instead shifts the value inwards to achieve
   *	a better color representation at the edges. Primarily this is done to allow setting custom limits to where each color begins
   *	and ends. If a color begins and ends at 1, it should not be visible. The simplest way to achive this is to remove 1 and 0
   *	from the possible numbers that can be used. Colors that are not equal to 1 or 0 should not be affected.
   */
  // The following is done to keep the scaled value above 0 and below 1. This shifts values that hits an exact boundary upwards.
  // eslint-disable-next-line no-param-reassign
  scaledValue = Math.min(Math.max(scaledValue, 0.000000000001), 0.999999999999);
  return numParts - scaledValue * numParts;
}

function getLevel(scale, level) {
  return Math.min(level || scale.startLevel, scale.colorParts.length - 1);
}

function blend(c1, c2, t) {
  const r = Math.floor(c1.r + (c2.r - c1.r) * t);
  const g = Math.floor(c1.g + (c2.g - c1.g) * t);
  const b = Math.floor(c1.b + (c2.b - c1.b) * t);
  const a = Math.floor(c1.opacity + (c2.opacity - c1.opacity) * t);
  return rgb(r, g, b, a);
}

class ColorScale {
  constructor(nanColor) {
    this.colorParts = [];
    this.startLevel = 0;
    this.max = 1;
    this.min = 0;
    this.nanColor = color$1(nanColor);
  }
  /**
   * Adds a part to this color scale. The input colors span one part of the gradient, colors between them are interpolated. Input two equal colors for a solid scale part.
   * @ignore
   * @param {String|Number} color1 - First color to be used, in formats defined by Color
   * @param {String|Number} color2 - Second color to be used, in formats defined by Color
   * @param {Number} level - Which level of the color pyramid to add this part to.
   */


  addColorPart(color1, color2, level) {
    // eslint-disable-next-line no-param-reassign
    level = level || 0;
    this.startLevel = Math.max(level, this.startLevel);

    if (!this.colorParts[level]) {
      this.colorParts[level] = [];
    }

    this.colorParts[level].push([color$1(color1), color$1(color2)]);
  }
  /**
   * Gets the color which represents the input value
   * @ignore
   * @param {Number} scaledValue - A value between 0 and 1 representing a value in the data scaled between the max and min boundaries of the data. Values are clamped to 0 and 1.
   */


  getColor(value, level) {
    const scaledValue = value - this.min;

    if (Number.isNaN(+value) || Number.isNaN(+scaledValue)) {
      return this.nanColor;
    } // eslint-disable-next-line no-param-reassign


    level = getLevel(this, level);
    const k = limitFunction(scaledValue, this.colorParts[level].length);
    let f = Math.floor(k);
    f = f === k ? f - 1 : f; // To fulfill equal or greater than: 329-<330

    const part = this.colorParts[level][f];
    const c1 = part[0];
    const c2 = part[1]; // For absolute edges we return the colors at the limit

    if (value === this.min) {
      return c2;
    }

    if (value === this.max) {
      return c1;
    }

    const t = k - f;
    const uc = blend(c1, c2, t);
    return uc;
  }

}

/* Calculates a value that expands from 0.5 out to 0 and 1
 * Ex for size 8:
 * current -> percent
 * 0 -> 0.0625	4 -> 0.3125
 * 1 -> 0.125	5 -> 0.375
 * 2 -> 0.1875	6 -> 0.4375
 * 3 -> 0.25		7 -> 0.5
 */

function getScaleValue(value, current, size) {
  const percent = 0.25 + (current + 1) / size * 0.25;
  const min = 0.5 - percent;
  const max = 0.5 + percent;
  const span = max - min;
  return min + value / 1 * span;
}

function setupColorScale(colors, nanColor, gradient) {
  const newColors = [];
  const cs = new ColorScale(nanColor);
  newColors.push(colors[0]);

  if (!gradient) {
    newColors.push(colors[0]);
  }

  let i = 1;

  for (; i < colors.length - 1; i++) {
    newColors.push(colors[i]);
    newColors.push(colors[i]);
  }

  newColors.push(colors[i]);

  if (!gradient) {
    newColors.push(colors[i]);
  }

  for (let j = 0; j < newColors.length; j += 2) {
    cs.addColorPart(newColors[j], newColors[j + 1]);
  }

  return cs;
}

function generateLevel(scale, current, size) {
  const level = [];

  for (let j = 0; j < current + 1; j++) {
    let c;

    switch (current) {
      case 0:
        c = scale.getColor(0.5);
        break;

      default:
        {
          const scaled = getScaleValue(1 / current * j, current, size);
          c = scale.getColor(scaled);
          break;
        }
    }

    level.push(color$1(c).formatHex());
  }

  return level;
}
/**
 * Generates a pyramid of colors from a minimum of 2 colors
 *
 * @ignore
 * @internal
 * @param {Array} colors an array of colors to generate from
 * @param {number} size the integer size of the base of the pyramid
 * @returns {Array} A 2 dimensional array containing the levels of the color pyramid
 */


function createPyramidFromColors(colors, size, nanColor) {
  const gradientScale = setupColorScale(colors, nanColor, true);
  const baseLevel = generateLevel(gradientScale, size - 1, size);
  const scale = setupColorScale(baseLevel, nanColor, false);
  const pyramid = [null];

  for (let i = 0; i < size; i++) {
    pyramid.push(generateLevel(scale, i, size));
  }

  return pyramid;
}

function generateOrdinalScales(scalesDef) {
  let nanColor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '#d2d2d2';
  scalesDef.forEach(def => {
    if (def.type === 'class') {
      // generate pyramid
      const pyramid = createPyramidFromColors(def.scale, Math.max(def.scale.length, 7), nanColor); // eslint-disable-next-line no-param-reassign

      def.scale = pyramid; // eslint-disable-next-line no-param-reassign

      def.type = 'class-pyramid';
    }
  });
}

/**
 * Creates the following array of paths
 * object.barChart - legend.title - fontSize
 * object - legend.title - fontSize
 * legend.title - fontSize
 * object.barChart - legend - fontSize
 * object - legend - fontSize
 * legend - fontSize
 * object.barChart - fontSize
 * object - fontSize
 * fontSize
 * @ignore
 */

function constructPaths(pathSteps, baseSteps) {
  const ret = [];
  let localBaseSteps;
  let baseLength;

  if (pathSteps) {
    let pathLength = pathSteps.length;

    while (pathLength >= 0) {
      localBaseSteps = baseSteps.slice();
      baseLength = localBaseSteps.length;

      while (baseLength >= 0) {
        ret.push(localBaseSteps.concat(pathSteps));
        localBaseSteps.pop();
        baseLength--;
      }

      pathSteps.pop();
      pathLength--;
    }
  } else {
    localBaseSteps = baseSteps.slice();
    baseLength = localBaseSteps.length;

    while (baseLength >= 0) {
      ret.push(localBaseSteps.concat());
      localBaseSteps.pop();
      baseLength--;
    }
  }

  return ret;
}

function getObject$1(root, steps) {
  let obj = root;

  for (let i = 0; i < steps.length; i++) {
    if (obj[steps[i]]) {
      obj = obj[steps[i]];
    } else {
      return undefined;
    }
  }

  return obj;
}

function searchPathArray(pathArray, attribute, theme) {
  const attributeArray = attribute.split('.');

  for (let i = 0; i < pathArray.length; i++) {
    const restult = getObject$1(theme, [...pathArray[i], ...attributeArray]);
    if (restult !== undefined) return restult;
  }

  return undefined;
}

function searchValue(path, attribute, baseSteps, component) {
  let pathArray;

  if (path === '') {
    pathArray = constructPaths(null, baseSteps);
  } else {
    const steps = path.split('.');
    pathArray = constructPaths(steps, baseSteps);
  }

  return searchPathArray(pathArray, attribute, component);
}

function styleResolver(basePath, themeJSON) {
  const basePathSteps = basePath.split('.');
  const api = {
    /**
     *
     * Get the value of a style attribute, starting in the given base path + path
     * Ex: Base path: "object.barChart", Path: "legend.title", Attribute: "fontSize"
     * Will search in, and fall back to:
     * object.barChart - legend.title - fontSize
     * object - legend.title - fontSize
     * legend.title - fontSize
     * object.barChart - legend - fontSize
     * object - legend - fontSize
     * legend - fontSize
     * object.barChart - fontSize
     * object - fontSize
     * fontSize
     * When attributes separated by dots is provided, they are required in the theme JSON file
     * Ex. Base path: "object" , Path: "legend", ", Attribute: "title.fontSize"
     * title: {fontSize: ...} must be matched and the rest is the same as above
     * If you want a exact match, you can use `getStyle('object', '', 'legend.title.fontSize');`
     * @ignore
     *
     * @param {string} component String of properties separated by dots to search in
     * @param {string} attribute Name of the style attribute
     * @returns {string|undefined} The style value of the resolved path, undefined if not found
     */
    getStyle(component, attribute) {
      // TODO - object overrides
      // TODO - feature flag on font-family?
      // TODO - caching
      const baseSteps = basePathSteps.concat();
      const result = searchValue(component, attribute, baseSteps, themeJSON); // TODO - support functions

      return result;
    }

  };
  return api;
}
/**
 * Iterate the object tree and resolve variables and functions.
 * @ignore
 * @param {Object} - objTree
 * @param {Object} - variables
 */

function resolveVariables(objTree, variables) {
  Object.keys(objTree).forEach(key => {
    if (typeof objTree[key] === 'object' && objTree[key] !== null) {
      resolveVariables(objTree[key], variables);
    } else if (typeof objTree[key] === 'string' && objTree[key].charAt(0) === '@') {
      // Resolve variables
      objTree[key] = variables[objTree[key]]; // eslint-disable-line no-param-reassign
    }
  });
}

styleResolver.resolveRawTheme = raw => {
  // TODO - validate format
  const c = extend$2(true, {}, raw);
  resolveVariables(c, c._variables); // eslint-disable-line
  // generate class-pyramid

  if (c.scales) {
    generateOrdinalScales(c.scales, c.dataColors && c.dataColors.nullColor);
  }

  return c;
};

function luminance(colStr) {
  const c = color$1(colStr).rgb();
  const {
    r,
    g,
    b
  } = c; // https://www.w3.org/TR/WCAG20/#relativeluminancedef

  const [sR, sG, sB] = [r, g, b].map(v => v / 255);
  const [R, G, B] = [sR, sG, sB].map(v => v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
  return +(0.2126 * R + 0.7152 * G + 0.0722 * B).toFixed(5);
}

// https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html#contrast-ratiodef
function contrast(L1, L2) {
  return +((Math.max(L1, L2) + 0.05) / (Math.min(L1, L2) + 0.05)).toFixed(5);
}

/* eslint no-cond-assign: 0 */
const MAX_SIZE = 1000;
function colorFn() {
  let colors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['#333333', '#ffffff'];
  let cache = {};
  let n = 0;
  const luminances = colors.map(luminance);
  return {
    getBestContrastColor(colorString) {
      if (!cache[colorString]) {
        if (n > MAX_SIZE) {
          cache = {};
          n = 0;
        }

        const L = luminance(colorString);
        const contrasts = luminances.map(lum => contrast(L, lum));
        const c = colors[contrasts.indexOf(Math.max(...contrasts))];
        cache[colorString] = c;
        n++;
      }

      return cache[colorString];
    }

  };
}

function theme() {
  let resolvedThemeJSON;
  let styleResolverInstanceCache = {};
  let paletteResolver;
  let contraster;
  /**
   * @class
   * @alias Theme
   */

  const externalAPI =
  /** @lends Theme# */
  {
    /**
     * @returns {Theme~ScalePalette[]}
     */
    getDataColorScales() {
      return paletteResolver.dataScales();
    },

    /**
     * @returns {Theme~DataPalette[]}
     */
    getDataColorPalettes() {
      return paletteResolver.dataPalettes();
    },

    /**
     * @returns {Theme~ColorPickerPalette[]}
     */
    getDataColorPickerPalettes() {
      return paletteResolver.uiPalettes();
    },

    /**
     * @returns {Theme~DataColorSpecials}
     */
    getDataColorSpecials() {
      return paletteResolver.dataColors();
    },

    /**
     * Resolve a color object using the color picker palette from the provided JSON theme.
     * @param {object} c
     * @param {number=} c.index
     * @param {string=} c.color
     * @returns {string} The resolved color.
     *
     * @example
     * theme.getColorPickerColor({ index: 1 });
     * theme.getColorPickerColor({ color: 'red' });
     */
    getColorPickerColor() {
      return paletteResolver.uiColor(...arguments);
    },

    /**
     * Get the best contrasting color against the specified `color`.
     * This is typically used to find a suitable text color for a label placed on an arbitrarily colored background.
     *
     * The returned colors are derived from the theme.
     * @param {string} color - A color to measure the contrast against
     * @returns {string} - The color that has the best contrast against the specified `color`.
     * @example
     * theme.getContrastingColorTo('#400');
     */
    getContrastingColorTo(color) {
      return contraster.getBestContrastColor(color);
    },

    /**
     * Get the value of a style attribute in the theme
     * by searching in the theme's JSON structure.
     * The search starts at the specified base path
     * and continues upwards until the value is found.
     * If possible it will get the attribute's value using the given path.
     * When attributes separated by dots are provided, such as 'hover.color',
     * they are required in the theme JSON file
     *
     * @param {string} basePath - Base path in the theme's JSON structure to start the search in (specified as a name path separated by dots).
     * @param {string} path - Expected path for the attribute (specified as a name path separated by dots).
     * @param {string} attribute - Name of the style attribute. (specified as a name attribute separated by dots).
     * @returns {string|undefined} The style value or undefined if not found
     *
     * @example
     * theme.getStyle('object', 'title.main', 'fontSize');
     * theme.getStyle('object', 'title', 'main.fontSize');
     * theme.getStyle('object', '', 'title.main.fontSize');
     * theme.getStyle('', '', 'fontSize');
     */
    getStyle(basePath, path, attribute) {
      if (!styleResolverInstanceCache[basePath]) {
        styleResolverInstanceCache[basePath] = styleResolver(basePath, resolvedThemeJSON);
      }

      return styleResolverInstanceCache[basePath].getStyle(path, attribute);
    }

  };
  const internalAPI = {
    /**
     * @private
     * @param {object} t Raw JSON theme
     */
    setTheme(t, name) {
      resolvedThemeJSON = setTheme(t, styleResolver.resolveRawTheme);
      styleResolverInstanceCache = {};
      paletteResolver = theme$1(resolvedThemeJSON); // try to determine if the theme color is light or dark

      const textColor = externalAPI.getStyle('', '', 'color');
      const textColorLuminance = luminance(textColor); // if it appears dark, create an inverse that is light and vice versa

      const inverseTextColor = textColorLuminance < 0.2 ? '#ffffff' : '#333333'; // instantiate a contraster that uses those two colors when determining the best contrast for an arbitrary color

      contraster = colorFn([textColor, inverseTextColor]);
      externalAPI.emit('changed');

      externalAPI.name = () => name;
    }

  };
  Object.keys(nodeEventEmitter.prototype).forEach(key => {
    externalAPI[key] = nodeEventEmitter.prototype[key];
  });
  nodeEventEmitter.init(externalAPI);
  internalAPI.setTheme({}, 'light');
  return {
    externalAPI,
    internalAPI
  };
}

/* eslint no-underscore-dangle:0 */

const timed = (t, v) => new Promise(resolve => {
  setTimeout(() => resolve(v), t);
});

const LOAD_THEME_TIMEOUT = 5000;
function appTheme() {
  let {
    themes = [],
    root
  } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  const wrappedTheme = theme();

  const setTheme = async themeId => {
    const found = themes.filter(t => t.id === themeId)[0];
    let muiTheme = themeId === 'dark' ? 'dark' : 'light';

    if (found && found.load) {
      try {
        const raw = await Promise.race([found.load(), timed(LOAD_THEME_TIMEOUT, {
          __timedOut: true
        })]);

        if (raw.__timedOut) {
          if (true) {
            console.warn("Timeout when loading theme '".concat(themeId, "'")); // eslint-disable-line no-console
          }
        } else {
          muiTheme = raw.type === 'dark' ? 'dark' : 'light';
          wrappedTheme.internalAPI.setTheme(raw, themeId);
          root.setMuiThemeName(muiTheme);
        }
      } catch (e) {
        {
          console.error(e); // eslint-disable-line no-console
        }
      }
    } else {
      wrappedTheme.internalAPI.setTheme({
        type: muiTheme
      }, themeId);
      root.setMuiThemeName(muiTheme);
    }
  };

  return {
    setTheme,
    externalAPI: wrappedTheme.externalAPI
  };
}

// from https://patrickhlauke.github.io/touch/touchscreen-detection/ (MIT License)
function detectTouchscreen() {
  let result = false;

  if (window.PointerEvent && 'maxTouchPoints' in navigator) {
    // if Pointer Events are supported, just check maxTouchPoints
    if (navigator.maxTouchPoints > 0) {
      result = true;
    }
  } else if (window.matchMedia && window.matchMedia('(any-pointer:coarse)').matches) {
    // check for any-pointer:coarse which mostly means touchscreen
    result = true;
  } else if (window.TouchEvent || 'ontouchstart' in window) {
    // last resort - check for exposed touch events API / event handler
    result = true;
  }

  return result;
}

function deviceTypeFn(deviceType) {
  if (deviceType !== 'auto') {
    return deviceType;
  }

  return detectTouchscreen() ? 'touch' : 'desktop';
}

function chainPropTypes(propType1, propType2) {
  {
    return function () {
      return null;
    };
  }
}

function _extends$3() {
  _extends$3 = Object.assign || function (target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];

      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }

    return target;
  };

  return _extends$3.apply(this, arguments);
}

function _typeof2$1(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2$1 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2$1 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2$1(obj); }

function _typeof$1(obj) {
  if (typeof Symbol === "function" && _typeof2$1(Symbol.iterator) === "symbol") {
    _typeof$1 = function _typeof(obj) {
      return _typeof2$1(obj);
    };
  } else {
    _typeof$1 = function _typeof(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2$1(obj);
    };
  }

  return _typeof$1(obj);
}

function isPlainObject(item) {
  return item && _typeof$1(item) === 'object' && item.constructor === Object;
}
function deepmerge(target, source) {
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
    clone: true
  };
  var output = options.clone ? _extends$3({}, target) : target;

  if (isPlainObject(target) && isPlainObject(source)) {
    Object.keys(source).forEach(function (key) {
      // Avoid prototype pollution
      if (key === '__proto__') {
        return;
      }

      if (isPlainObject(source[key]) && key in target) {
        output[key] = deepmerge(target[key], source[key], options);
      } else {
        output[key] = source[key];
      }
    });
  }

  return output;
}

var propTypes = {exports: {}};

/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';

var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;

/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

var ReactPropTypesSecret = ReactPropTypesSecret_1;

function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;

var factoryWithThrowingShims = function() {
  function shim(props, propName, componentName, location, propFullName, secret) {
    if (secret === ReactPropTypesSecret) {
      // It is still safe when called from React.
      return;
    }
    var err = new Error(
      'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
      'Use PropTypes.checkPropTypes() to call them. ' +
      'Read more at http://fb.me/use-check-prop-types'
    );
    err.name = 'Invariant Violation';
    throw err;
  }  shim.isRequired = shim;
  function getShim() {
    return shim;
  }  // Important!
  // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
  var ReactPropTypes = {
    array: shim,
    bool: shim,
    func: shim,
    number: shim,
    object: shim,
    string: shim,
    symbol: shim,

    any: shim,
    arrayOf: getShim,
    element: shim,
    elementType: shim,
    instanceOf: getShim,
    node: shim,
    objectOf: getShim,
    oneOf: getShim,
    oneOfType: getShim,
    shape: getShim,
    exact: getShim,

    checkPropTypes: emptyFunctionWithReset,
    resetWarningCache: emptyFunction
  };

  ReactPropTypes.PropTypes = ReactPropTypes;

  return ReactPropTypes;
};

/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

{
  // By explicitly using `prop-types` you are opting into new production behavior.
  // http://fb.me/prop-types-in-prod
  propTypes.exports = factoryWithThrowingShims();
}

var elementAcceptingRef = chainPropTypes(propTypes.exports.element);
elementAcceptingRef.isRequired = chainPropTypes(propTypes.exports.element.isRequired);

/**
 * WARNING: Don't import this directly.
 * Use `MuiError` from `@material-ui/utils/macros/MuiError.macro` instead.
 * @param {number} code
 */
function formatMuiErrorMessage(code) {
  // Apply babel-plugin-transform-template-literals in loose mode
  // loose mode is safe iff we're concatenating primitives
  // see https://babeljs.io/docs/en/babel-plugin-transform-template-literals#loose

  /* eslint-disable prefer-template */
  var url = 'https://mui.com/production-error/?code=' + code;

  for (var i = 1; i < arguments.length; i += 1) {
    // rest params over-transpile for this case
    // eslint-disable-next-line prefer-rest-params
    url += '&args[]=' + encodeURIComponent(arguments[i]);
  }

  return 'Minified Material-UI error #' + code + '; visit ' + url + ' for the full message.';
  /* eslint-enable prefer-template */
}

var reactIs = {exports: {}};

var reactIs_production_min = {};

/** @license React v17.0.2
 * react-is.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var b=60103,c=60106,d=60107,e=60108,f=60114,g=60109,h=60110,k=60112,l=60113,m=60120,n=60115,p=60116,q=60121,r=60122,u=60117,v=60129,w=60131;
if("function"===typeof Symbol&&Symbol.for){var x=Symbol.for;b=x("react.element");c=x("react.portal");d=x("react.fragment");e=x("react.strict_mode");f=x("react.profiler");g=x("react.provider");h=x("react.context");k=x("react.forward_ref");l=x("react.suspense");m=x("react.suspense_list");n=x("react.memo");p=x("react.lazy");q=x("react.block");r=x("react.server.block");u=x("react.fundamental");v=x("react.debug_trace_mode");w=x("react.legacy_hidden");}
function y(a){if("object"===typeof a&&null!==a){var t=a.$$typeof;switch(t){case b:switch(a=a.type,a){case d:case f:case e:case l:case m:return a;default:switch(a=a&&a.$$typeof,a){case h:case k:case p:case n:case g:return a;default:return t}}case c:return t}}}var z=g,A=b,B=k,C=d,D=p,E=n,F=c,G=f,H=e,I=l;reactIs_production_min.ContextConsumer=h;reactIs_production_min.ContextProvider=z;reactIs_production_min.Element=A;reactIs_production_min.ForwardRef=B;reactIs_production_min.Fragment=C;reactIs_production_min.Lazy=D;reactIs_production_min.Memo=E;reactIs_production_min.Portal=F;reactIs_production_min.Profiler=G;reactIs_production_min.StrictMode=H;
reactIs_production_min.Suspense=I;reactIs_production_min.isAsyncMode=function(){return !1};reactIs_production_min.isConcurrentMode=function(){return !1};reactIs_production_min.isContextConsumer=function(a){return y(a)===h};reactIs_production_min.isContextProvider=function(a){return y(a)===g};reactIs_production_min.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===b};reactIs_production_min.isForwardRef=function(a){return y(a)===k};reactIs_production_min.isFragment=function(a){return y(a)===d};reactIs_production_min.isLazy=function(a){return y(a)===p};reactIs_production_min.isMemo=function(a){return y(a)===n};
reactIs_production_min.isPortal=function(a){return y(a)===c};reactIs_production_min.isProfiler=function(a){return y(a)===f};reactIs_production_min.isStrictMode=function(a){return y(a)===e};reactIs_production_min.isSuspense=function(a){return y(a)===l};reactIs_production_min.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===d||a===f||a===v||a===e||a===l||a===m||a===w||"object"===typeof a&&null!==a&&(a.$$typeof===p||a.$$typeof===n||a.$$typeof===g||a.$$typeof===h||a.$$typeof===k||a.$$typeof===u||a.$$typeof===q||a[0]===r)?!0:!1};
reactIs_production_min.typeOf=y;

(function (module) {

	{
	  module.exports = reactIs_production_min;
	}
} (reactIs));

/* eslint-disable */
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();

propTypes.exports.oneOfType([propTypes.exports.func, propTypes.exports.object]);

/* eslint-disable no-use-before-define */

/**
 * Returns a number whose value is limited to the given range.
 *
 * @param {number} value The value to be clamped
 * @param {number} min The lower boundary of the output range
 * @param {number} max The upper boundary of the output range
 * @returns {number} A number in the range [min, max]
 */
function clamp(value) {
  var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;

  return Math.min(Math.max(min, value), max);
}
/**
 * Converts a color from CSS hex format to CSS rgb format.
 *
 * @param {string} color - Hex color, i.e. #nnn or #nnnnnn
 * @returns {string} A CSS rgb color string
 */


function hexToRgb(color) {
  color = color.substr(1);
  var re = new RegExp(".{1,".concat(color.length >= 6 ? 2 : 1, "}"), 'g');
  var colors = color.match(re);

  if (colors && colors[0].length === 1) {
    colors = colors.map(function (n) {
      return n + n;
    });
  }

  return colors ? "rgb".concat(colors.length === 4 ? 'a' : '', "(").concat(colors.map(function (n, index) {
    return index < 3 ? parseInt(n, 16) : Math.round(parseInt(n, 16) / 255 * 1000) / 1000;
  }).join(', '), ")") : '';
}
/**
 * Converts a color from hsl format to rgb format.
 *
 * @param {string} color - HSL color values
 * @returns {string} rgb color values
 */

function hslToRgb(color) {
  color = decomposeColor(color);
  var _color = color,
      values = _color.values;
  var h = values[0];
  var s = values[1] / 100;
  var l = values[2] / 100;
  var a = s * Math.min(l, 1 - l);

  var f = function f(n) {
    var k = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (n + h / 30) % 12;
    return l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
  };

  var type = 'rgb';
  var rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];

  if (color.type === 'hsla') {
    type += 'a';
    rgb.push(values[3]);
  }

  return recomposeColor({
    type: type,
    values: rgb
  });
}
/**
 * Returns an object with the type and values of a color.
 *
 * Note: Does not support rgb % values.
 *
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
 * @returns {object} - A MUI color object: {type: string, values: number[]}
 */

function decomposeColor(color) {
  // Idempotent
  if (color.type) {
    return color;
  }

  if (color.charAt(0) === '#') {
    return decomposeColor(hexToRgb(color));
  }

  var marker = color.indexOf('(');
  var type = color.substring(0, marker);

  if (['rgb', 'rgba', 'hsl', 'hsla'].indexOf(type) === -1) {
    throw new Error(formatMuiErrorMessage(3, color));
  }

  var values = color.substring(marker + 1, color.length - 1).split(',');
  values = values.map(function (value) {
    return parseFloat(value);
  });
  return {
    type: type,
    values: values
  };
}
/**
 * Converts a color object with type and values to a string.
 *
 * @param {object} color - Decomposed color
 * @param {string} color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla'
 * @param {array} color.values - [n,n,n] or [n,n,n,n]
 * @returns {string} A CSS color string
 */

function recomposeColor(color) {
  var type = color.type;
  var values = color.values;

  if (type.indexOf('rgb') !== -1) {
    // Only convert the first 3 values to int (i.e. not alpha)
    values = values.map(function (n, i) {
      return i < 3 ? parseInt(n, 10) : n;
    });
  } else if (type.indexOf('hsl') !== -1) {
    values[1] = "".concat(values[1], "%");
    values[2] = "".concat(values[2], "%");
  }

  return "".concat(type, "(").concat(values.join(', '), ")");
}
/**
 * Calculates the contrast ratio between two colors.
 *
 * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
 *
 * @param {string} foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
 * @param {string} background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
 * @returns {number} A contrast ratio value in the range 0 - 21.
 */

function getContrastRatio(foreground, background) {
  var lumA = getLuminance(foreground);
  var lumB = getLuminance(background);
  return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);
}
/**
 * The relative brightness of any point in a color space,
 * normalized to 0 for darkest black and 1 for lightest white.
 *
 * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
 *
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
 * @returns {number} The relative brightness of the color in the range 0 - 1
 */

function getLuminance(color) {
  color = decomposeColor(color);
  var rgb = color.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : color.values;
  rgb = rgb.map(function (val) {
    val /= 255; // normalized

    return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);
  }); // Truncate at 3 digits

  return Number((0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3));
}
/**
 * Darkens a color.
 *
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
 * @param {number} coefficient - multiplier in the range 0 - 1
 * @returns {string} A CSS color string. Hex input values are returned as rgb
 */

function darken(color, coefficient) {
  color = decomposeColor(color);
  coefficient = clamp(coefficient);

  if (color.type.indexOf('hsl') !== -1) {
    color.values[2] *= 1 - coefficient;
  } else if (color.type.indexOf('rgb') !== -1) {
    for (var i = 0; i < 3; i += 1) {
      color.values[i] *= 1 - coefficient;
    }
  }

  return recomposeColor(color);
}
/**
 * Lightens a color.
 *
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
 * @param {number} coefficient - multiplier in the range 0 - 1
 * @returns {string} A CSS color string. Hex input values are returned as rgb
 */

function lighten(color, coefficient) {
  color = decomposeColor(color);
  coefficient = clamp(coefficient);

  if (color.type.indexOf('hsl') !== -1) {
    color.values[2] += (100 - color.values[2]) * coefficient;
  } else if (color.type.indexOf('rgb') !== -1) {
    for (var i = 0; i < 3; i += 1) {
      color.values[i] += (255 - color.values[i]) * coefficient;
    }
  }

  return recomposeColor(color);
}

function _defineProperty$1(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null) return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i;

  for (i = 0; i < sourceKeys.length; i++) {
    key = sourceKeys[i];
    if (excluded.indexOf(key) >= 0) continue;
    target[key] = source[key];
  }

  return target;
}

function _objectWithoutProperties(source, excluded) {
  if (source == null) return {};
  var target = _objectWithoutPropertiesLoose(source, excluded);
  var key, i;

  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);

    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key = sourceSymbolKeys[i];
      if (excluded.indexOf(key) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
      target[key] = source[key];
    }
  }

  return target;
}

function _extends$2() {
  _extends$2 = Object.assign || function (target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];

      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }

    return target;
  };

  return _extends$2.apply(this, arguments);
}

// Sorted ASC by size. That's important.
// It can't be configured as it's used statically for propTypes.
var keys = ['xs', 'sm', 'md', 'lg', 'xl']; // Keep in mind that @media is inclusive by the CSS specification.

function createBreakpoints(breakpoints) {
  var _breakpoints$values = breakpoints.values,
      values = _breakpoints$values === void 0 ? {
    xs: 0,
    sm: 600,
    md: 960,
    lg: 1280,
    xl: 1920
  } : _breakpoints$values,
      _breakpoints$unit = breakpoints.unit,
      unit = _breakpoints$unit === void 0 ? 'px' : _breakpoints$unit,
      _breakpoints$step = breakpoints.step,
      step = _breakpoints$step === void 0 ? 5 : _breakpoints$step,
      other = _objectWithoutProperties(breakpoints, ["values", "unit", "step"]);

  function up(key) {
    var value = typeof values[key] === 'number' ? values[key] : key;
    return "@media (min-width:".concat(value).concat(unit, ")");
  }

  function down(key) {
    var endIndex = keys.indexOf(key) + 1;
    var upperbound = values[keys[endIndex]];

    if (endIndex === keys.length) {
      // xl down applies to all sizes
      return up('xs');
    }

    var value = typeof upperbound === 'number' && endIndex > 0 ? upperbound : key;
    return "@media (max-width:".concat(value - step / 100).concat(unit, ")");
  }

  function between(start, end) {
    var endIndex = keys.indexOf(end);

    if (endIndex === keys.length - 1) {
      return up(start);
    }

    return "@media (min-width:".concat(typeof values[start] === 'number' ? values[start] : start).concat(unit, ") and ") + "(max-width:".concat((endIndex !== -1 && typeof values[keys[endIndex + 1]] === 'number' ? values[keys[endIndex + 1]] : end) - step / 100).concat(unit, ")");
  }

  function only(key) {
    return between(key, key);
  }

  function width(key) {

    return values[key];
  }

  return _extends$2({
    keys: keys,
    values: values,
    up: up,
    down: down,
    between: between,
    only: only,
    width: width
  }, other);
}

function createMixins(breakpoints, spacing, mixins) {
  var _toolbar;

  return _extends$2({
    gutters: function gutters() {
      var styles = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      console.warn(['Material-UI: theme.mixins.gutters() is deprecated.', 'You can use the source of the mixin directly:', "\n      paddingLeft: theme.spacing(2),\n      paddingRight: theme.spacing(2),\n      [theme.breakpoints.up('sm')]: {\n        paddingLeft: theme.spacing(3),\n        paddingRight: theme.spacing(3),\n      },\n      "].join('\n'));
      return _extends$2({
        paddingLeft: spacing(2),
        paddingRight: spacing(2)
      }, styles, _defineProperty$1({}, breakpoints.up('sm'), _extends$2({
        paddingLeft: spacing(3),
        paddingRight: spacing(3)
      }, styles[breakpoints.up('sm')])));
    },
    toolbar: (_toolbar = {
      minHeight: 56
    }, _defineProperty$1(_toolbar, "".concat(breakpoints.up('xs'), " and (orientation: landscape)"), {
      minHeight: 48
    }), _defineProperty$1(_toolbar, breakpoints.up('sm'), {
      minHeight: 64
    }), _toolbar)
  }, mixins);
}

var common = {
  black: '#000',
  white: '#fff'
};

var grey = {
  50: '#fafafa',
  100: '#f5f5f5',
  200: '#eeeeee',
  300: '#e0e0e0',
  400: '#bdbdbd',
  500: '#9e9e9e',
  600: '#757575',
  700: '#616161',
  800: '#424242',
  900: '#212121',
  A100: '#d5d5d5',
  A200: '#aaaaaa',
  A400: '#303030',
  A700: '#616161'
};

var indigo = {
  50: '#e8eaf6',
  100: '#c5cae9',
  200: '#9fa8da',
  300: '#7986cb',
  400: '#5c6bc0',
  500: '#3f51b5',
  600: '#3949ab',
  700: '#303f9f',
  800: '#283593',
  900: '#1a237e',
  A100: '#8c9eff',
  A200: '#536dfe',
  A400: '#3d5afe',
  A700: '#304ffe'
};

var pink = {
  50: '#fce4ec',
  100: '#f8bbd0',
  200: '#f48fb1',
  300: '#f06292',
  400: '#ec407a',
  500: '#e91e63',
  600: '#d81b60',
  700: '#c2185b',
  800: '#ad1457',
  900: '#880e4f',
  A100: '#ff80ab',
  A200: '#ff4081',
  A400: '#f50057',
  A700: '#c51162'
};

var red = {
  50: '#ffebee',
  100: '#ffcdd2',
  200: '#ef9a9a',
  300: '#e57373',
  400: '#ef5350',
  500: '#f44336',
  600: '#e53935',
  700: '#d32f2f',
  800: '#c62828',
  900: '#b71c1c',
  A100: '#ff8a80',
  A200: '#ff5252',
  A400: '#ff1744',
  A700: '#d50000'
};

var orange = {
  50: '#fff3e0',
  100: '#ffe0b2',
  200: '#ffcc80',
  300: '#ffb74d',
  400: '#ffa726',
  500: '#ff9800',
  600: '#fb8c00',
  700: '#f57c00',
  800: '#ef6c00',
  900: '#e65100',
  A100: '#ffd180',
  A200: '#ffab40',
  A400: '#ff9100',
  A700: '#ff6d00'
};

var blue = {
  50: '#e3f2fd',
  100: '#bbdefb',
  200: '#90caf9',
  300: '#64b5f6',
  400: '#42a5f5',
  500: '#2196f3',
  600: '#1e88e5',
  700: '#1976d2',
  800: '#1565c0',
  900: '#0d47a1',
  A100: '#82b1ff',
  A200: '#448aff',
  A400: '#2979ff',
  A700: '#2962ff'
};

var green = {
  50: '#e8f5e9',
  100: '#c8e6c9',
  200: '#a5d6a7',
  300: '#81c784',
  400: '#66bb6a',
  500: '#4caf50',
  600: '#43a047',
  700: '#388e3c',
  800: '#2e7d32',
  900: '#1b5e20',
  A100: '#b9f6ca',
  A200: '#69f0ae',
  A400: '#00e676',
  A700: '#00c853'
};

var light$1 = {
  // The colors used to style the text.
  text: {
    // The most important text.
    primary: 'rgba(0, 0, 0, 0.87)',
    // Secondary text.
    secondary: 'rgba(0, 0, 0, 0.54)',
    // Disabled text have even lower visual prominence.
    disabled: 'rgba(0, 0, 0, 0.38)',
    // Text hints.
    hint: 'rgba(0, 0, 0, 0.38)'
  },
  // The color used to divide different elements.
  divider: 'rgba(0, 0, 0, 0.12)',
  // The background colors used to style the surfaces.
  // Consistency between these values is important.
  background: {
    paper: common.white,
    default: grey[50]
  },
  // The colors used to style the action elements.
  action: {
    // The color of an active action like an icon button.
    active: 'rgba(0, 0, 0, 0.54)',
    // The color of an hovered action.
    hover: 'rgba(0, 0, 0, 0.04)',
    hoverOpacity: 0.04,
    // The color of a selected action.
    selected: 'rgba(0, 0, 0, 0.08)',
    selectedOpacity: 0.08,
    // The color of a disabled action.
    disabled: 'rgba(0, 0, 0, 0.26)',
    // The background color of a disabled action.
    disabledBackground: 'rgba(0, 0, 0, 0.12)',
    disabledOpacity: 0.38,
    focus: 'rgba(0, 0, 0, 0.12)',
    focusOpacity: 0.12,
    activatedOpacity: 0.12
  }
};
var dark$1 = {
  text: {
    primary: common.white,
    secondary: 'rgba(255, 255, 255, 0.7)',
    disabled: 'rgba(255, 255, 255, 0.5)',
    hint: 'rgba(255, 255, 255, 0.5)',
    icon: 'rgba(255, 255, 255, 0.5)'
  },
  divider: 'rgba(255, 255, 255, 0.12)',
  background: {
    paper: grey[800],
    default: '#303030'
  },
  action: {
    active: common.white,
    hover: 'rgba(255, 255, 255, 0.08)',
    hoverOpacity: 0.08,
    selected: 'rgba(255, 255, 255, 0.16)',
    selectedOpacity: 0.16,
    disabled: 'rgba(255, 255, 255, 0.3)',
    disabledBackground: 'rgba(255, 255, 255, 0.12)',
    disabledOpacity: 0.38,
    focus: 'rgba(255, 255, 255, 0.12)',
    focusOpacity: 0.12,
    activatedOpacity: 0.24
  }
};

function addLightOrDark(intent, direction, shade, tonalOffset) {
  var tonalOffsetLight = tonalOffset.light || tonalOffset;
  var tonalOffsetDark = tonalOffset.dark || tonalOffset * 1.5;

  if (!intent[direction]) {
    if (intent.hasOwnProperty(shade)) {
      intent[direction] = intent[shade];
    } else if (direction === 'light') {
      intent.light = lighten(intent.main, tonalOffsetLight);
    } else if (direction === 'dark') {
      intent.dark = darken(intent.main, tonalOffsetDark);
    }
  }
}

function createPalette(palette) {
  var _palette$primary = palette.primary,
      primary = _palette$primary === void 0 ? {
    light: indigo[300],
    main: indigo[500],
    dark: indigo[700]
  } : _palette$primary,
      _palette$secondary = palette.secondary,
      secondary = _palette$secondary === void 0 ? {
    light: pink.A200,
    main: pink.A400,
    dark: pink.A700
  } : _palette$secondary,
      _palette$error = palette.error,
      error = _palette$error === void 0 ? {
    light: red[300],
    main: red[500],
    dark: red[700]
  } : _palette$error,
      _palette$warning = palette.warning,
      warning = _palette$warning === void 0 ? {
    light: orange[300],
    main: orange[500],
    dark: orange[700]
  } : _palette$warning,
      _palette$info = palette.info,
      info = _palette$info === void 0 ? {
    light: blue[300],
    main: blue[500],
    dark: blue[700]
  } : _palette$info,
      _palette$success = palette.success,
      success = _palette$success === void 0 ? {
    light: green[300],
    main: green[500],
    dark: green[700]
  } : _palette$success,
      _palette$type = palette.type,
      type = _palette$type === void 0 ? 'light' : _palette$type,
      _palette$contrastThre = palette.contrastThreshold,
      contrastThreshold = _palette$contrastThre === void 0 ? 3 : _palette$contrastThre,
      _palette$tonalOffset = palette.tonalOffset,
      tonalOffset = _palette$tonalOffset === void 0 ? 0.2 : _palette$tonalOffset,
      other = _objectWithoutProperties(palette, ["primary", "secondary", "error", "warning", "info", "success", "type", "contrastThreshold", "tonalOffset"]); // Use the same logic as
  // Bootstrap: https://github.com/twbs/bootstrap/blob/1d6e3710dd447de1a200f29e8fa521f8a0908f70/scss/_functions.scss#L59
  // and material-components-web https://github.com/material-components/material-components-web/blob/ac46b8863c4dab9fc22c4c662dc6bd1b65dd652f/packages/mdc-theme/_functions.scss#L54


  function getContrastText(background) {
    var contrastText = getContrastRatio(background, dark$1.text.primary) >= contrastThreshold ? dark$1.text.primary : light$1.text.primary;

    return contrastText;
  }

  var augmentColor = function augmentColor(color) {
    var mainShade = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 500;
    var lightShade = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 300;
    var darkShade = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 700;
    color = _extends$2({}, color);

    if (!color.main && color[mainShade]) {
      color.main = color[mainShade];
    }

    if (!color.main) {
      throw new Error(formatMuiErrorMessage(4, mainShade));
    }

    if (typeof color.main !== 'string') {
      throw new Error(formatMuiErrorMessage(5, JSON.stringify(color.main)));
    }

    addLightOrDark(color, 'light', lightShade, tonalOffset);
    addLightOrDark(color, 'dark', darkShade, tonalOffset);

    if (!color.contrastText) {
      color.contrastText = getContrastText(color.main);
    }

    return color;
  };

  var types = {
    dark: dark$1,
    light: light$1
  };

  var paletteOutput = deepmerge(_extends$2({
    // A collection of common colors.
    common: common,
    // The palette type, can be light or dark.
    type: type,
    // The colors used to represent primary interface elements for a user.
    primary: augmentColor(primary),
    // The colors used to represent secondary interface elements for a user.
    secondary: augmentColor(secondary, 'A400', 'A200', 'A700'),
    // The colors used to represent interface elements that the user should be made aware of.
    error: augmentColor(error),
    // The colors used to represent potentially dangerous actions or important messages.
    warning: augmentColor(warning),
    // The colors used to present information to the user that is neutral and not necessarily important.
    info: augmentColor(info),
    // The colors used to indicate the successful completion of an action that user triggered.
    success: augmentColor(success),
    // The grey colors.
    grey: grey,
    // Used by `getContrastText()` to maximize the contrast between
    // the background and the text.
    contrastThreshold: contrastThreshold,
    // Takes a background color and returns the text color that maximizes the contrast.
    getContrastText: getContrastText,
    // Generate a rich color object.
    augmentColor: augmentColor,
    // Used by the functions below to shift a color's luminance by approximately
    // two indexes within its tonal palette.
    // E.g., shift from Red 500 to Red 300 or Red 700.
    tonalOffset: tonalOffset
  }, types[type]), other);
  return paletteOutput;
}

function round(value) {
  return Math.round(value * 1e5) / 1e5;
}

function roundWithDeprecationWarning(value) {

  return round(value);
}

var caseAllCaps = {
  textTransform: 'uppercase'
};
var defaultFontFamily = '"Roboto", "Helvetica", "Arial", sans-serif';
/**
 * @see @link{https://material.io/design/typography/the-type-system.html}
 * @see @link{https://material.io/design/typography/understanding-typography.html}
 */

function createTypography(palette, typography) {
  var _ref = typeof typography === 'function' ? typography(palette) : typography,
      _ref$fontFamily = _ref.fontFamily,
      fontFamily = _ref$fontFamily === void 0 ? defaultFontFamily : _ref$fontFamily,
      _ref$fontSize = _ref.fontSize,
      fontSize = _ref$fontSize === void 0 ? 14 : _ref$fontSize,
      _ref$fontWeightLight = _ref.fontWeightLight,
      fontWeightLight = _ref$fontWeightLight === void 0 ? 300 : _ref$fontWeightLight,
      _ref$fontWeightRegula = _ref.fontWeightRegular,
      fontWeightRegular = _ref$fontWeightRegula === void 0 ? 400 : _ref$fontWeightRegula,
      _ref$fontWeightMedium = _ref.fontWeightMedium,
      fontWeightMedium = _ref$fontWeightMedium === void 0 ? 500 : _ref$fontWeightMedium,
      _ref$fontWeightBold = _ref.fontWeightBold,
      fontWeightBold = _ref$fontWeightBold === void 0 ? 700 : _ref$fontWeightBold,
      _ref$htmlFontSize = _ref.htmlFontSize,
      htmlFontSize = _ref$htmlFontSize === void 0 ? 16 : _ref$htmlFontSize,
      allVariants = _ref.allVariants,
      pxToRem2 = _ref.pxToRem,
      other = _objectWithoutProperties(_ref, ["fontFamily", "fontSize", "fontWeightLight", "fontWeightRegular", "fontWeightMedium", "fontWeightBold", "htmlFontSize", "allVariants", "pxToRem"]);

  var coef = fontSize / 14;

  var pxToRem = pxToRem2 || function (size) {
    return "".concat(size / htmlFontSize * coef, "rem");
  };

  var buildVariant = function buildVariant(fontWeight, size, lineHeight, letterSpacing, casing) {
    return _extends$2({
      fontFamily: fontFamily,
      fontWeight: fontWeight,
      fontSize: pxToRem(size),
      // Unitless following https://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/
      lineHeight: lineHeight
    }, fontFamily === defaultFontFamily ? {
      letterSpacing: "".concat(round(letterSpacing / size), "em")
    } : {}, casing, allVariants);
  };

  var variants = {
    h1: buildVariant(fontWeightLight, 96, 1.167, -1.5),
    h2: buildVariant(fontWeightLight, 60, 1.2, -0.5),
    h3: buildVariant(fontWeightRegular, 48, 1.167, 0),
    h4: buildVariant(fontWeightRegular, 34, 1.235, 0.25),
    h5: buildVariant(fontWeightRegular, 24, 1.334, 0),
    h6: buildVariant(fontWeightMedium, 20, 1.6, 0.15),
    subtitle1: buildVariant(fontWeightRegular, 16, 1.75, 0.15),
    subtitle2: buildVariant(fontWeightMedium, 14, 1.57, 0.1),
    body1: buildVariant(fontWeightRegular, 16, 1.5, 0.15),
    body2: buildVariant(fontWeightRegular, 14, 1.43, 0.15),
    button: buildVariant(fontWeightMedium, 14, 1.75, 0.4, caseAllCaps),
    caption: buildVariant(fontWeightRegular, 12, 1.66, 0.4),
    overline: buildVariant(fontWeightRegular, 12, 2.66, 1, caseAllCaps)
  };
  return deepmerge(_extends$2({
    htmlFontSize: htmlFontSize,
    pxToRem: pxToRem,
    round: roundWithDeprecationWarning,
    // TODO v5: remove
    fontFamily: fontFamily,
    fontSize: fontSize,
    fontWeightLight: fontWeightLight,
    fontWeightRegular: fontWeightRegular,
    fontWeightMedium: fontWeightMedium,
    fontWeightBold: fontWeightBold
  }, variants), other, {
    clone: false // No need to clone deep

  });
}

var shadowKeyUmbraOpacity = 0.2;
var shadowKeyPenumbraOpacity = 0.14;
var shadowAmbientShadowOpacity = 0.12;

function createShadow() {
  return ["".concat(arguments.length <= 0 ? undefined : arguments[0], "px ").concat(arguments.length <= 1 ? undefined : arguments[1], "px ").concat(arguments.length <= 2 ? undefined : arguments[2], "px ").concat(arguments.length <= 3 ? undefined : arguments[3], "px rgba(0,0,0,").concat(shadowKeyUmbraOpacity, ")"), "".concat(arguments.length <= 4 ? undefined : arguments[4], "px ").concat(arguments.length <= 5 ? undefined : arguments[5], "px ").concat(arguments.length <= 6 ? undefined : arguments[6], "px ").concat(arguments.length <= 7 ? undefined : arguments[7], "px rgba(0,0,0,").concat(shadowKeyPenumbraOpacity, ")"), "".concat(arguments.length <= 8 ? undefined : arguments[8], "px ").concat(arguments.length <= 9 ? undefined : arguments[9], "px ").concat(arguments.length <= 10 ? undefined : arguments[10], "px ").concat(arguments.length <= 11 ? undefined : arguments[11], "px rgba(0,0,0,").concat(shadowAmbientShadowOpacity, ")")].join(',');
} // Values from https://github.com/material-components/material-components-web/blob/be8747f94574669cb5e7add1a7c54fa41a89cec7/packages/mdc-elevation/_variables.scss


var shadows = ['none', createShadow(0, 2, 1, -1, 0, 1, 1, 0, 0, 1, 3, 0), createShadow(0, 3, 1, -2, 0, 2, 2, 0, 0, 1, 5, 0), createShadow(0, 3, 3, -2, 0, 3, 4, 0, 0, 1, 8, 0), createShadow(0, 2, 4, -1, 0, 4, 5, 0, 0, 1, 10, 0), createShadow(0, 3, 5, -1, 0, 5, 8, 0, 0, 1, 14, 0), createShadow(0, 3, 5, -1, 0, 6, 10, 0, 0, 1, 18, 0), createShadow(0, 4, 5, -2, 0, 7, 10, 1, 0, 2, 16, 1), createShadow(0, 5, 5, -3, 0, 8, 10, 1, 0, 3, 14, 2), createShadow(0, 5, 6, -3, 0, 9, 12, 1, 0, 3, 16, 2), createShadow(0, 6, 6, -3, 0, 10, 14, 1, 0, 4, 18, 3), createShadow(0, 6, 7, -4, 0, 11, 15, 1, 0, 4, 20, 3), createShadow(0, 7, 8, -4, 0, 12, 17, 2, 0, 5, 22, 4), createShadow(0, 7, 8, -4, 0, 13, 19, 2, 0, 5, 24, 4), createShadow(0, 7, 9, -4, 0, 14, 21, 2, 0, 5, 26, 4), createShadow(0, 8, 9, -5, 0, 15, 22, 2, 0, 6, 28, 5), createShadow(0, 8, 10, -5, 0, 16, 24, 2, 0, 6, 30, 5), createShadow(0, 8, 11, -5, 0, 17, 26, 2, 0, 6, 32, 5), createShadow(0, 9, 11, -5, 0, 18, 28, 2, 0, 7, 34, 6), createShadow(0, 9, 12, -6, 0, 19, 29, 2, 0, 7, 36, 6), createShadow(0, 10, 13, -6, 0, 20, 31, 3, 0, 8, 38, 7), createShadow(0, 10, 13, -6, 0, 21, 33, 3, 0, 8, 40, 7), createShadow(0, 10, 14, -6, 0, 22, 35, 3, 0, 8, 42, 7), createShadow(0, 11, 14, -7, 0, 23, 36, 3, 0, 9, 44, 8), createShadow(0, 11, 15, -7, 0, 24, 38, 3, 0, 9, 46, 8)];

var shape = {
  borderRadius: 4
};

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }

function _typeof(obj) {
  if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
    _typeof = function _typeof(obj) {
      return _typeof2(obj);
    };
  } else {
    _typeof = function _typeof(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
    };
  }

  return _typeof(obj);
}

function merge(acc, item) {
  if (!item) {
    return acc;
  }

  return deepmerge(acc, item, {
    clone: false // No need to clone deep, it's way faster.

  });
}

// For instance with the first breakpoint xs: [xs, sm[.

var values = {
  xs: 0,
  sm: 600,
  md: 960,
  lg: 1280,
  xl: 1920
};
var defaultBreakpoints = {
  // Sorted ASC by size. That's important.
  // It can't be configured as it's used statically for propTypes.
  keys: ['xs', 'sm', 'md', 'lg', 'xl'],
  up: function up(key) {
    return "@media (min-width:".concat(values[key], "px)");
  }
};
function handleBreakpoints(props, propValue, styleFromPropValue) {

  if (Array.isArray(propValue)) {
    var themeBreakpoints = props.theme.breakpoints || defaultBreakpoints;
    return propValue.reduce(function (acc, item, index) {
      acc[themeBreakpoints.up(themeBreakpoints.keys[index])] = styleFromPropValue(propValue[index]);
      return acc;
    }, {});
  }

  if (_typeof(propValue) === 'object') {
    var _themeBreakpoints = props.theme.breakpoints || defaultBreakpoints;

    return Object.keys(propValue).reduce(function (acc, breakpoint) {
      acc[_themeBreakpoints.up(breakpoint)] = styleFromPropValue(propValue[breakpoint]);
      return acc;
    }, {});
  }

  var output = styleFromPropValue(propValue);
  return output;
}

function getPath$1(obj, path) {
  if (!path || typeof path !== 'string') {
    return null;
  }

  return path.split('.').reduce(function (acc, item) {
    return acc && acc[item] ? acc[item] : null;
  }, obj);
}

function style(options) {
  var prop = options.prop,
      _options$cssProperty = options.cssProperty,
      cssProperty = _options$cssProperty === void 0 ? options.prop : _options$cssProperty,
      themeKey = options.themeKey,
      transform = options.transform;

  var fn = function fn(props) {
    if (props[prop] == null) {
      return null;
    }

    var propValue = props[prop];
    var theme = props.theme;
    var themeMapping = getPath$1(theme, themeKey) || {};

    var styleFromPropValue = function styleFromPropValue(propValueFinal) {
      var value;

      if (typeof themeMapping === 'function') {
        value = themeMapping(propValueFinal);
      } else if (Array.isArray(themeMapping)) {
        value = themeMapping[propValueFinal] || propValueFinal;
      } else {
        value = getPath$1(themeMapping, propValueFinal) || propValueFinal;

        if (transform) {
          value = transform(value);
        }
      }

      if (cssProperty === false) {
        return value;
      }

      return _defineProperty({}, cssProperty, value);
    };

    return handleBreakpoints(props, propValue, styleFromPropValue);
  };

  fn.propTypes = {};
  fn.filterProps = [prop];
  return fn;
}

function compose() {
  for (var _len = arguments.length, styles = new Array(_len), _key = 0; _key < _len; _key++) {
    styles[_key] = arguments[_key];
  }

  var fn = function fn(props) {
    return styles.reduce(function (acc, style) {
      var output = style(props);

      if (output) {
        return merge(acc, output);
      }

      return acc;
    }, {});
  }; // Alternative approach that doesn't yield any performance gain.
  // const handlers = styles.reduce((acc, style) => {
  //   style.filterProps.forEach(prop => {
  //     acc[prop] = style;
  //   });
  //   return acc;
  // }, {});
  // const fn = props => {
  //   return Object.keys(props).reduce((acc, prop) => {
  //     if (handlers[prop]) {
  //       return merge(acc, handlers[prop](props));
  //     }
  //     return acc;
  //   }, {});
  // };


  fn.propTypes = {};
  fn.filterProps = styles.reduce(function (acc, style) {
    return acc.concat(style.filterProps);
  }, []);
  return fn;
}

function getBorder(value) {
  if (typeof value !== 'number') {
    return value;
  }

  return "".concat(value, "px solid");
}

var border = style({
  prop: 'border',
  themeKey: 'borders',
  transform: getBorder
});
var borderTop = style({
  prop: 'borderTop',
  themeKey: 'borders',
  transform: getBorder
});
var borderRight = style({
  prop: 'borderRight',
  themeKey: 'borders',
  transform: getBorder
});
var borderBottom = style({
  prop: 'borderBottom',
  themeKey: 'borders',
  transform: getBorder
});
var borderLeft = style({
  prop: 'borderLeft',
  themeKey: 'borders',
  transform: getBorder
});
var borderColor = style({
  prop: 'borderColor',
  themeKey: 'palette'
});
var borderRadius$1 = style({
  prop: 'borderRadius',
  themeKey: 'shape'
});
compose(border, borderTop, borderRight, borderBottom, borderLeft, borderColor, borderRadius$1);

var displayPrint = style({
  prop: 'displayPrint',
  cssProperty: false,
  transform: function transform(value) {
    return {
      '@media print': {
        display: value
      }
    };
  }
});
var displayRaw = style({
  prop: 'display'
});
var overflow = style({
  prop: 'overflow'
});
var textOverflow = style({
  prop: 'textOverflow'
});
var visibility = style({
  prop: 'visibility'
});
var whiteSpace = style({
  prop: 'whiteSpace'
});
compose(displayPrint, displayRaw, overflow, textOverflow, visibility, whiteSpace);

var flexBasis = style({
  prop: 'flexBasis'
});
var flexDirection = style({
  prop: 'flexDirection'
});
var flexWrap = style({
  prop: 'flexWrap'
});
var justifyContent = style({
  prop: 'justifyContent'
});
var alignItems = style({
  prop: 'alignItems'
});
var alignContent = style({
  prop: 'alignContent'
});
var order = style({
  prop: 'order'
});
var flex = style({
  prop: 'flex'
});
var flexGrow = style({
  prop: 'flexGrow'
});
var flexShrink = style({
  prop: 'flexShrink'
});
var alignSelf = style({
  prop: 'alignSelf'
});
var justifyItems = style({
  prop: 'justifyItems'
});
var justifySelf = style({
  prop: 'justifySelf'
});
compose(flexBasis, flexDirection, flexWrap, justifyContent, alignItems, alignContent, order, flex, flexGrow, flexShrink, alignSelf, justifyItems, justifySelf);

var gridGap = style({
  prop: 'gridGap'
});
var gridColumnGap = style({
  prop: 'gridColumnGap'
});
var gridRowGap = style({
  prop: 'gridRowGap'
});
var gridColumn = style({
  prop: 'gridColumn'
});
var gridRow = style({
  prop: 'gridRow'
});
var gridAutoFlow = style({
  prop: 'gridAutoFlow'
});
var gridAutoColumns = style({
  prop: 'gridAutoColumns'
});
var gridAutoRows = style({
  prop: 'gridAutoRows'
});
var gridTemplateColumns = style({
  prop: 'gridTemplateColumns'
});
var gridTemplateRows = style({
  prop: 'gridTemplateRows'
});
var gridTemplateAreas = style({
  prop: 'gridTemplateAreas'
});
var gridArea = style({
  prop: 'gridArea'
});
compose(gridGap, gridColumnGap, gridRowGap, gridColumn, gridRow, gridAutoFlow, gridAutoColumns, gridAutoRows, gridTemplateColumns, gridTemplateRows, gridTemplateAreas, gridArea);

var color = style({
  prop: 'color',
  themeKey: 'palette'
});
var bgcolor = style({
  prop: 'bgcolor',
  cssProperty: 'backgroundColor',
  themeKey: 'palette'
});
compose(color, bgcolor);

var position = style({
  prop: 'position'
});
var zIndex$1 = style({
  prop: 'zIndex',
  themeKey: 'zIndex'
});
var top = style({
  prop: 'top'
});
var right = style({
  prop: 'right'
});
var bottom = style({
  prop: 'bottom'
});
var left = style({
  prop: 'left'
});
compose(position, zIndex$1, top, right, bottom, left);

style({
  prop: 'boxShadow',
  themeKey: 'shadows'
});

function transform(value) {
  return value <= 1 ? "".concat(value * 100, "%") : value;
}

var width = style({
  prop: 'width',
  transform: transform
});
var maxWidth = style({
  prop: 'maxWidth',
  transform: transform
});
var minWidth = style({
  prop: 'minWidth',
  transform: transform
});
var height = style({
  prop: 'height',
  transform: transform
});
var maxHeight = style({
  prop: 'maxHeight',
  transform: transform
});
var minHeight = style({
  prop: 'minHeight',
  transform: transform
});
style({
  prop: 'size',
  cssProperty: 'width',
  transform: transform
});
style({
  prop: 'size',
  cssProperty: 'height',
  transform: transform
});
var boxSizing = style({
  prop: 'boxSizing'
});
compose(width, maxWidth, minWidth, height, maxHeight, minHeight, boxSizing);

function createUnarySpacing(theme) {
  var themeSpacing = theme.spacing || 8;

  if (typeof themeSpacing === 'number') {
    return function (abs) {

      return themeSpacing * abs;
    };
  }

  if (Array.isArray(themeSpacing)) {
    return function (abs) {

      return themeSpacing[abs];
    };
  }

  if (typeof themeSpacing === 'function') {
    return themeSpacing;
  }

  return function () {
    return undefined;
  };
}

var fontFamily = style({
  prop: 'fontFamily',
  themeKey: 'typography'
});
var fontSize = style({
  prop: 'fontSize',
  themeKey: 'typography'
});
var fontStyle = style({
  prop: 'fontStyle',
  themeKey: 'typography'
});
var fontWeight = style({
  prop: 'fontWeight',
  themeKey: 'typography'
});
var letterSpacing = style({
  prop: 'letterSpacing'
});
var lineHeight = style({
  prop: 'lineHeight'
});
var textAlign = style({
  prop: 'textAlign'
});
compose(fontFamily, fontSize, fontStyle, fontWeight, letterSpacing, lineHeight, textAlign);

function createSpacing() {
  var spacingInput = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8;

  // Already transformed.
  if (spacingInput.mui) {
    return spacingInput;
  } // Material Design layouts are visually balanced. Most measurements align to an 8dp grid applied, which aligns both spacing and the overall layout.
  // Smaller components, such as icons and type, can align to a 4dp grid.
  // https://material.io/design/layout/understanding-layout.html#usage


  var transform = createUnarySpacing({
    spacing: spacingInput
  });

  var spacing = function spacing() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    if (args.length === 0) {
      return transform(1);
    }

    if (args.length === 1) {
      return transform(args[0]);
    }

    return args.map(function (argument) {
      if (typeof argument === 'string') {
        return argument;
      }

      var output = transform(argument);
      return typeof output === 'number' ? "".concat(output, "px") : output;
    }).join(' ');
  }; // Backward compatibility, to remove in v5.


  Object.defineProperty(spacing, 'unit', {
    get: function get() {

      return spacingInput;
    }
  });
  spacing.mui = true;
  return spacing;
}

// Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves
// to learn the context in which each easing should be used.
var easing = {
  // This is the most common easing curve.
  easeInOut: 'cubic-bezier(0.4, 0, 0.2, 1)',
  // Objects enter the screen at full velocity from off-screen and
  // slowly decelerate to a resting point.
  easeOut: 'cubic-bezier(0.0, 0, 0.2, 1)',
  // Objects leave the screen at full velocity. They do not decelerate when off-screen.
  easeIn: 'cubic-bezier(0.4, 0, 1, 1)',
  // The sharp curve is used by objects that may return to the screen at any time.
  sharp: 'cubic-bezier(0.4, 0, 0.6, 1)'
}; // Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations
// to learn when use what timing

var duration = {
  shortest: 150,
  shorter: 200,
  short: 250,
  // most basic recommended timing
  standard: 300,
  // this is to be used in complex animations
  complex: 375,
  // recommended when something is entering screen
  enteringScreen: 225,
  // recommended when something is leaving screen
  leavingScreen: 195
};

function formatMs(milliseconds) {
  return "".concat(Math.round(milliseconds), "ms");
}
/**
 * @param {string|Array} props
 * @param {object} param
 * @param {string} param.prop
 * @param {number} param.duration
 * @param {string} param.easing
 * @param {number} param.delay
 */


var transitions = {
  easing: easing,
  duration: duration,
  create: function create() {
    var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['all'];
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    var _options$duration = options.duration,
        durationOption = _options$duration === void 0 ? duration.standard : _options$duration,
        _options$easing = options.easing,
        easingOption = _options$easing === void 0 ? easing.easeInOut : _options$easing,
        _options$delay = options.delay,
        delay = _options$delay === void 0 ? 0 : _options$delay;
        _objectWithoutProperties(options, ["duration", "easing", "delay"]);

    return (Array.isArray(props) ? props : [props]).map(function (animatedProp) {
      return "".concat(animatedProp, " ").concat(typeof durationOption === 'string' ? durationOption : formatMs(durationOption), " ").concat(easingOption, " ").concat(typeof delay === 'string' ? delay : formatMs(delay));
    }).join(',');
  },
  getAutoHeightDuration: function getAutoHeightDuration(height) {
    if (!height) {
      return 0;
    }

    var constant = height / 36; // https://www.wolframalpha.com/input/?i=(4+%2B+15+*+(x+%2F+36+)+**+0.25+%2B+(x+%2F+36)+%2F+5)+*+10

    return Math.round((4 + 15 * Math.pow(constant, 0.25) + constant / 5) * 10);
  }
};

// We need to centralize the zIndex definitions as they work
// like global values in the browser.
var zIndex = {
  mobileStepper: 1000,
  speedDial: 1050,
  appBar: 1100,
  drawer: 1200,
  modal: 1300,
  snackbar: 1400,
  tooltip: 1500
};

function createTheme() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  var _options$breakpoints = options.breakpoints,
      breakpointsInput = _options$breakpoints === void 0 ? {} : _options$breakpoints,
      _options$mixins = options.mixins,
      mixinsInput = _options$mixins === void 0 ? {} : _options$mixins,
      _options$palette = options.palette,
      paletteInput = _options$palette === void 0 ? {} : _options$palette,
      spacingInput = options.spacing,
      _options$typography = options.typography,
      typographyInput = _options$typography === void 0 ? {} : _options$typography,
      other = _objectWithoutProperties(options, ["breakpoints", "mixins", "palette", "spacing", "typography"]);

  var palette = createPalette(paletteInput);
  var breakpoints = createBreakpoints(breakpointsInput);
  var spacing = createSpacing(spacingInput);
  var muiTheme = deepmerge({
    breakpoints: breakpoints,
    direction: 'ltr',
    mixins: createMixins(breakpoints, spacing, mixinsInput),
    overrides: {},
    // Inject custom styles
    palette: palette,
    props: {},
    // Provide default props
    shadows: shadows,
    typography: createTypography(palette, typographyInput),
    spacing: spacing,
    shape: shape,
    transitions: transitions,
    zIndex: zIndex
  }, other);

  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }

  muiTheme = args.reduce(function (acc, argument) {
    return deepmerge(acc, argument);
  }, muiTheme);

  return muiTheme;
}

var defaultTheme = createTheme();

withThemeCreator({
  defaultTheme: defaultTheme
});

var base = {
  typography: {
    fontSize: 14,
    htmlFontSize: 16,
    fontWeightLight: 300,
    fontWeightRegular: 400,
    fontWeightMedium: 600,
    fontFamily: ['"Source Sans Pro"', '"Segoe UI"', '"Helvetica Neue"', '-apple-system', 'Arial', 'sans-serif'].join(','),
    button: {
      textTransform: 'initial',
      fontWeight: 400
    }
  },
  shape: {
    borderRadius: 2
  },
  shadows: ['none', '0px 1px 2px 0px rgba(0,0,0,0.15)', '0px 1px 2px 0px rgba(0,0,0,0.15)', '0px 1px 2px 0px rgba(0,0,0,0.15)', '0px 1px 2px 0px rgba(0,0,0,0.15)', '0px 1px 2px 0px rgba(0,0,0,0.15)', '0px 1px 2px 0px rgba(0,0,0,0.15)', '0px 2px 4px 0px rgba(0,0,0,0.15)', '0px 2px 4px 0px rgba(0,0,0,0.15)', '0px 2px 4px 0px rgba(0,0,0,0.15)', '0px 2px 4px 0px rgba(0,0,0,0.15)', '0px 2px 4px 0px rgba(0,0,0,0.15)', '0px 2px 4px 0px rgba(0,0,0,0.15)', '0px 4px 10px 0px rgba(0,0,0,0.15)', '0px 4px 10px 0px rgba(0,0,0,0.15)', '0px 4px 10px 0px rgba(0,0,0,0.15)', '0px 4px 10px 0px rgba(0,0,0,0.15)', '0px 4px 10px 0px rgba(0,0,0,0.15)', '0px 4px 10px 0px rgba(0,0,0,0.15)', '0px 6px 20px 0px rgba(0,0,0,0.15)', '0px 6px 20px 0px rgba(0,0,0,0.15)', '0px 6px 20px 0px rgba(0,0,0,0.15)', '0px 6px 20px 0px rgba(0,0,0,0.15)', '0px 6px 20px 0px rgba(0,0,0,0.15)', '0px 6px 20px 0px rgba(0,0,0,0.15)'],
  props: {
    MuiButtonBase: {
      disableRipple: true,
      disableTouchRipple: true,
      focusRipple: false
    }
  }
};

const colors = {
  green: '#009845',
  greenPale: '#0AAF54',
  red: '#DC423F',
  redPale: '#F05551',
  blue: '#3F8AB3',
  bluePale: '#469DCD',
  // greyscale
  grey100: '#ffffff',
  grey98: '#FBFBFB',
  grey95: '#F2F2F2',
  grey90: '#E6E6E6',
  grey85: '#D9D9D9',
  grey55: '#8C8C8C',
  grey30: '#4D4D4D',
  grey25: '#404040',
  grey20: '#333333',
  grey15: '#262626',
  grey10: '#1A1A1A',
  grey5: '#0E0E0E',
  grey0: '#000000'
};

const light = {
  type: 'light',
  palette: {
    primary: {
      main: colors.grey25,
      contrastText: colors.grey100
    },
    secondary: {
      light: '#0AAF54',
      main: '#009845',
      dark: '#006937'
    },
    text: {
      primary: colors.grey25,
      secondary: 'rgba(0, 0, 0, 0.55)',
      disabled: 'rgba(0, 0, 0, 0.3)'
    },
    action: {
      active: colors.grey25,
      // color for actionable things like icon buttons
      hover: 'rgba(0, 0, 0, 0.03)',
      // color for hoverable things like list items
      hoverOpacity: 0.08,
      // used to fade primary/secondary colors
      selected: 'rgba(0, 0, 0, 0.05)',
      // focused things like list items
      disabled: 'rgba(0, 0, 0, 0.3)',
      // usually text
      disabledBackground: 'rgba(0, 0, 0, 0.12)'
    },
    background: {
      paper: colors.grey100,
      default: colors.grey100,
      // -- custom properties --
      lightest: colors.grey100,
      lighter: colors.grey98,
      darker: colors.grey95,
      darkest: colors.grey90
    },
    // --- custom stuff ---
    custom: {
      focusBorder: colors.blue,
      focusOutline: 'rgba(70, 157, 205, 0.3)',
      inputBackground: 'rgba(255, 255, 255, 1)'
    },
    selected: {
      main: colors.green,
      alternative: '#E4E4E4',
      excluded: '#BEBEBE',
      mainContrastText: colors.grey100,
      alternativeContrastText: colors.grey25,
      excludedContrastText: colors.grey25
    },
    btn: {
      normal: 'rgba(255, 255, 255, 0.6)',
      hover: 'rgba(0, 0, 0, 0.03)',
      active: 'rgba(0, 0, 0, 0.1)',
      disabled: 'rgba(255, 255, 255, 0.6)',
      border: 'rgba(0, 0, 0, 0.15)',
      borderHover: 'rgba(0, 0, 0, 0.15)'
    }
  }
};

const dark = {
  type: 'dark',
  palette: {
    primary: {
      main: colors.grey20,
      contrastText: colors.grey100
    },
    secondary: {
      light: '#0AAF54',
      main: '#009845',
      dark: '#006937'
    },
    text: {
      primary: colors.grey100,
      secondary: 'rgba(255, 255, 255, 0.6)',
      disabled: 'rgba(255, 255, 255, 0.3)'
    },
    action: {
      // active: 'rgba(0, 0, 0, 0.55)',
      active: colors.grey100,
      hover: 'rgba(255, 255, 255, 0.05)',
      hoverOpacity: 0.08,
      selected: 'rgba(0, 0, 0, 0.03)',
      disabled: 'rgba(255, 255, 255, 0.3)',
      disabledBackground: 'rgba(0, 0, 0, 0.12)'
    },
    divider: 'rgba(0,0,0,0.3)',
    background: {
      default: '#323232',
      paper: '#323232',
      // -- custom properties --
      lightest: colors.grey25,
      lighter: colors.grey20,
      darker: colors.grey15,
      darkest: colors.grey10
    },
    // -- custom --
    custom: {
      focusBorder: colors.blue,
      focusOutline: 'rgba(70, 157, 205, 0.3)',
      inputBackground: 'rgba(0, 0, 0, 0.2)'
    },
    selected: {
      main: colors.green,
      alternative: colors.grey20,
      excluded: colors.grey10,
      mainContrastText: colors.grey100,
      alternativeContrastText: colors.grey100,
      excludedContrastText: colors.grey100
    },
    btn: {
      normal: 'rgba(255, 255, 255, 0.15)',
      hover: 'rgba(255, 255, 255, 0.25)',
      active: 'rgba(0, 0, 0, 0.6)',
      disabled: 'rgba(255, 255, 255, 0.15)',
      border: 'rgba(0, 0, 0, 0.15)',
      borderHover: 'rgba(0, 0, 0, 0.30)'
    }
  }
};

const cache = {};

const overrides = theme => ({
  MuiTypography: {
    root: {
      color: theme.palette.text.primary
    }
  },
  MuiIconButton: {
    root: {
      padding: 7,
      borderRadius: 2,
      border: '1px solid transparent',
      // should ideally use $focusVisible, but that messes up focus in all other places where Iconbutton is used (Checkbox, Switch etc)
      '&:focus': {
        borderColor: theme.palette.custom.focusBorder,
        boxShadow: "0 0 0 2px ".concat(theme.palette.custom.focusOutline)
      }
    }
  },
  MuiOutlinedInput: {
    root: {
      backgroundColor: theme.palette.custom.inputBackground,
      '&:hover $notchedOutline': {
        borderColor: theme.palette.btn.border
      },
      '&$focused $notchedOutline': {
        borderColor: theme.palette.custom.focusBorder,
        borderWidth: 2
      }
    }
  },
  MuiButton: {
    outlined: {
      padding: '3px 11px',
      '&$focusVisible': {
        borderColor: theme.palette.custom.focusBorder,
        boxShadow: "0 0 0 2px ".concat(theme.palette.custom.focusOutline)
      }
    },
    contained: {
      color: theme.palette.text.primary,
      padding: '3px 11px',
      border: "1px solid ".concat(theme.palette.btn.border),
      backgroundColor: theme.palette.btn.normal,
      boxShadow: 'none',
      '&$focusVisible': {
        borderColor: theme.palette.custom.focusBorder,
        boxShadow: "0 0 0 2px ".concat(theme.palette.custom.focusOutline)
      },
      '&:hover': {
        backgroundColor: theme.palette.btn.hover,
        borderColor: theme.palette.btn.borderHover,
        boxShadow: 'none',
        '&$disabled': {
          backgroundColor: theme.palette.btn.disabled
        }
      },
      '&:active': {
        boxShadow: 'none',
        backgroundColor: theme.palette.btn.active
      },
      '&$disabled': {
        backgroundColor: theme.palette.btn.disabled
      }
    }
  },
  MuiExpansionPanelSummary: {
    content: {
      margin: '8px 0'
    }
  }
});

function create$3(definition) {
  let def = light;
  let name = '';

  if (typeof definition === 'string') {
    name = definition;

    if (definition !== 'light' && definition !== 'dark') {
      console.warn("Invalid theme: '".concat(definition, "'"));
    } else if (definition === 'dark') {
      def = dark;
    }
  }

  const key = JSON.stringify(def);

  if (cache[key]) {
    return cache[key];
  }

  const withDefaults = {
    palette: _objectSpread2(_objectSpread2({
      type: def.type
    }, base.palette), def.palette),
    typography: _objectSpread2({}, base.typography),
    shadows: base.shadows,
    props: _objectSpread2({}, base.props),
    shape: _objectSpread2({}, base.shape)
  };
  cache[key] = createTheme(_objectSpread2(_objectSpread2({}, withDefaults), {}, {
    overrides: overrides(withDefaults)
  }));
  cache[key].name = name;
  return cache[key];
}

var InstanceContext = React.createContext({
  language: null,
  theme: null,
  translator: null,
  constraints: {}
});

var createKeyStore = (function () {
  let initialState = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  let applyMiddleware = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : () => {};
  const sharedState = initialState;
  const hookListeners = [];
  const store = {
    get: key => sharedState[key],
    set: (key, value) => {
      if (typeof key === 'undefined' || typeof key === 'object') {
        throw new Error("Invalid key: ".concat(JSON.stringify(key)));
      }

      sharedState[key] = value;
      applyMiddleware({
        type: 'SET',
        value
      });
      return value;
    },
    clear: key => {
      if (typeof key === 'undefined' || typeof key === 'object') {
        throw new Error("Invalid key: ".concat(JSON.stringify(key)));
      }

      sharedState[key] = null;
    },
    dispatch: forceNewState => {
      hookListeners.forEach(listener => listener(forceNewState ? {} : sharedState));
    }
  };

  const useKeyStore = () => {
    const [, setState] = useState$1(sharedState);
    useEffect$1(() => {
      hookListeners.push(setState);
      return () => {
        const ix = hookListeners.indexOf(setState);
        hookListeners.splice(ix, 1);
      };
    }, [setState]);
    return [store];
  };

  return [useKeyStore, store];
});

const [useRpcResultStore, rpcResultStore] = createKeyStore({});
const [useRpcRequestStore, rpcRequestStore] = createKeyStore({});
const [useRpcRequestSessionModelStore, rpcRequestSessionModelStore] = createKeyStore({});
const [useRpcRequestModelStore, rpcRequestModelStore] = createKeyStore({});
const [useModelChangedStore, modelChangedStore] = createKeyStore({});
const [, modelInitializedStore] = createKeyStore({});

const modelStoreMiddleware = _ref => {
  let {
    type,
    value: model
  } = _ref;
  const initialized = modelInitializedStore.get(model.id);
  modelInitializedStore.set(model.id, {});

  const onChanged = () => {
    rpcRequestStore.clear(model.id);
    modelChangedStore.set(model.id, {});
    modelChangedStore.dispatch(true); // Force new state to trigger hooks
  };

  const unsubscribe = () => {
    model.removeListener('changed', onChanged);
    rpcResultStore.clear(model.id);
    rpcRequestStore.clear(model.id);
    rpcRequestSessionModelStore.clear(model.id);
    rpcRequestModelStore.clear(model.id);
    modelChangedStore.clear(model.id);
    modelInitializedStore.clear(model.id);
  };

  switch (type) {
    case 'SET':
      if (!initialized) {
        model.on('changed', onChanged);
        model.once('closed', () => {
          unsubscribe();
        });
      }

      break;
  }

  return unsubscribe;
};

const [useModelStore, modelStore] = createKeyStore({}, modelStoreMiddleware);

const subscribe = model => {
  const unsubscribe = modelStoreMiddleware({
    type: 'SET',
    value: model
  });
  return () => {
    unsubscribe();
    modelStore.clear(model.id);
  };
};

const rpcReducer = (state, action) => {
  const {
    rpcResultStore,
    key,
    method
  } = action;
  let newState;

  switch (action.type) {
    case 'INVALID':
      {
        newState = _objectSpread2(_objectSpread2({}, state), {}, {
          valid: false,
          invalid: true,
          validating: true,
          canCancel: true,
          canRetry: false,
          rpcRetry: false
        });
        break;
      }

    case 'VALID':
      {
        newState = {
          result: _objectSpread2({}, action.result),
          invalid: false,
          valid: true,
          validating: false,
          canCancel: false,
          canRetry: false,
          rpcRetry: false
        };
        break;
      }

    case 'CANCELLED':
      {
        newState = _objectSpread2(_objectSpread2({}, state), {}, {
          invalid: true,
          valid: false,
          validating: false,
          canCancel: false,
          canRetry: true,
          rpcRetry: false
        });
        break;
      }

    default:
      throw new Error('Undefined action');
  }

  let sharedState = rpcResultStore.get(key);

  if (!sharedState) {
    sharedState = {};
  }

  sharedState[method] = newState;
  rpcResultStore.set(key, sharedState);
  return newState;
};

function useRpc(model, method) {
  const key = model ? "".concat(model.id) : null;
  const [rpcResultStore] = useRpcResultStore();
  const [state, dispatch] = useReducer(rpcReducer, key ? rpcResultStore.get(key) : null);
  const [modelChangedStore] = useModelChangedStore();
  const [rpcRequestStore] = useRpcRequestStore();
  let rpcShared;

  if (key) {
    rpcShared = rpcRequestStore.get(key);

    if (!rpcShared) {
      rpcShared = {};
      rpcRequestStore.set(key, rpcShared);
    }
  }

  const call = async skipRetry => {
    let cache = rpcShared[method];

    if (!cache || cache && cache.rpcRetry) {
      const rpc = model[method]();
      cache = {
        rpc,
        rpcRetry: false
      };
      rpcShared[method] = cache;
      dispatch({
        type: 'INVALID',
        method,
        key,
        model,
        rpcResultStore,
        canCancel: true
      });
    }

    try {
      // await sleep(5000);
      const result = await cache.rpc;
      dispatch({
        type: 'VALID',
        result,
        key,
        method,
        model,
        rpcResultStore
      });
    } catch (err) {
      if (err.code === 15 && !skipRetry) {
        // Request aborted. This will be called multiple times by hooks only retry once
        if (!cache.rpcRetry) {
          cache.rpcRetry = true;
        }

        call(true);
      }
    }
  };

  const longrunning = {
    cancel: async () => {
      const global = model.session.getObjectApi({
        handle: -1
      });
      await global.cancelRequest(rpcShared[method].rpc.requestId);
      dispatch({
        type: 'CANCELLED',
        key,
        method,
        model,
        rpcResultStore
      });
    },
    retry: () => {
      rpcShared[method].rpcRetry = true;
      call();
    }
  };
  useEffect$1(() => {
    if (!model) return undefined;
    call();
    return undefined;
  }, [model, modelChangedStore.get(model && model.id), key, method]);
  return [// Result
  state && state.result, {
    validating: state && state.validating,
    canCancel: state && state.canCancel,
    canRetry: state && state.canRetry
  }, // Long running api e.g cancel retry
  longrunning];
}

function useLayout$1(model) {
  return useRpc(model, 'getLayout');
}
function useAppLayout$1(model) {
  return useRpc(model, 'getAppLayout');
}

function useSessionModel(definition, app) {
  const key = app ? "".concat(app.id, "/").concat(JSON.stringify(definition)) : null;
  const [modelStore] = useModelStore();
  const [rpcRequestSessionModelStore] = useRpcRequestSessionModelStore();
  const [model, setModel] = useState$1();
  let rpcShared;

  if (key) {
    rpcShared = rpcRequestSessionModelStore.get(key);
  }

  for (var _len = arguments.length, deps = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
    deps[_key - 2] = arguments[_key];
  }

  useEffect$1(() => {
    if (!app) {
      return;
    } // Create new session object


    const create = async () => {
      if (!rpcShared) {
        const rpc = app.createSessionObject(definition);
        rpcShared = rpc;
        rpcRequestSessionModelStore.set(key, rpcShared);
      }

      const newModel = await rpcShared;
      modelStore.set(key, newModel);
      setModel(newModel);
    };

    create();
  }, [app, ...deps]);
  return [model];
}

const definition = {
  qInfo: {
    qType: 'current-selections'
  },
  qSelectionObjectDef: {
    qStateName: '$'
  },
  alternateStates: []
};
function useCurrentSelectionsModel(app) {
  return useSessionModel(definition, app);
}

const patchAlternateState = (currentSelectionsModel, currentSelectionsLayout, appLayout) => {
  const states = [...(appLayout.qStateNames || [])].map(s => ({
    stateName: s,
    // need this as reference in selection toolbar since qSelectionObject.qStateName is not in the layout
    qSelectionObjectDef: {
      qStateName: s
    }
  }));
  const existingStates = (currentSelectionsLayout && currentSelectionsLayout.alternateStates ? currentSelectionsLayout.alternateStates.map(s => s.stateName) : []).join('::');
  const newStates = (appLayout.qStateNames || []).map(s => s).join('::');

  if (existingStates !== newStates) {
    currentSelectionsModel.applyPatches([{
      qOp: 'replace',
      qPath: '/alternateStates',
      qValue: JSON.stringify(states)
    }], true);
  }
};

function useAppSelectionsNavigation(app) {
  const [currentSelectionsModel] = useCurrentSelectionsModel(app);
  const [currentSelectionsLayout] = useLayout$1(currentSelectionsModel);
  const [appLayout] = useAppLayout$1(app);
  const [navigationState, setNavigationState] = useState$1(null);
  useEffect$1(() => {
    if (!appLayout || !currentSelectionsModel || !currentSelectionsLayout) return;
    patchAlternateState(currentSelectionsModel, currentSelectionsLayout, appLayout);
  }, [appLayout, currentSelectionsModel, currentSelectionsLayout]);
  useEffect$1(() => {
    if (!currentSelectionsLayout) return;
    let canGoBack = false;
    let canGoForward = false;
    let canClear = false;
    [currentSelectionsLayout, ...(currentSelectionsLayout.alternateStates || [])].forEach(state => {
      canGoBack = canGoBack || state.qSelectionObject && state.qSelectionObject.qBackCount > 0;
      canGoForward = canGoForward || state.qSelectionObject && state.qSelectionObject.qForwardCount > 0;
      canClear = canClear || (state.qSelectionObject && state.qSelectionObject.qSelections || []).filter(s => s.qLocked !== true).length > 0;
    });
    setNavigationState({
      canGoBack,
      canGoForward,
      canClear
    });
  }, [currentSelectionsLayout]);
  return [navigationState, currentSelectionsModel, currentSelectionsLayout];
}

const [useAppSelectionsStore, appSelectionsStore] = createKeyStore({});
const [useAppModalStore, appModalStore] = createKeyStore({});
const [useObjectSelectionsStore, objectSelectionsStore] = createKeyStore({});
const [useModalObjectStore, modalObjectStore] = createKeyStore({});

/* eslint no-underscore-dangle: 0 */

function createAppSelections(_ref) {
  let {
    app,
    currentSelectionsLayout,
    navState
  } = _ref;
  const key = "".concat(app.id);

  const end = async function () {
    let accept = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
    const model = modalObjectStore.get(key);

    if (model) {
      await model.endSelections(accept);
      modalObjectStore.clear(key);
      const objectSelections = objectSelectionsStore.get(model.id);
      objectSelections.emit('deactivated');
    }
  };

  const begin = async function (model, path) {
    let accept = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

    // Quick return if it's already in modal
    if (model === modalObjectStore.get(key)) {
      return;
    } // If other model is in modal state end it


    end(accept); // Pending modal

    modalObjectStore.set(key, model);
    const p = Array.isArray(path) ? path : [path];

    const beginSelections = async skipRetry => {
      try {
        await model.beginSelections(p);
        modalObjectStore.set(key, model); // We have a modal
      } catch (err) {
        if (err.code === 6003 && !skipRetry) {
          await app.abortModal(accept);
          beginSelections(true);
        } else {
          modalObjectStore.clear(key); // No modal
        }
      }
    };

    await beginSelections();
  };

  const appModal = {
    begin,
    end
  };
  appModalStore.set(key, appModal);
  /**
   * @class
   * @alias AppSelections
   */

  const appSelections = {
    model: app,

    isInModal() {
      return !!modalObjectStore.get(key);
    },

    isModal(object) {
      // TODO check model state
      return object ? modalObjectStore.get(key) === object : !!modalObjectStore.get(key);
    },

    canGoForward() {
      return navState.canGoForward;
    },

    canGoBack() {
      return navState.canGoBack;
    },

    canClear() {
      return navState.canClear;
    },

    layout() {
      return currentSelectionsLayout;
    },

    forward() {
      return appModal.end().then(() => app.forward());
    },

    back() {
      return appModal.end().then(() => app.back());
    },

    clear() {
      return appModal.end().then(() => app.clearAll());
    },

    clearField(field) {
      let state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '$';
      return appModal.end().then(() => app.getField(field, state).then(f => f.clear()));
    }

  };
  return appSelections;
}

function useAppSelections(app) {
  if (!app.session) {
    // assume the app is mocked if session is undefined
    return [];
  }

  const [navState, currentSelectionsModel, currentSelectionsLayout] = useAppSelectionsNavigation(app);
  const [appSelectionsStore] = useAppSelectionsStore();
  const key = app ? app.id : null;
  let appSelections = appSelectionsStore.get(key);
  useEffect$1(() => {
    if (!app || !currentSelectionsModel || !currentSelectionsLayout || !navState || appSelections) return;
    appSelections = createAppSelections({
      app,
      currentSelectionsLayout,
      navState
    });
    appSelectionsStore.set(key, appSelections);
    appSelectionsStore.dispatch(true);
  }, [app, currentSelectionsModel, currentSelectionsLayout, navState]);
  return [appSelections, navState];
}

const NEBULA_VERSION_HASH = "32d7" ;
let counter = 0;
const NebulaApp = forwardRef((_ref, ref) => {
  let {
    initialContext,
    app
  } = _ref;
  const [appSelections] = useAppSelections(app);
  const [context, setContext] = useState$1(initialContext);
  const [muiThemeName, setMuiThemeName] = useState$1();
  const {
    theme,
    generator
  } = useMemo$1(() => ({
    theme: create$3(muiThemeName),
    generator: createGenerateClassName({
      productionPrefix: "".concat(NEBULA_VERSION_HASH),
      disableGlobal: true,
      seed: "njs-".concat(counter++)
    })
  }), [muiThemeName]);
  const [components, setComponents] = useState$1([]);
  useImperativeHandle$1(ref, () => ({
    addComponent(component) {
      setComponents([...components, component]);
    },

    removeComponent(component) {
      const ix = components.indexOf(component);

      if (ix !== -1) {
        components.splice(ix, 1);
        setComponents([...components]);
      }
    },

    setMuiThemeName,
    setContext,
    getAppSelections: () => appSelections
  }));
  return /*#__PURE__*/React.createElement(StylesProvider, {
    generateClassName: generator
  }, /*#__PURE__*/React.createElement(ThemeProvider, {
    theme: theme
  }, /*#__PURE__*/React.createElement(InstanceContext.Provider, {
    value: context
  }, components)));
});
function boot(_ref2) {
  let {
    app,
    context
  } = _ref2;
  let resolveRender;
  const rendered = new Promise(resolve => {
    resolveRender = resolve;
  });
  const appRef = React.createRef();
  const element = document.createElement('div');
  element.style.display = 'none';
  element.setAttribute('data-nebulajs-version', "2.12.0" );
  element.setAttribute('data-app-id', app.id);
  document.body.appendChild(element);
  ReactDOM.render( /*#__PURE__*/React.createElement(NebulaApp, {
    ref: appRef,
    app: app,
    initialContext: context
  }), element, resolveRender);
  const cells = {};
  return [{
    toggleFocusOfCells(cellIdToFocus) {
      Object.keys(cells).forEach(i => {
        cells[i].current.toggleFocus(i === cellIdToFocus);
      });
    },

    cells,

    addCell(id, cell) {
      cells[id] = cell;
    },

    add(component) {
      (async () => {
        await rendered;
        appRef.current.addComponent(component);
      })();
    },

    remove(component) {
      (async () => {
        await rendered;
        appRef.current.removeComponent(component);
      })();
    },

    setMuiThemeName(themeName) {
      (async () => {
        await rendered;
        appRef.current.setMuiThemeName(themeName);
      })();
    },

    context(ctx) {
      (async () => {
        await rendered;
        appRef.current.setContext(ctx);
      })();
    },

    getAppSelections: async () => {
      await rendered;
      return appRef.current.getAppSelections();
    }
  }, appRef, rendered];
}

function useRect$1() {
  const [node, setNode] = useState$1();
  const [rect, setRect] = useState$1();
  const callbackRef = useCallback(ref => {
    if (!ref) {
      return;
    }

    setNode(ref);
  }, []);

  const handleResize = () => {
    const {
      left,
      top,
      width,
      height
    } = node.getBoundingClientRect();
    setRect({
      left,
      top,
      width,
      height
    });
  };

  useLayoutEffect$1(() => {
    if (!node) {
      return undefined;
    }

    if (typeof ResizeObserver === 'function') {
      let resizeObserver = new ResizeObserver(handleResize);
      resizeObserver.observe(node);
      return () => {
        resizeObserver.unobserve(node);
        resizeObserver.disconnect(node);
        resizeObserver = null;
      };
    }

    handleResize();
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [node]);
  return [callbackRef, rect, node];
}

function getFontSize(size) {
  if (size === 'large') {
    return '20px';
  }

  if (size === 'small') {
    return '12px';
  }

  return '16px';
}

function SvgIcon(_ref) {
  let {
    size,
    style = {},
    viewBox = '0 0 16 16',
    shapes = []
  } = _ref;

  const s = _objectSpread2({
    fontSize: getFontSize(size),
    display: 'inline-block',
    fontStyle: 'normal',
    lineHeight: '0',
    textAlign: 'center',
    textTransform: 'none',
    verticalAlign: '-.125em',
    textRendering: 'optimizeLegibility',
    WebkitFontSmoothing: 'antialiased',
    MozOsxFontSmoothing: 'grayscale'
  }, style);

  return /*#__PURE__*/React.createElement("i", {
    style: s
  }, /*#__PURE__*/React.createElement("svg", {
    xmlns: "http://www.w3.org/2000/svg",
    width: "1em",
    height: "1em",
    viewBox: viewBox,
    fill: "currentColor"
  }, shapes.map((_ref2, ix) => {
    let {
      type: Type,
      attrs
    } = _ref2;
    return (
      /*#__PURE__*/
      // eslint-disable-next-line react/no-array-index-key
      React.createElement(Type, _extends$4({
        key: ix
      }, attrs))
    );
  })));
}

const remove = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M9.41421356,8 L11.8890873,5.52512627 C12.065864,5.34834957 12.0305087,4.95944084 11.8183766,4.74730881 L11.2526912,4.18162338 C11.0405592,3.96949135 10.6516504,3.93413601 10.4748737,4.1109127 L8,6.58578644 L5.52512627,4.1109127 C5.34834957,3.93413601 4.95944084,3.96949135 4.74730881,4.18162338 L4.25233406,4.67659813 C3.96949135,4.95944084 3.93413601,5.34834957 4.1109127,5.52512627 L6.58578644,8 L4.1109127,10.4748737 C3.93413601,10.6516504 3.96949135,11.0405592 4.18162338,11.2526912 L4.67659813,11.7476659 C4.95944084,12.0305087 5.34834957,12.065864 5.52512627,11.8890873 L8,9.41421356 L10.4748737,11.8890873 C10.6516504,12.065864 11.0405592,12.0305087 11.2526912,11.8183766 L11.8183766,11.2526912 C12.0305087,11.0405592 12.065864,10.6516504 11.8890873,10.4748737 L9.41421356,8 Z M8,0 C12.4,0 16,3.6 16,8 C16,12.4 12.4,16 8,16 C3.6,16 0,12.4 0,8 C0,3.6 3.6,0 8,0 Z'
    }
  }]
});

var Remove = (props => SvgIcon(remove(props)));

const lock = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M13,7 L8,7 L13,7 L13,4.98151367 C13,2.23029964 10.7614237,0 8,0 C5.23857625,0 3,2.23029964 3,4.98151367 L3,7 L3.75,7 L3,7 L4.5,7 L4.5,5.33193359 C4.5,3.21561511 5.54860291,1.5 8,1.5 C10.4513971,1.5 11.5,3.21561511 11.5,5.33193359 L11.5,7 L12.25,7 L3,7 C2.44771525,7 2,7.44771525 2,8 L2,15 C2,15.5522847 2.44771525,16 3,16 L13,16 C13.5522847,16 14,15.5522847 14,15 L14,8 C14,7.44771525 13.5522847,7 13,7 L3,7 L13,7 Z'
    }
  }]
});

var Lock = (props => SvgIcon(lock(props)));

const unlock = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M2.5,7 L11,7 C11.5522847,7 12,7.44771525 12,8 L12,15 C12,15.5522847 11.5522847,16 11,16 L1,16 C0.44771525,16 0,15.5522847 0,15 L0,8 C0,7.44771525 0.44771525,7 1,7 L1,4.98151367 C1,2.23029964 3.23857625,0 6,0 C8.4241995,0 10.4454541,1.71883353 10.9029715,4 L9.34209114,4 C8.9671727,2.54028848 7.9088888,1.5 6,1.5 C3.54860291,1.5 2.5,3.21561511 2.5,5.33193359 L2.5,7 Z'
    }
  }]
});

var Unlock = (props => SvgIcon(unlock(props)));

function _extends$1() {
  _extends$1 = Object.assign || function (target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];

      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }

    return target;
  };

  return _extends$1.apply(this, arguments);
}

function _assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return self;
}

function _inheritsLoose(subClass, superClass) {
  subClass.prototype = Object.create(superClass.prototype);
  subClass.prototype.constructor = subClass;
  subClass.__proto__ = superClass;
}

function areInputsEqual(newInputs, lastInputs) {
  if (newInputs.length !== lastInputs.length) {
    return false;
  }

  for (var i = 0; i < newInputs.length; i++) {
    if (newInputs[i] !== lastInputs[i]) {
      return false;
    }
  }

  return true;
}

function index$1 (resultFn, isEqual) {
  if (isEqual === void 0) {
    isEqual = areInputsEqual;
  }

  var lastThis;
  var lastArgs = [];
  var lastResult;
  var calledOnce = false;

  var result = function result() {
    for (var _len = arguments.length, newArgs = new Array(_len), _key = 0; _key < _len; _key++) {
      newArgs[_key] = arguments[_key];
    }

    if (calledOnce && lastThis === this && isEqual(newArgs, lastArgs)) {
      return lastResult;
    }

    lastResult = resultFn.apply(this, newArgs);
    calledOnce = true;
    lastThis = this;
    lastArgs = newArgs;
    return lastResult;
  };

  return result;
}

// Animation frame based implementation of setTimeout.
// Inspired by Joe Lambert, https://gist.github.com/joelambert/1002116#file-requesttimeout-js
var hasNativePerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';
var now = hasNativePerformanceNow ? function () {
  return performance.now();
} : function () {
  return Date.now();
};
function cancelTimeout(timeoutID) {
  cancelAnimationFrame(timeoutID.id);
}
function requestTimeout(callback, delay) {
  var start = now();

  function tick() {
    if (now() - start >= delay) {
      callback.call(null);
    } else {
      timeoutID.id = requestAnimationFrame(tick);
    }
  }

  var timeoutID = {
    id: requestAnimationFrame(tick)
  };
  return timeoutID;
}
var cachedRTLResult = null; // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
// Chrome does not seem to adhere; its scrollLeft values are positive (measured relative to the left).
// Safari's elastic bounce makes detecting this even more complicated wrt potential false positives.
// The safest way to check this is to intentionally set a negative offset,
// and then verify that the subsequent "scroll" event matches the negative offset.
// If it does not match, then we can assume a non-standard RTL scroll implementation.

function getRTLOffsetType(recalculate) {
  if (recalculate === void 0) {
    recalculate = false;
  }

  if (cachedRTLResult === null || recalculate) {
    var outerDiv = document.createElement('div');
    var outerStyle = outerDiv.style;
    outerStyle.width = '50px';
    outerStyle.height = '50px';
    outerStyle.overflow = 'scroll';
    outerStyle.direction = 'rtl';
    var innerDiv = document.createElement('div');
    var innerStyle = innerDiv.style;
    innerStyle.width = '100px';
    innerStyle.height = '100px';
    outerDiv.appendChild(innerDiv);
    document.body.appendChild(outerDiv);

    if (outerDiv.scrollLeft > 0) {
      cachedRTLResult = 'positive-descending';
    } else {
      outerDiv.scrollLeft = 1;

      if (outerDiv.scrollLeft === 0) {
        cachedRTLResult = 'negative';
      } else {
        cachedRTLResult = 'positive-ascending';
      }
    }

    document.body.removeChild(outerDiv);
    return cachedRTLResult;
  }

  return cachedRTLResult;
}

var IS_SCROLLING_DEBOUNCE_INTERVAL$1 = 150;

var defaultItemKey$1 = function defaultItemKey(index, data) {
  return index;
}; // In DEV mode, this Set helps us only log a warning once per component instance.

function createListComponent(_ref) {
  var _class;

  var getItemOffset = _ref.getItemOffset,
      getEstimatedTotalSize = _ref.getEstimatedTotalSize,
      getItemSize = _ref.getItemSize,
      getOffsetForIndexAndAlignment = _ref.getOffsetForIndexAndAlignment,
      getStartIndexForOffset = _ref.getStartIndexForOffset,
      getStopIndexForStartIndex = _ref.getStopIndexForStartIndex,
      initInstanceProps = _ref.initInstanceProps,
      shouldResetStyleCacheOnItemSizeChange = _ref.shouldResetStyleCacheOnItemSizeChange,
      validateProps = _ref.validateProps;
  return _class = /*#__PURE__*/function (_PureComponent) {
    _inheritsLoose(List, _PureComponent);

    // Always use explicit constructor for React components.
    // It produces less code after transpilation. (#26)
    // eslint-disable-next-line no-useless-constructor
    function List(props) {
      var _this;

      _this = _PureComponent.call(this, props) || this;
      _this._instanceProps = initInstanceProps(_this.props, _assertThisInitialized(_this));
      _this._outerRef = void 0;
      _this._resetIsScrollingTimeoutId = null;
      _this.state = {
        instance: _assertThisInitialized(_this),
        isScrolling: false,
        scrollDirection: 'forward',
        scrollOffset: typeof _this.props.initialScrollOffset === 'number' ? _this.props.initialScrollOffset : 0,
        scrollUpdateWasRequested: false
      };
      _this._callOnItemsRendered = void 0;
      _this._callOnItemsRendered = index$1(function (overscanStartIndex, overscanStopIndex, visibleStartIndex, visibleStopIndex) {
        return _this.props.onItemsRendered({
          overscanStartIndex: overscanStartIndex,
          overscanStopIndex: overscanStopIndex,
          visibleStartIndex: visibleStartIndex,
          visibleStopIndex: visibleStopIndex
        });
      });
      _this._callOnScroll = void 0;
      _this._callOnScroll = index$1(function (scrollDirection, scrollOffset, scrollUpdateWasRequested) {
        return _this.props.onScroll({
          scrollDirection: scrollDirection,
          scrollOffset: scrollOffset,
          scrollUpdateWasRequested: scrollUpdateWasRequested
        });
      });
      _this._getItemStyle = void 0;

      _this._getItemStyle = function (index) {
        var _this$props = _this.props,
            direction = _this$props.direction,
            itemSize = _this$props.itemSize,
            layout = _this$props.layout;

        var itemStyleCache = _this._getItemStyleCache(shouldResetStyleCacheOnItemSizeChange && itemSize, shouldResetStyleCacheOnItemSizeChange && layout, shouldResetStyleCacheOnItemSizeChange && direction);

        var style;

        if (itemStyleCache.hasOwnProperty(index)) {
          style = itemStyleCache[index];
        } else {
          var _offset = getItemOffset(_this.props, index, _this._instanceProps);

          var size = getItemSize(_this.props, index, _this._instanceProps); // TODO Deprecate direction "horizontal"

          var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
          var isRtl = direction === 'rtl';
          var offsetHorizontal = isHorizontal ? _offset : 0;
          itemStyleCache[index] = style = {
            position: 'absolute',
            left: isRtl ? undefined : offsetHorizontal,
            right: isRtl ? offsetHorizontal : undefined,
            top: !isHorizontal ? _offset : 0,
            height: !isHorizontal ? size : '100%',
            width: isHorizontal ? size : '100%'
          };
        }

        return style;
      };

      _this._getItemStyleCache = void 0;
      _this._getItemStyleCache = index$1(function (_, __, ___) {
        return {};
      });

      _this._onScrollHorizontal = function (event) {
        var _event$currentTarget = event.currentTarget,
            clientWidth = _event$currentTarget.clientWidth,
            scrollLeft = _event$currentTarget.scrollLeft,
            scrollWidth = _event$currentTarget.scrollWidth;

        _this.setState(function (prevState) {
          if (prevState.scrollOffset === scrollLeft) {
            // Scroll position may have been updated by cDM/cDU,
            // In which case we don't need to trigger another render,
            // And we don't want to update state.isScrolling.
            return null;
          }

          var direction = _this.props.direction;
          var scrollOffset = scrollLeft;

          if (direction === 'rtl') {
            // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
            // This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).
            // It's also easier for this component if we convert offsets to the same format as they would be in for ltr.
            // So the simplest solution is to determine which browser behavior we're dealing with, and convert based on it.
            switch (getRTLOffsetType()) {
              case 'negative':
                scrollOffset = -scrollLeft;
                break;

              case 'positive-descending':
                scrollOffset = scrollWidth - clientWidth - scrollLeft;
                break;
            }
          } // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.


          scrollOffset = Math.max(0, Math.min(scrollOffset, scrollWidth - clientWidth));
          return {
            isScrolling: true,
            scrollDirection: prevState.scrollOffset < scrollLeft ? 'forward' : 'backward',
            scrollOffset: scrollOffset,
            scrollUpdateWasRequested: false
          };
        }, _this._resetIsScrollingDebounced);
      };

      _this._onScrollVertical = function (event) {
        var _event$currentTarget2 = event.currentTarget,
            clientHeight = _event$currentTarget2.clientHeight,
            scrollHeight = _event$currentTarget2.scrollHeight,
            scrollTop = _event$currentTarget2.scrollTop;

        _this.setState(function (prevState) {
          if (prevState.scrollOffset === scrollTop) {
            // Scroll position may have been updated by cDM/cDU,
            // In which case we don't need to trigger another render,
            // And we don't want to update state.isScrolling.
            return null;
          } // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.


          var scrollOffset = Math.max(0, Math.min(scrollTop, scrollHeight - clientHeight));
          return {
            isScrolling: true,
            scrollDirection: prevState.scrollOffset < scrollOffset ? 'forward' : 'backward',
            scrollOffset: scrollOffset,
            scrollUpdateWasRequested: false
          };
        }, _this._resetIsScrollingDebounced);
      };

      _this._outerRefSetter = function (ref) {
        var outerRef = _this.props.outerRef;
        _this._outerRef = ref;

        if (typeof outerRef === 'function') {
          outerRef(ref);
        } else if (outerRef != null && typeof outerRef === 'object' && outerRef.hasOwnProperty('current')) {
          outerRef.current = ref;
        }
      };

      _this._resetIsScrollingDebounced = function () {
        if (_this._resetIsScrollingTimeoutId !== null) {
          cancelTimeout(_this._resetIsScrollingTimeoutId);
        }

        _this._resetIsScrollingTimeoutId = requestTimeout(_this._resetIsScrolling, IS_SCROLLING_DEBOUNCE_INTERVAL$1);
      };

      _this._resetIsScrolling = function () {
        _this._resetIsScrollingTimeoutId = null;

        _this.setState({
          isScrolling: false
        }, function () {
          // Clear style cache after state update has been committed.
          // This way we don't break pure sCU for items that don't use isScrolling param.
          _this._getItemStyleCache(-1, null);
        });
      };

      return _this;
    }

    List.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
      validateSharedProps$1(nextProps, prevState);
      validateProps(nextProps);
      return null;
    };

    var _proto = List.prototype;

    _proto.scrollTo = function scrollTo(scrollOffset) {
      scrollOffset = Math.max(0, scrollOffset);
      this.setState(function (prevState) {
        if (prevState.scrollOffset === scrollOffset) {
          return null;
        }

        return {
          scrollDirection: prevState.scrollOffset < scrollOffset ? 'forward' : 'backward',
          scrollOffset: scrollOffset,
          scrollUpdateWasRequested: true
        };
      }, this._resetIsScrollingDebounced);
    };

    _proto.scrollToItem = function scrollToItem(index, align) {
      if (align === void 0) {
        align = 'auto';
      }

      var itemCount = this.props.itemCount;
      var scrollOffset = this.state.scrollOffset;
      index = Math.max(0, Math.min(index, itemCount - 1));
      this.scrollTo(getOffsetForIndexAndAlignment(this.props, index, align, scrollOffset, this._instanceProps));
    };

    _proto.componentDidMount = function componentDidMount() {
      var _this$props2 = this.props,
          direction = _this$props2.direction,
          initialScrollOffset = _this$props2.initialScrollOffset,
          layout = _this$props2.layout;

      if (typeof initialScrollOffset === 'number' && this._outerRef != null) {
        var outerRef = this._outerRef; // TODO Deprecate direction "horizontal"

        if (direction === 'horizontal' || layout === 'horizontal') {
          outerRef.scrollLeft = initialScrollOffset;
        } else {
          outerRef.scrollTop = initialScrollOffset;
        }
      }

      this._callPropsCallbacks();
    };

    _proto.componentDidUpdate = function componentDidUpdate() {
      var _this$props3 = this.props,
          direction = _this$props3.direction,
          layout = _this$props3.layout;
      var _this$state = this.state,
          scrollOffset = _this$state.scrollOffset,
          scrollUpdateWasRequested = _this$state.scrollUpdateWasRequested;

      if (scrollUpdateWasRequested && this._outerRef != null) {
        var outerRef = this._outerRef; // TODO Deprecate direction "horizontal"

        if (direction === 'horizontal' || layout === 'horizontal') {
          if (direction === 'rtl') {
            // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements.
            // This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left).
            // So we need to determine which browser behavior we're dealing with, and mimic it.
            switch (getRTLOffsetType()) {
              case 'negative':
                outerRef.scrollLeft = -scrollOffset;
                break;

              case 'positive-ascending':
                outerRef.scrollLeft = scrollOffset;
                break;

              default:
                var clientWidth = outerRef.clientWidth,
                    scrollWidth = outerRef.scrollWidth;
                outerRef.scrollLeft = scrollWidth - clientWidth - scrollOffset;
                break;
            }
          } else {
            outerRef.scrollLeft = scrollOffset;
          }
        } else {
          outerRef.scrollTop = scrollOffset;
        }
      }

      this._callPropsCallbacks();
    };

    _proto.componentWillUnmount = function componentWillUnmount() {
      if (this._resetIsScrollingTimeoutId !== null) {
        cancelTimeout(this._resetIsScrollingTimeoutId);
      }
    };

    _proto.render = function render() {
      var _this$props4 = this.props,
          children = _this$props4.children,
          className = _this$props4.className,
          direction = _this$props4.direction,
          height = _this$props4.height,
          innerRef = _this$props4.innerRef,
          innerElementType = _this$props4.innerElementType,
          innerTagName = _this$props4.innerTagName,
          itemCount = _this$props4.itemCount,
          itemData = _this$props4.itemData,
          _this$props4$itemKey = _this$props4.itemKey,
          itemKey = _this$props4$itemKey === void 0 ? defaultItemKey$1 : _this$props4$itemKey,
          layout = _this$props4.layout,
          outerElementType = _this$props4.outerElementType,
          outerTagName = _this$props4.outerTagName,
          style = _this$props4.style,
          useIsScrolling = _this$props4.useIsScrolling,
          width = _this$props4.width;
      var isScrolling = this.state.isScrolling; // TODO Deprecate direction "horizontal"

      var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
      var onScroll = isHorizontal ? this._onScrollHorizontal : this._onScrollVertical;

      var _this$_getRangeToRend = this._getRangeToRender(),
          startIndex = _this$_getRangeToRend[0],
          stopIndex = _this$_getRangeToRend[1];

      var items = [];

      if (itemCount > 0) {
        for (var _index = startIndex; _index <= stopIndex; _index++) {
          items.push(createElement(children, {
            data: itemData,
            key: itemKey(_index, itemData),
            index: _index,
            isScrolling: useIsScrolling ? isScrolling : undefined,
            style: this._getItemStyle(_index)
          }));
        }
      } // Read this value AFTER items have been created,
      // So their actual sizes (if variable) are taken into consideration.


      var estimatedTotalSize = getEstimatedTotalSize(this.props, this._instanceProps);
      return createElement(outerElementType || outerTagName || 'div', {
        className: className,
        onScroll: onScroll,
        ref: this._outerRefSetter,
        style: _extends$1({
          position: 'relative',
          height: height,
          width: width,
          overflow: 'auto',
          WebkitOverflowScrolling: 'touch',
          willChange: 'transform',
          direction: direction
        }, style)
      }, createElement(innerElementType || innerTagName || 'div', {
        children: items,
        ref: innerRef,
        style: {
          height: isHorizontal ? '100%' : estimatedTotalSize,
          pointerEvents: isScrolling ? 'none' : undefined,
          width: isHorizontal ? estimatedTotalSize : '100%'
        }
      }));
    };

    _proto._callPropsCallbacks = function _callPropsCallbacks() {
      if (typeof this.props.onItemsRendered === 'function') {
        var itemCount = this.props.itemCount;

        if (itemCount > 0) {
          var _this$_getRangeToRend2 = this._getRangeToRender(),
              _overscanStartIndex = _this$_getRangeToRend2[0],
              _overscanStopIndex = _this$_getRangeToRend2[1],
              _visibleStartIndex = _this$_getRangeToRend2[2],
              _visibleStopIndex = _this$_getRangeToRend2[3];

          this._callOnItemsRendered(_overscanStartIndex, _overscanStopIndex, _visibleStartIndex, _visibleStopIndex);
        }
      }

      if (typeof this.props.onScroll === 'function') {
        var _this$state2 = this.state,
            _scrollDirection = _this$state2.scrollDirection,
            _scrollOffset = _this$state2.scrollOffset,
            _scrollUpdateWasRequested = _this$state2.scrollUpdateWasRequested;

        this._callOnScroll(_scrollDirection, _scrollOffset, _scrollUpdateWasRequested);
      }
    } // Lazily create and cache item styles while scrolling,
    // So that pure component sCU will prevent re-renders.
    // We maintain this cache, and pass a style prop rather than index,
    // So that List can clear cached styles and force item re-render if necessary.
    ;

    _proto._getRangeToRender = function _getRangeToRender() {
      var _this$props5 = this.props,
          itemCount = _this$props5.itemCount,
          overscanCount = _this$props5.overscanCount;
      var _this$state3 = this.state,
          isScrolling = _this$state3.isScrolling,
          scrollDirection = _this$state3.scrollDirection,
          scrollOffset = _this$state3.scrollOffset;

      if (itemCount === 0) {
        return [0, 0, 0, 0];
      }

      var startIndex = getStartIndexForOffset(this.props, scrollOffset, this._instanceProps);
      var stopIndex = getStopIndexForStartIndex(this.props, startIndex, scrollOffset, this._instanceProps); // Overscan by one item in each direction so that tab/focus works.
      // If there isn't at least one extra item, tab loops back around.

      var overscanBackward = !isScrolling || scrollDirection === 'backward' ? Math.max(1, overscanCount) : 1;
      var overscanForward = !isScrolling || scrollDirection === 'forward' ? Math.max(1, overscanCount) : 1;
      return [Math.max(0, startIndex - overscanBackward), Math.max(0, Math.min(itemCount - 1, stopIndex + overscanForward)), startIndex, stopIndex];
    };

    return List;
  }(PureComponent), _class.defaultProps = {
    direction: 'ltr',
    itemData: undefined,
    layout: 'vertical',
    overscanCount: 2,
    useIsScrolling: false
  }, _class;
} // NOTE: I considered further wrapping individual items with a pure ListItem component.
// This would avoid ever calling the render function for the same index more than once,
// But it would also add the overhead of a lot of components/fibers.
// I assume people already do this (render function returning a class component),
// So my doing it would just unnecessarily double the wrappers.

var validateSharedProps$1 = function validateSharedProps(_ref2, _ref3) {
  _ref2.children;
      _ref2.direction;
      _ref2.height;
      _ref2.layout;
      _ref2.innerTagName;
      _ref2.outerTagName;
      _ref2.width;
  _ref3.instance;
};

var FixedSizeList = /*#__PURE__*/createListComponent({
  getItemOffset: function getItemOffset(_ref, index) {
    var itemSize = _ref.itemSize;
    return index * itemSize;
  },
  getItemSize: function getItemSize(_ref2, index) {
    var itemSize = _ref2.itemSize;
    return itemSize;
  },
  getEstimatedTotalSize: function getEstimatedTotalSize(_ref3) {
    var itemCount = _ref3.itemCount,
        itemSize = _ref3.itemSize;
    return itemSize * itemCount;
  },
  getOffsetForIndexAndAlignment: function getOffsetForIndexAndAlignment(_ref4, index, align, scrollOffset) {
    var direction = _ref4.direction,
        height = _ref4.height,
        itemCount = _ref4.itemCount,
        itemSize = _ref4.itemSize,
        layout = _ref4.layout,
        width = _ref4.width;
    // TODO Deprecate direction "horizontal"
    var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
    var size = isHorizontal ? width : height;
    var lastItemOffset = Math.max(0, itemCount * itemSize - size);
    var maxOffset = Math.min(lastItemOffset, index * itemSize);
    var minOffset = Math.max(0, index * itemSize - size + itemSize);

    if (align === 'smart') {
      if (scrollOffset >= minOffset - size && scrollOffset <= maxOffset + size) {
        align = 'auto';
      } else {
        align = 'center';
      }
    }

    switch (align) {
      case 'start':
        return maxOffset;

      case 'end':
        return minOffset;

      case 'center':
        {
          // "Centered" offset is usually the average of the min and max.
          // But near the edges of the list, this doesn't hold true.
          var middleOffset = Math.round(minOffset + (maxOffset - minOffset) / 2);

          if (middleOffset < Math.ceil(size / 2)) {
            return 0; // near the beginning
          } else if (middleOffset > lastItemOffset + Math.floor(size / 2)) {
            return lastItemOffset; // near the end
          } else {
            return middleOffset;
          }
        }

      case 'auto':
      default:
        if (scrollOffset >= minOffset && scrollOffset <= maxOffset) {
          return scrollOffset;
        } else if (scrollOffset < minOffset) {
          return minOffset;
        } else {
          return maxOffset;
        }

    }
  },
  getStartIndexForOffset: function getStartIndexForOffset(_ref5, offset) {
    var itemCount = _ref5.itemCount,
        itemSize = _ref5.itemSize;
    return Math.max(0, Math.min(itemCount - 1, Math.floor(offset / itemSize)));
  },
  getStopIndexForStartIndex: function getStopIndexForStartIndex(_ref6, startIndex, scrollOffset) {
    var direction = _ref6.direction,
        height = _ref6.height,
        itemCount = _ref6.itemCount,
        itemSize = _ref6.itemSize,
        layout = _ref6.layout,
        width = _ref6.width;
    // TODO Deprecate direction "horizontal"
    var isHorizontal = direction === 'horizontal' || layout === 'horizontal';
    var offset = startIndex * itemSize;
    var size = isHorizontal ? width : height;
    var numVisibleItems = Math.ceil((size + scrollOffset - offset) / itemSize);
    return Math.max(0, Math.min(itemCount - 1, startIndex + numVisibleItems - 1 // -1 is because stop index is inclusive
    ));
  },
  initInstanceProps: function initInstanceProps(props) {// Noop
  },
  shouldResetStyleCacheOnItemSizeChange: true,
  validateProps: function validateProps(_ref7) {
    _ref7.itemSize;
  }
});

function isRangeVisible(_ref) {
  var lastRenderedStartIndex = _ref.lastRenderedStartIndex,
      lastRenderedStopIndex = _ref.lastRenderedStopIndex,
      startIndex = _ref.startIndex,
      stopIndex = _ref.stopIndex;

  return !(startIndex > lastRenderedStopIndex || stopIndex < lastRenderedStartIndex);
}

function scanForUnloadedRanges(_ref) {
  var isItemLoaded = _ref.isItemLoaded,
      itemCount = _ref.itemCount,
      minimumBatchSize = _ref.minimumBatchSize,
      startIndex = _ref.startIndex,
      stopIndex = _ref.stopIndex;

  var unloadedRanges = [];

  var rangeStartIndex = null;
  var rangeStopIndex = null;

  for (var _index = startIndex; _index <= stopIndex; _index++) {
    var loaded = isItemLoaded(_index);

    if (!loaded) {
      rangeStopIndex = _index;
      if (rangeStartIndex === null) {
        rangeStartIndex = _index;
      }
    } else if (rangeStopIndex !== null) {
      unloadedRanges.push(rangeStartIndex, rangeStopIndex);

      rangeStartIndex = rangeStopIndex = null;
    }
  }

  // If :rangeStopIndex is not null it means we haven't ran out of unloaded rows.
  // Scan forward to try filling our :minimumBatchSize.
  if (rangeStopIndex !== null) {
    var potentialStopIndex = Math.min(Math.max(rangeStopIndex, rangeStartIndex + minimumBatchSize - 1), itemCount - 1);

    for (var _index2 = rangeStopIndex + 1; _index2 <= potentialStopIndex; _index2++) {
      if (!isItemLoaded(_index2)) {
        rangeStopIndex = _index2;
      } else {
        break;
      }
    }

    unloadedRanges.push(rangeStartIndex, rangeStopIndex);
  }

  // Check to see if our first range ended prematurely.
  // In this case we should scan backwards to try filling our :minimumBatchSize.
  if (unloadedRanges.length) {
    while (unloadedRanges[1] - unloadedRanges[0] + 1 < minimumBatchSize && unloadedRanges[0] > 0) {
      var _index3 = unloadedRanges[0] - 1;

      if (!isItemLoaded(_index3)) {
        unloadedRanges[0] = _index3;
      } else {
        break;
      }
    }
  }

  return unloadedRanges;
}

var classCallCheck$1 = function (instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
};

var createClass$1 = function () {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  return function (Constructor, protoProps, staticProps) {
    if (protoProps) defineProperties(Constructor.prototype, protoProps);
    if (staticProps) defineProperties(Constructor, staticProps);
    return Constructor;
  };
}();

var inherits$1 = function (subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  }

  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};

var possibleConstructorReturn$1 = function (self, call) {
  if (!self) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return call && (typeof call === "object" || typeof call === "function") ? call : self;
};

var InfiniteLoader = function (_PureComponent) {
  inherits$1(InfiniteLoader, _PureComponent);

  function InfiniteLoader() {
    var _ref;

    var _temp, _this, _ret;

    classCallCheck$1(this, InfiniteLoader);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = possibleConstructorReturn$1(this, (_ref = InfiniteLoader.__proto__ || Object.getPrototypeOf(InfiniteLoader)).call.apply(_ref, [this].concat(args))), _this), _this._lastRenderedStartIndex = -1, _this._lastRenderedStopIndex = -1, _this._memoizedUnloadedRanges = [], _this._onItemsRendered = function (_ref2) {
      var visibleStartIndex = _ref2.visibleStartIndex,
          visibleStopIndex = _ref2.visibleStopIndex;

      _this._lastRenderedStartIndex = visibleStartIndex;
      _this._lastRenderedStopIndex = visibleStopIndex;

      _this._ensureRowsLoaded(visibleStartIndex, visibleStopIndex);
    }, _this._setRef = function (listRef) {
      _this._listRef = listRef;
    }, _temp), possibleConstructorReturn$1(_this, _ret);
  }

  createClass$1(InfiniteLoader, [{
    key: 'resetloadMoreItemsCache',
    value: function resetloadMoreItemsCache() {
      var autoReload = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      this._memoizedUnloadedRanges = [];

      if (autoReload) {
        this._ensureRowsLoaded(this._lastRenderedStartIndex, this._lastRenderedStopIndex);
      }
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
    }
  }, {
    key: 'render',
    value: function render() {
      var children = this.props.children;


      return children({
        onItemsRendered: this._onItemsRendered,
        ref: this._setRef
      });
    }
  }, {
    key: '_ensureRowsLoaded',
    value: function _ensureRowsLoaded(startIndex, stopIndex) {
      var _props = this.props,
          isItemLoaded = _props.isItemLoaded,
          itemCount = _props.itemCount,
          _props$minimumBatchSi = _props.minimumBatchSize,
          minimumBatchSize = _props$minimumBatchSi === undefined ? 10 : _props$minimumBatchSi,
          _props$threshold = _props.threshold,
          threshold = _props$threshold === undefined ? 15 : _props$threshold;


      var unloadedRanges = scanForUnloadedRanges({
        isItemLoaded: isItemLoaded,
        itemCount: itemCount,
        minimumBatchSize: minimumBatchSize,
        startIndex: Math.max(0, startIndex - threshold),
        stopIndex: Math.min(itemCount - 1, stopIndex + threshold)
      });

      // Avoid calling load-rows unless range has changed.
      // This shouldn't be strictly necessary, but is maybe nice to do.
      if (this._memoizedUnloadedRanges.length !== unloadedRanges.length || this._memoizedUnloadedRanges.some(function (startOrStop, index) {
        return unloadedRanges[index] !== startOrStop;
      })) {
        this._memoizedUnloadedRanges = unloadedRanges;
        this._loadUnloadedRanges(unloadedRanges);
      }
    }
  }, {
    key: '_loadUnloadedRanges',
    value: function _loadUnloadedRanges(unloadedRanges) {
      var _this2 = this;

      // loadMoreRows was renamed to loadMoreItems in v1.0.3; will be removed in v2.0
      var loadMoreItems = this.props.loadMoreItems || this.props.loadMoreRows;

      var _loop = function _loop(i) {
        var startIndex = unloadedRanges[i];
        var stopIndex = unloadedRanges[i + 1];
        var promise = loadMoreItems(startIndex, stopIndex);
        if (promise != null) {
          promise.then(function () {
            // Refresh the visible rows if any of them have just been loaded.
            // Otherwise they will remain in their unloaded visual state.
            if (isRangeVisible({
              lastRenderedStartIndex: _this2._lastRenderedStartIndex,
              lastRenderedStopIndex: _this2._lastRenderedStopIndex,
              startIndex: startIndex,
              stopIndex: stopIndex
            })) {
              // Handle an unmount while promises are still in flight.
              if (_this2._listRef == null) {
                return;
              }

              // Resize cached row sizes for VariableSizeList,
              // otherwise just re-render the list.
              if (typeof _this2._listRef.resetAfterIndex === 'function') {
                _this2._listRef.resetAfterIndex(startIndex, true);
              } else {
                // HACK reset temporarily cached item styles to force PureComponent to re-render.
                // This is pretty gross, but I'm okay with it for now.
                // Don't judge me.
                if (typeof _this2._listRef._getItemStyleCache === 'function') {
                  _this2._listRef._getItemStyleCache(-1);
                }
                _this2._listRef.forceUpdate();
              }
            }
          });
        }
      };

      for (var i = 0; i < unloadedRanges.length; i += 2) {
        _loop(i);
      }
    }
  }]);
  return InfiniteLoader;
}(PureComponent);

const SELECTED_STATES = ['S', 'XS'];

const flatten = arr => arr.reduce((prev, cur) => prev.concat(cur));

function isStateSelected(qState) {
  return SELECTED_STATES.includes(qState);
}

function getUniques(arr) {
  return Array.isArray(arr) ? Array.from(new Set(arr)) : undefined;
}
function getSelectedValues(pages) {
  if (!pages || !pages.length) {
    return [];
  }

  const elementNbrs = pages.map(page => {
    const elementNumbers = page.qMatrix.map(p => {
      const [p0] = p;
      return isStateSelected(p0.qState) ? p0.qElemNumber : false;
    });
    return elementNumbers.filter(n => n !== false);
  });
  return flatten(elementNbrs);
}
function applySelectionsOnPages(pages, elmNumbers) {
  let clearAllButElmNumbers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

  const getNewSelectionState = qState => elmNumbers.length <= 1 && isStateSelected(qState) ? 'A' : 'S';

  const matrices = pages.map(page => {
    const qMatrix = page.qMatrix.map(p => {
      const [p0] = p;
      const selectionMatchesElement = elmNumbers.includes(p0.qElemNumber);
      let qState;

      if (clearAllButElmNumbers) {
        qState = selectionMatchesElement ? 'S' : 'A';
      } else {
        qState = selectionMatchesElement ? getNewSelectionState(p0.qState) : p0.qState;
      }

      return [_objectSpread2(_objectSpread2({}, p0), {}, {
        qState
      }), p.slice(1)];
    });
    return _objectSpread2(_objectSpread2({}, page), {}, {
      qMatrix
    });
  });
  return matrices;
}
async function selectValues(_ref) {
  let {
    selections,
    elemNumbers,
    isSingleSelect = false
  } = _ref;
  let resolved = Promise.resolve(false);
  const hasNanValues = elemNumbers.some(elemNumber => Number.isNaN(elemNumber));

  if (!hasNanValues) {
    const elemNumbersToSelect = elemNumbers;
    resolved = selections.select({
      method: 'selectListObjectValues',
      params: ['/qListObjectDef', elemNumbersToSelect, !isSingleSelect]
    }).then(success => success !== false).catch(() => false);
  }

  return resolved;
}
function getElemNumbersFromPages(pages) {
  if (!pages || !pages.length) {
    return [];
  }

  const elemNumbersArr = pages.map(page => {
    const qElemNumbers = page.qMatrix.map(p => {
      const [{
        qElemNumber
      }] = p;
      return qElemNumber;
    });
    return qElemNumbers;
  });
  const elemNumbers = flatten(elemNumbersArr);
  return elemNumbers;
}
/**
 * @ignore
 * @interface MinMaxResult
 * @property {number} min
 * @property {number} max
 */

/**
 * Returns the min and max indices of elemNumbersOrdered which contains
 * all numbers in elementNbrs.
 *
 * @ignore
 * @param {number[]} elementNbrs
 * @param {number[]} elemNumbersOrdered
 * @returns {MinMaxResult}
 */

function getMinMax(elementNbrs, elemNumbersOrdered) {
  let min = Infinity;
  let max = -Infinity;
  elementNbrs.forEach(nbr => {
    const index = elemNumbersOrdered.indexOf(nbr);
    min = index < min ? index : min;
    max = index > max ? index : max;
  });
  return {
    min,
    max
  };
}

function fillRange(elementNbrs, elemNumbersOrdered) {
  if (!elementNbrs) {
    return [];
  }

  if (elementNbrs.length <= 1) {
    return elementNbrs;
  } // Interpolate values algorithm


  const {
    min,
    max
  } = getMinMax(elementNbrs, elemNumbersOrdered);
  return elemNumbersOrdered.slice(min, max + 1);
}

function useSelectionsInteractions(_ref) {
  let {
    layout,
    selections,
    pages = [],
    checkboxes = false,
    selectDisabled,
    doc = document,
    isSingleSelect: singleSelect = false
  } = _ref;
  const [instantPages, setInstantPages] = useState$1(pages);
  const [mouseDown, setMouseDown] = useState$1(false);
  const [selectingValues, setSelectingValues] = useState$1(false);
  const [isSingleSelect, setIsSingleSelect] = useState$1(singleSelect);
  const [selected, setSelected] = useState$1([]);
  const [isRangeSelection, setIsRangeSelection] = useState$1(false);
  const [preSelected, setPreSelected] = useState$1([]);
  const elemNumbersOrdered = getElemNumbersFromPages(pages);
  useEffect$1(() => {
    setIsSingleSelect(singleSelect);
  }, [singleSelect]); // Select values for real, by calling the backend.

  const select = async function () {
    let elemNumbers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    let additive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

    if (selectDisabled()) {
      return;
    }

    setSelectingValues(true);
    const filtered = additive ? elemNumbers.filter(n => !selected.includes(n)) : elemNumbers;
    await selectValues({
      selections,
      elemNumbers: filtered,
      isSingleSelect
    });
    setSelectingValues(false);
    setPreSelected([]);
  }; // Show estimated selection states instantly before applying the selections for real.


  const preSelect = function (elemNumbers) {
    let additive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

    if (selectDisabled()) {
      return;
    }

    setPreSelected(existing => {
      const uniques = getUniques([...existing, ...elemNumbers]);
      const filtered = additive ? uniques.filter(n => !selected.includes(n)) : uniques;
      const filled = additive ? fillRange(uniques, elemNumbersOrdered) : filtered;
      return filled;
    });
  };

  const selectManually = function () {
    let elementIds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    let additive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    setIsRangeSelection(false); // range is not supported for manual select

    setMouseDown(true);
    preSelect(elementIds, additive || isRangeSelection);
    const p = select(elementIds, additive || isRangeSelection);
    setMouseDown(false);
    return p;
  };

  const handleSingleSelectKey = event => {
    if (event.ctrlKey || event.metaKey) {
      setIsSingleSelect(true);
      event.currentTarget.focus(); // will not be focused otherwise

      event.preventDefault();
    }
  };

  const onClick = useCallback(event => {
    if (selectingValues || selectDisabled()) {
      return;
    }

    const elemNumber = +event.currentTarget.getAttribute('data-n');
    setPreSelected([elemNumber]);
    handleSingleSelectKey(event);
  }, [selectingValues, selectDisabled]);
  const onMouseDown = useCallback(event => {
    if (selectingValues || selectDisabled()) {
      return;
    }

    setIsRangeSelection(false);
    setMouseDown(true);
    const elemNumber = +event.currentTarget.getAttribute('data-n');
    setPreSelected([elemNumber]);
    handleSingleSelectKey(event);
  }, [selectingValues, selectDisabled]);
  const onMouseUp = useCallback(event => {
    const elemNumber = +event.currentTarget.getAttribute('data-n');

    if (isSingleSelect || !mouseDown || selectingValues || preSelected.length === 1 && preSelected[0] === elemNumber // prevent toggling again on mouseup
    ) {
      return;
    }

    preSelect([elemNumber]);
  }, [mouseDown, selectingValues, preSelected, selected, isRangeSelection, selectDisabled]);
  const onMouseUpDoc = useCallback(() => {
    // Ensure we end interactions when mouseup happens outside the Listbox.
    setMouseDown(false);
    setSelectingValues(false);
    setIsRangeSelection(false);
    setIsSingleSelect(singleSelect);
  }, [singleSelect]);
  const onMouseEnter = useCallback(event => {
    if (isSingleSelect || !mouseDown || selectingValues || selectDisabled()) {
      return;
    }

    setIsRangeSelection(true);
    const elemNumber = +event.currentTarget.getAttribute('data-n');
    preSelect([elemNumber], true);
  }, [mouseDown, selectingValues, isRangeSelection, preSelected, selected, selectDisabled, layout && layout.qListObject.qDimensionInfo.qIsOneAndOnlyOne]);
  useEffect$1(() => {
    // Perform selections of pre-selected values. This can
    // happen only when interactions have finished (mouseup).
    const interactionIsFinished = !mouseDown;

    if (!preSelected || !preSelected.length || selectingValues || !interactionIsFinished || !layout) {
      return;
    }

    select(preSelected, isRangeSelection);
  }, [preSelected, mouseDown, selectDisabled()]);
  useEffect$1(() => {
    doc.addEventListener('mouseup', onMouseUpDoc);
    return () => {
      doc.removeEventListener('mouseup', onMouseUpDoc);
    };
  }, [onMouseUpDoc]);
  useEffect$1(() => {
    if (selectingValues || mouseDown) {
      return;
    } // Keep track of (truely) selected fields so we can prevent toggling them on range select.


    const alreadySelected = getSelectedValues(pages);
    setSelected(alreadySelected);
  }, [pages]);
  useEffect$1(() => {
    if (selectingValues || !pages || !checkboxes && !mouseDown) {
      return;
    } // Render pre-selections before they have been selected in Engine.


    const newPages = applySelectionsOnPages(pages, preSelected, isSingleSelect);
    setInstantPages(newPages);
  }, [preSelected]);
  const interactionEvents = {};

  if (checkboxes) {
    Object.assign(interactionEvents, {
      onClick
    });
  } else {
    Object.assign(interactionEvents, {
      onMouseUp,
      onMouseDown,
      onMouseEnter
    });
  }

  return {
    instantPages,
    interactionEvents,
    select: selectManually // preselect and select without having to trigger an event

  };
}

const tick = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M6,10 L13,3 L15,5 L8,12 L6,14 L1,9 L3,7 L6,10 Z'
    }
  }]
});

var Tick = (props => SvgIcon(tick(props)));

const CheckboxChecked = "url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath" + " fill-rule='evenodd' clip-rule='evenodd' d='M12 5c-.28 0-.53.11-.71.29L7 9.59l-2.29-2.3a1.003 " + "1.003 0 00-1.42 1.42l3 3c.18.18.43.29.71.29s.53-.11.71-.29l5-5A1.003 1.003 0 0012 5z' fill='%23fff'/%3E%3C/svg%3E\")";

const borderRadius = 3;
const useStyles$e = makeStyles(theme => ({
  cbIcon: {
    borderRadius,
    width: 16,
    height: 16,
    boxShadow: 'inset 0 0 0 1px rgba(16,22,26,.2), inset 0 -1px 0 rgba(16,22,26,.1)',
    backgroundColor: '#f5f8fa',
    backgroundImage: 'linear-gradient(180deg,hsla(0,0%,100%,.8),hsla(0,0%,100%,0))',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center'
  },
  cbIconChecked: {
    borderRadius,
    backgroundColor: theme.palette.selected.main,
    backgroundImage: 'linear-gradient(180deg,hsla(0,0%,100%,.1),hsla(0,0%,100%,0))',
    '&:before': {
      display: 'block',
      width: 16,
      height: 16,
      backgroundImage: CheckboxChecked,
      content: '""'
    }
  },
  cbIconExcluded: {
    borderRadius: borderRadius - 1,
    width: 12,
    height: 12,
    backgroundColor: theme.palette.selected.excluded
  },
  cbIconAlternative: {
    borderRadius: borderRadius - 1,
    width: 12,
    height: 12,
    backgroundColor: theme.palette.selected.alternative
  },
  checkbox: {
    margin: 0,
    '&:hover': {
      backgroundColor: 'inherit !important'
    }
  },
  dense: {
    padding: '4px 8px'
  }
}));

const getIcon = function (styles) {
  let showGray = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  let excluded = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  let alternative = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  return /*#__PURE__*/React.createElement("span", {
    className: styles.cbIcon
  }, (excluded || alternative) && /*#__PURE__*/React.createElement("span", {
    className: [showGray && excluded && styles.cbIconExcluded, showGray && alternative && styles.cbIconAlternative].filter(Boolean).join(' ')
  }));
};

function ListboxCheckbox(_ref) {
  let {
    checked,
    label,
    dense,
    excluded,
    alternative,
    showGray = true
  } = _ref;
  const styles = useStyles$e();
  return /*#__PURE__*/React.createElement(Checkbox, {
    edge: "start",
    checked: checked,
    disableRipple: true,
    className: [styles.checkbox, dense && styles.dense].filter(Boolean).join(' '),
    inputProps: {
      'aria-labelledby': label
    },
    name: label,
    icon: getIcon(styles, showGray, excluded, alternative),
    checkedIcon: /*#__PURE__*/React.createElement("span", {
      className: styles.cbIconChecked
    })
  });
}

/**
 * @ignore
 * @interface Range
 * @property {number} qCharPos The (absolute) index where the highlighted range starts.
 * @property {number} qCharCount The length of the sub-string (starting from qChartPos) that should be highlighted.
 */

/**
 * @ignore
 * @interface Segment
 * @property {string} segment The sub-string/segment cut out from the original label.
 * @property {boolean} highlighted A flag which tells whether the segment should be highlighted or not.
 */

/**
 * @ignore
 * @param {string} label The label we want to create segments out of.
 * @param {Range} range The indexes which define how to create the segments.
 * @param {number=} [startIndex] An optional index which tells where we want to start the first segment from
 *   (only relevant for creating the first unhighlighted segment of a string/sub-string).
 * @returns {Segment[]} An array of segments.
 */
function getSegmentsFromRange(label, range) {
  let startIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  const {
    qCharPos,
    qCharCount
  } = range;
  const segments = [];

  if (qCharPos > startIndex) {
    // Create a non-highlighted section before the highighted section.
    segments.push([label.slice(startIndex, qCharPos), false]);
  } // Highlighted segment.


  segments.push([label.slice(qCharPos, qCharPos + qCharCount), true]);
  return segments;
}
/**
 * @ignore
 * @param {string} label The label we want to create segments out of.
 * @param {Range[]} ranges The ranges defining indices for cutting the string into segments.
 * @returns {Segment[]} An array of segments, covering the entire string label.
 */


function getSegmentsFromRanges(label, ranges) {
  if (!ranges.length) {
    return [];
  }

  const labels = ranges.reduce((acc, curr, ix) => {
    const startIndex = ix === 0 ? 0 : ranges[ix - 1].qCharPos + ranges[ix - 1].qCharCount;
    acc.push(...getSegmentsFromRange(label, curr, startIndex)); // Last non highlighted segment

    const isLastRange = ix === ranges.length - 1;
    const endIndex = ranges[ix].qCharPos + ranges[ix].qCharCount;

    if (isLastRange && endIndex < label.length) {
      acc.push([label.slice(endIndex), false]);
    }

    return acc;
  }, []);
  return labels;
}

const useStyles$d = makeStyles(() => ({
  denseRadioButton: {
    height: '100%',
    boxSizing: 'border-box',
    '& svg': {
      width: '0.7em',
      height: '0.7em'
    }
  },
  radioButton: {
    right: '5px'
  }
}));
function ListBoxRadioButton(_ref) {
  let {
    checked,
    label,
    dense
  } = _ref;
  const styles = useStyles$d();
  return /*#__PURE__*/React.createElement(Radio, {
    checked: checked,
    value: label,
    name: label,
    inputProps: {
      'aria-labelledby': label
    },
    className: dense ? styles.denseRadioButton : styles.radioButton,
    style: {
      backgroundColor: 'transparent'
    },
    disableRipple: true
  });
}

const KEYS = Object.freeze({
  ENTER: 13,
  ESCAPE: 27,
  SPACE: 32,
  TAB: 9,
  BACKSPACE: 8,
  DELETE: 46,
  ALT: 18,
  CTRL: 17,
  SHIFT: 16,
  ARROW_UP: 38,
  ARROW_DOWN: 40,
  ARROW_LEFT: 37,
  ARROW_RIGHT: 39,
  PAGE_DOWN: 34,
  PAGE_UP: 33,
  HOME: 36,
  END: 35,
  F10: 121,
  A: 65,
  F: 70,
  ZERO: 48,
  NINE: 57,
  NUMPAD_ZERO: 96,
  NUMPAD_NINE: 105,
  SUBTRACTION: 189,
  DECIMAL: 190,
  NUMPAD_DECIMAL: 110,
  isArrow: key => key === KEYS.ARROW_UP || key === KEYS.ARROW_DOWN || key === KEYS.ARROW_LEFT || key === KEYS.ARROW_RIGHT
});

function getFieldKeyboardNavigation(_ref) {
  let {
    select,
    confirm,
    cancel
  } = _ref;

  const getElement = function (elm) {
    let next = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    const parentElm = elm && elm.parentElement[next ? 'nextElementSibling' : 'previousElementSibling'];
    return parentElm && parentElm.querySelector('[role]');
  };

  let startedRange = false;

  const setStartedRange = val => {
    startedRange = val;
  };

  const handleKeyDown = event => {
    let elementToFocus;
    const {
      keyCode,
      shiftKey = false
    } = event.nativeEvent;

    switch (keyCode) {
      case KEYS.SHIFT:
        // This is to ensure we include the first value when starting a range selection.
        setStartedRange(true);
        break;

      case KEYS.SPACE:
        select([+event.currentTarget.getAttribute('data-n')]);
        break;

      case KEYS.ARROW_DOWN:
      case KEYS.ARROW_RIGHT:
        elementToFocus = getElement(event.currentTarget, true);

        if (shiftKey && elementToFocus) {
          if (startedRange) {
            select([+event.currentTarget.getAttribute('data-n')], true);
            setStartedRange(false);
          }

          select([+elementToFocus.getAttribute('data-n')], true);
        }

        break;

      case KEYS.ARROW_UP:
      case KEYS.ARROW_LEFT:
        elementToFocus = getElement(event.currentTarget, false);

        if (shiftKey && elementToFocus) {
          if (startedRange) {
            select([+event.currentTarget.getAttribute('data-n')], true);
            setStartedRange(false);
          }

          select([+elementToFocus.getAttribute('data-n')], true);
        }

        break;

      case KEYS.ENTER:
        confirm();
        break;

      case KEYS.ESCAPE:
        cancel();
        return;
      // let it propagate to top-level

      default:
        return;
      // don't stop propagation since we want to outsource keydown to other handlers.
    }

    if (elementToFocus) {
      elementToFocus.focus();
    }

    event.preventDefault();
    event.stopPropagation();
  };

  return handleKeyDown;
}
function getListboxInlineKeyboardNavigation(_ref2) {
  let {
    setKeyboardActive
  } = _ref2;

  const focusInsideListbox = element => {
    const fieldElement = element.querySelector('.search input, .value.selector, .value');
    setKeyboardActive(true);

    if (fieldElement) {
      fieldElement.focus();
    }
  };

  const focusContainer = element => {
    setKeyboardActive(false);
    element.focus();
  };

  const handleKeyDown = event => {
    const {
      keyCode
    } = event.nativeEvent;

    switch (keyCode) {
      // case KEYS.TAB: TODO: Focus confirm button using keyboard.focusSelection when we can access the useKeyboard hook.
      case KEYS.ENTER:
      case KEYS.SPACE:
        focusInsideListbox(event.currentTarget);
        break;

      case KEYS.ESCAPE:
        focusContainer(event.currentTarget);
        break;

      default:
        return;
    } // Note: We should not stop propagation here as it will block the containing app
    // from handling keydown events.


    event.preventDefault();
  };

  return handleKeyDown;
}

const ellipsis = {
  width: '100%',
  overflow: 'hidden',
  textOverflow: 'ellipsis'
};
const barPadPx = 4;
const barBorderWidthPx = 1;
const barWithCheckboxLeftPadPx = 29;
const frequencyTextNone = '0';

const getSelectedStyle = _ref => {
  let {
    theme
  } = _ref;
  return {
    background: theme.palette.selected.main,
    color: theme.palette.selected.mainContrastText,
    '&:focus': {
      boxShadow: "inset 0 0 0 2px rgba(0, 0, 0, 0.3)",
      outline: 'none'
    },
    '& $cell': {
      paddingRight: 0
    }
  };
};

const useStyles$c = makeStyles(theme => ({
  row: {
    flexWrap: 'nowrap',
    color: theme.palette.text.primary
  },
  rowBorderBottom: {
    borderBottom: "1px solid ".concat(theme.palette.divider)
  },
  column: {
    flexWrap: 'nowrap',
    borderRight: "1px solid ".concat(theme.palette.divider),
    color: theme.palette.text.primary
  },
  fieldRoot: {
    '&:focus': {
      boxShadow: "inset 0 0 0 2px ".concat(theme.palette.custom.focusBorder, " !important")
    },
    '&:focus-visible': {
      outline: 'none'
    }
  },
  // The interior wrapper for all field content.
  cell: {
    display: 'flex',
    alignItems: 'center',
    minWidth: 0,
    flexGrow: 1,
    // Note that this padding is overridden when using checkboxes.
    paddingLeft: '9px',
    paddingRight: '9px'
  },
  // The leaf node, containing the label text.
  labelText: _objectSpread2({
    flexBasis: 'max-content',
    lineHeight: '16px',
    userSelect: 'none',
    whiteSpace: 'pre'
  }, ellipsis),
  labelDense: {
    fontSize: 12
  },
  // Highlight is added to labelText spans, which are created as siblings to original labelText,
  // when a search string is matched.
  highlighted: {
    overflow: 'visible',
    width: '100%',
    '& > span': {
      width: '100%',
      backgroundColor: '#FFC72A'
    }
  },
  // Checkbox and label container.
  checkboxLabel: {
    margin: 0,
    width: '100%',
    height: '100%',
    // The checkbox's span
    '& > span:nth-child(1)': {
      paddingRight: '8px'
    },
    // The checkbox's label container.
    '& > span:nth-child(2)': _objectSpread2(_objectSpread2({}, ellipsis), {}, {
      display: 'flex',
      alignItems: 'center',
      paddingLeft: 0
    })
  },
  // The icons container holding tick and lock, shown inside fields.
  icon: {
    display: 'flex',
    padding: theme.spacing(1, 1, 1, 0)
  },
  // Selection styles (S=Selected, XS=ExcludedSelected, A=Available, X=Excluded).
  S: _objectSpread2({}, getSelectedStyle({
    theme
  })),
  XS: _objectSpread2(_objectSpread2({}, getSelectedStyle({
    theme
  })), {}, {
    background: theme.palette.selected.excluded,
    color: theme.palette.selected.mainContrastText
  }),
  A: {
    background: theme.palette.selected.alternative,
    color: theme.palette.selected.alternativeContrastText
  },
  X: {
    background: theme.palette.selected.excluded,
    color: theme.palette.selected.mainContrastText
  },
  frequencyCount: {
    paddingLeft: '8px',
    paddingRight: '8px'
  },
  barContainer: {
    position: 'relative'
  },
  bar: {
    border: "".concat(barBorderWidthPx, "px solid"),
    borderColor: '#D9D9D9',
    height: '16px',
    position: 'absolute',
    zIndex: '-1',
    alignSelf: 'center',
    left: "".concat(barPadPx, "px"),
    transition: 'width 0.2s',
    backgroundColor: '#FAFAFA'
  },
  barSelected: {
    opacity: '30%',
    zIndex: '0',
    background: theme.palette.background.lighter
  },
  barWithCheckbox: {
    left: "".concat(barWithCheckboxLeftPadPx, "px")
  },
  barSelectedWithCheckbox: {
    background: '#BFE5D0',
    borderColor: '#BFE5D0'
  },
  excludedTextWithCheckbox: {
    color: '#828282'
  }
}));

function RowColumn(_ref2) {
  let {
    index,
    style,
    data,
    column = false
  } = _ref2;
  const {
    onClick,
    onMouseDown,
    onMouseUp,
    onMouseEnter,
    pages,
    isLocked,
    checkboxes = false,
    dense = false,
    frequencyMode = 'N',
    isSingleSelect,
    actions,
    frequencyMax = '',
    histogram = false,
    keyboard,
    showGray = true
  } = data;
  const handleKeyDownCallback = useCallback(getFieldKeyboardNavigation(actions), [actions]);
  const [isSelected, setSelected] = useState$1(false);
  const [cell, setCell] = useState$1();
  const classes = useStyles$c();
  const [classArr, setClassArr] = useState$1([]);
  useEffect$1(() => {
    if (!pages) {
      return;
    }

    let c;
    const page = pages.filter(p => p.qArea.qTop <= index && index < p.qArea.qTop + p.qArea.qHeight)[0];

    if (page) {
      const area = page.qArea;

      if (index >= area.qTop && index < area.qTop + area.qHeight) {
        [c] = page.qMatrix[index - area.qTop];
      }
    }

    setCell(c);
  }, [pages]);

  const isExcluded = c => c ? c.qState === 'X' || c.qState === 'XS' || c.qState === 'XL' : null;

  const isAlternative = c => c ? c.qState === 'A' : null;

  useEffect$1(() => {
    if (!cell) {
      return;
    }

    const selected = cell.qState === 'S' || cell.qState === 'XS' || cell.qState === 'L';
    setSelected(selected);
    const clazzArr = [column ? classes.column : classes.row];
    if (!(histogram && dense)) clazzArr.push(classes.rowBorderBottom);

    if (!checkboxes) {
      if (cell.qState === 'XS') {
        clazzArr.push(showGray ? classes.XS : classes.S);
      } else if (cell.qState === 'S' || cell.qState === 'L') {
        clazzArr.push(classes.S);
      } else if (showGray && isAlternative(cell)) {
        clazzArr.push(classes.A);
      } else if (showGray && isExcluded(cell)) {
        clazzArr.push(classes.X);
      }
    }

    setClassArr(clazzArr);
  }, [cell && cell.qState]);

  const joinClassNames = namesArray => namesArray.filter(c => !!c).join(' ').trim();

  const excludedOrAlternative = () => (isAlternative(cell) || isExcluded(cell)) && checkboxes;

  const getValueField = _ref3 => {
    let {
      lbl,
      ix,
      color,
      highlighted = false
    } = _ref3;
    return /*#__PURE__*/React.createElement(Typography, {
      component: "span",
      variant: "body2",
      key: ix,
      className: joinClassNames([classes.labelText, highlighted && classes.highlighted, dense && classes.labelDense, showGray && excludedOrAlternative() && classes.excludedTextWithCheckbox]),
      color: color
    }, /*#__PURE__*/React.createElement("span", {
      style: {
        whiteSpace: 'pre'
      }
    }, lbl));
  };

  const preventContextMenu = event => {
    if (checkboxes) {
      // Event will not propagate in the checkbox/radiobutton case
      onClick(event);
    }

    event.preventDefault();
  };

  const getCheckboxField = _ref4 => {
    let {
      lbl,
      color,
      qElemNumber
    } = _ref4;
    const cb = /*#__PURE__*/React.createElement(ListboxCheckbox, {
      label: lbl,
      checked: isSelected,
      dense: dense,
      excluded: isExcluded(cell),
      alternative: isAlternative(cell),
      showGray: showGray
    });
    const rb = /*#__PURE__*/React.createElement(ListBoxRadioButton, {
      label: lbl,
      checked: isSelected,
      dense: dense
    });
    const labelTag = typeof lbl === 'string' ? getValueField({
      lbl,
      color,
      highlighted: false
    }) : lbl;
    return /*#__PURE__*/React.createElement(FormControlLabel, {
      color: color,
      control: isSingleSelect ? rb : cb,
      className: classes.checkboxLabel,
      label: labelTag,
      key: qElemNumber
    });
  };

  const label = cell ? cell.qText : '';

  const getFrequencyText = () => {
    if (cell) {
      return cell.qFrequency ? cell.qFrequency : frequencyTextNone;
    }

    return '';
  }; // Search highlights. Split up labelText span into several and add the highlighted class to matching sub-strings.


  const ranges = cell && cell.qHighlightRanges && cell.qHighlightRanges.qRanges.sort((a, b) => a.qCharPos - b.qCharPos) || [];
  const labels = getSegmentsFromRanges(label, ranges);
  const getField = checkboxes ? getCheckboxField : getValueField;

  const getFieldWithRanges = _ref5 => {
    let {
      lbls
    } = _ref5;
    const labelsWithRanges = lbls.map((_ref6, ix) => {
      let [lbl, highlighted] = _ref6;
      return getValueField({
        ix,
        highlighted,
        lbl
      });
    });
    return checkboxes ? getCheckboxField({
      lbl: labelsWithRanges
    }) : labelsWithRanges;
  };

  const iconStyles = {
    alignItems: 'center',
    display: 'flex'
  };
  const showLock = isSelected && isLocked;
  const showTick = !checkboxes && isSelected && !isLocked;
  const cellStyle = {
    display: 'flex',
    alignItems: 'center',
    minWidth: 0,
    flexGrow: 1,
    padding: checkboxes ? 0 : undefined
  };

  const hasHistogramBar = () => cell && histogram && getFrequencyText() !== frequencyTextNone;

  const getBarWidth = qFrequency => {
    const freqStr = String(qFrequency);
    const isPercent = freqStr.substring(freqStr.length - 1) === '%';
    const freq = parseFloat(isPercent ? freqStr : qFrequency);
    const rightSlice = checkboxes ? "(".concat(barWithCheckboxLeftPadPx, "px + ").concat(barPadPx + barBorderWidthPx * 2, "px)") : "".concat(barPadPx * 2 + barBorderWidthPx * 2, "px");
    const width = isPercent ? freq : freq / frequencyMax * 100;
    return "calc(".concat(width, "% - ").concat(rightSlice, ")");
  };

  const isFirstElement = index === 0;
  return /*#__PURE__*/React.createElement("div", {
    className: classes.barContainer
  }, /*#__PURE__*/React.createElement(Grid, {
    container: true,
    spacing: 0,
    className: joinClassNames(['value', ...classArr]),
    classes: {
      root: classes.fieldRoot
    },
    style: style,
    onClick: onClick,
    onMouseDown: onMouseDown,
    onMouseUp: onMouseUp,
    onMouseEnter: onMouseEnter,
    onKeyDown: handleKeyDownCallback,
    onContextMenu: preventContextMenu,
    role: column ? 'column' : 'row',
    tabIndex: isFirstElement && (!keyboard.enabled || keyboard.active) ? 0 : -1,
    "data-n": cell && cell.qElemNumber
  }, hasHistogramBar() && /*#__PURE__*/React.createElement("div", {
    className: joinClassNames([classes.bar, checkboxes && classes.barWithCheckbox, isSelected && (checkboxes ? classes.barSelectedWithCheckbox : classes.barSelected)]),
    style: {
      width: getBarWidth(cell.qFrequency)
    }
  }), /*#__PURE__*/React.createElement(Grid, {
    item: true,
    style: cellStyle,
    className: joinClassNames([classes.cell, classes.selectedCell]),
    title: "".concat(label)
  }, ranges.length === 0 ? getField({
    lbl: label,
    color: 'inherit'
  }) : getFieldWithRanges({
    lbls: labels
  })), frequencyMode !== 'N' && /*#__PURE__*/React.createElement(Grid, {
    item: true,
    style: {
      display: 'flex',
      alignItems: 'center'
    },
    className: classes.frequencyCount
  }, /*#__PURE__*/React.createElement(Typography, {
    noWrap: true,
    color: "inherit",
    variant: "body2",
    className: joinClassNames([dense && classes.labelDense, classes.labelText, showGray && excludedOrAlternative() && classes.excludedTextWithCheckbox])
  }, getFrequencyText())), (showLock || showTick) && /*#__PURE__*/React.createElement(Grid, {
    item: true,
    className: classes.icon
  }, showLock && /*#__PURE__*/React.createElement(Lock, {
    style: iconStyles,
    size: "small"
  }), showTick && /*#__PURE__*/React.createElement(Tick, {
    style: iconStyles,
    size: "small"
  }))));
}

const scrollBarThumb = '#BBB';
const scrollBarThumbHover = '#555';
const scrollBarBackground = '#f1f1f1';
const useStyles$b = makeStyles(() => ({
  styledScrollbars: {
    scrollbarColor: "".concat(scrollBarThumb, " ").concat(scrollBarBackground),
    '&::-webkit-scrollbar': {
      width: 10,
      height: 10
    },
    '&::-webkit-scrollbar-track': {
      backgroundColor: scrollBarBackground
    },
    '&::-webkit-scrollbar-thumb': {
      backgroundColor: scrollBarThumb,
      borderRadius: '1rem'
    },
    '&::-webkit-scrollbar-thumb:hover': {
      backgroundColor: scrollBarThumbHover
    }
  }
}));

function getSizeInfo(_ref) {
  let {
    isVertical,
    checkboxes,
    dense,
    height
  } = _ref;
  let sizeVertical = checkboxes ? 40 : 33;

  if (dense) {
    sizeVertical = 20;
  }

  const itemSize = isVertical ? sizeVertical : 200;
  const listHeight = height || 8 * itemSize;
  return {
    itemSize,
    listHeight
  };
}

function ListBox(_ref2) {
  let {
    model,
    selections,
    direction,
    height,
    width,
    listLayout = 'vertical',
    frequencyMode = 'N',
    histogram = false,
    checkboxes = false,
    update = undefined,
    fetchStart = undefined,
    dense = false,
    keyboard = {},
    showGray = true,
    scrollState,
    sortByState,
    selectDisabled = () => false,
    setCount
  } = _ref2;
  const [layout] = useLayout$1(model);
  const isSingleSelect = !!(layout && layout.qListObject.qDimensionInfo.qIsOneAndOnlyOne);
  const [pages, setPages] = useState$1(null);
  const [isLoadingData, setIsLoadingData] = useState$1(false);
  const styles = useStyles$b();
  const {
    instantPages = [],
    interactionEvents,
    select
  } = useSelectionsInteractions({
    layout,
    selections,
    pages,
    checkboxes,
    selectDisabled,
    doc: document,
    isSingleSelect
  });
  const loaderRef = useRef(null);
  const local = useRef({
    queue: [],
    validPages: false
  });
  const listData = useRef({
    pages: []
  });
  const isItemLoaded = useCallback(index => {
    if (!pages || !local.current.validPages) {
      return false;
    }

    local.current.checkIdx = index;

    const isLoaded = p => p.qArea.qTop <= index && index < p.qArea.qTop + p.qArea.qHeight;

    const page = pages.filter(p => isLoaded(p))[0];
    return page && isLoaded(page);
  }, [layout, pages]); // The time from scroll end until new data is being fetched, may be exposed in API later on.

  const scrollTimeout = 0;
  const loadMoreItems = useCallback((startIndex, stopIndex) => {
    local.current.queue.push({
      start: startIndex,
      stop: stopIndex
    });
    const isScrolling = loaderRef.current ? loaderRef.current._listRef.state.isScrolling : false;

    if (local.current.queue.length > 10) {
      local.current.queue.shift();
    }

    clearTimeout(local.current.timeout);
    setIsLoadingData(true);
    return new Promise(resolve => {
      local.current.timeout = setTimeout(() => {
        const sorted = local.current.queue.slice(-2).sort((a, b) => a.start - b.start);
        const reqPromise = model.getListObjectData('/qListObjectDef', sorted.map(s => ({
          qTop: s.start,
          qHeight: s.stop - s.start + 1,
          qLeft: 0,
          qWidth: 1
        }))).then(p => {
          local.current.validPages = true;
          listData.current.pages = p;
          setPages(p);
          setIsLoadingData(false);
          resolve();
        });
        fetchStart && fetchStart(reqPromise);
      }, isScrolling ? scrollTimeout : 0);
    });
  }, [layout]);

  const fetchData = () => {
    local.current.queue = [];
    local.current.validPages = false;

    if (loaderRef.current) {
      loaderRef.current.resetloadMoreItemsCache(true); // Skip scrollToItem if we are in selections, or if we dont sort by state.

      if (layout && layout.qSelectionInfo.qInSelections || sortByState === 0) {
        return;
      }

      loaderRef.current._listRef.scrollToItem(0);
    }
  };

  if (update) {
    // Hand over the update function for manual refresh from hosting application.
    update.call(null, fetchData);
  }

  useEffect$1(() => {
    fetchData();

    if (typeof setCount === 'function' && layout) {
      setCount(layout.qListObject.qSize.qcy);
    }
  }, [layout]);
  useEffect$1(() => {
    if (!instantPages || isLoadingData) {
      return;
    }

    setPages(instantPages);
  }, [instantPages]);
  const [initScrollPosIsSet, setInitScrollPosIsSet] = useState$1(false);
  useEffect$1(() => {
    if (scrollState && !initScrollPosIsSet && loaderRef.current) {
      loaderRef.current._listRef.scrollToItem(scrollState.initScrollPos);

      setInitScrollPosIsSet(true);
    }
  }, [loaderRef.current]);

  if (!layout) {
    return null;
  }

  const isVertical = listLayout !== 'horizontal';
  const count = layout.qListObject.qSize.qcy;
  const {
    itemSize,
    listHeight
  } = getSizeInfo({
    isVertical,
    checkboxes,
    dense,
    height
  });
  const isLocked = layout && layout.qListObject.qDimensionInfo.qLocked;
  const {
    frequencyMax
  } = layout;
  return /*#__PURE__*/React.createElement(InfiniteLoader, {
    isItemLoaded: isItemLoaded,
    itemCount: count,
    loadMoreItems: loadMoreItems,
    threshold: 0,
    minimumBatchSize: 100,
    ref: loaderRef
  }, _ref3 => {
    let {
      onItemsRendered,
      ref
    } = _ref3;
    local.current.listRef = ref;
    return /*#__PURE__*/React.createElement(FixedSizeList, {
      direction: direction,
      "data-testid": "fixed-size-list",
      useIsScrolling: true,
      style: {},
      height: listHeight,
      width: width,
      itemCount: count,
      layout: listLayout,
      className: styles.styledScrollbars,
      itemData: _objectSpread2(_objectSpread2({
        isLocked,
        column: !isVertical,
        pages
      }, isLocked || selectDisabled() ? {} : interactionEvents), {}, {
        checkboxes,
        dense,
        frequencyMode,
        isSingleSelect,
        actions: {
          select,
          confirm: () => selections && selections.confirm.call(selections),
          cancel: () => selections && selections.cancel.call(selections)
        },
        frequencyMax,
        histogram,
        keyboard,
        showGray
      }),
      itemSize: itemSize,
      onItemsRendered: renderProps => {
        if (scrollState) {
          scrollState.setScrollPos(renderProps.visibleStopIndex);
        }

        onItemsRendered(_objectSpread2({}, renderProps));
      },
      ref: ref
    }, RowColumn);
  });
}

const selectAll = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M15.4,9 C15.8,9 16,9.3 16,9.6 L16,15.4 C16,15.7 15.8,16 15.4,16 L9.6,16 C9.3,16 9,15.8 9,15.4 L9,9.6 C9,9.3 9.3,9 9.6,9 L15.4,9 Z M15,10 L10,10 L10,15 L15,15 L15,10 Z M6.5,0 C6.8,0 7,0.3 7,0.6 L7,6.4 C7,6.8 6.8,7 6.5,7 L0.6,7 C0.3,7 0,6.8 0,6.5 L0,0.6 C0,0.3 0.3,0 0.6,0 L6.5,0 Z M6,2.8 C6.3,2.5 6.3,2.1 6.1,1.8 C5.9,1.5 5.4,1.6 5.1,1.9 L3.1,3.9 L2.4,3.2 C2.1,2.9 1.7,2.9 1.4,3.1 C1.2,3.3 1.2,3.8 1.5,4.1 L2.7,5.3 C3,5.6 3.4,5.6 3.7,5.3 L3.8,5.3 L6,2.8 Z M6.5,9 C6.8,9 7,9.3 7,9.6 L7,15.4 C7,15.8 6.8,16 6.5,16 L0.6,16 C0.3,16 0,15.8 0,15.4 L0,9.6 C0,9.3 0.3,9 0.6,9 L6.5,9 Z M6,11.8 C6.3,11.5 6.3,11.1 6.1,10.8 C5.9,10.6 5.4,10.6 5.1,10.8 L3.1,12.8 L2.3,12 C2,11.7 1.6,11.7 1.3,12 C1.1,12.3 1.1,12.7 1.4,13 L2.6,14.2 C2.9,14.5 3.3,14.5 3.6,14.3 L3.7,14.2 L6,11.8 Z M15.4,0 C15.8,0 16,0.3 16,0.6 L16,6.4 C16,6.8 15.8,7 15.4,7 L9.6,7 C9.3,7 9,6.8 9,6.5 L9,0.6 C9,0.3 9.3,0 9.6,0 L15.4,0 Z M15,2.8 C15.3,2.5 15.3,2.1 15.1,1.8 C14.9,1.5 14.4,1.6 14.1,1.9 L12.1,3.9 L11.3,3.1 C11,2.8 10.6,2.8 10.3,3 C10,3.2 10.1,3.7 10.3,4 L11.5,5.2 C11.8,5.5 12.2,5.5 12.5,5.2 L15,2.8 Z'
    }
  }]
});

const selectAlternative = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M6,15.5 C6,15.2238576 6.22385763,15 6.5,15 L9.5,15 C9.77614237,15 10,15.2238576 10,15.5 C10,15.7761424 9.77614237,16 9.5,16 L6.5,16 C6.22385763,16 6,15.7761424 6,15.5 Z M1,13.5 L1,14.5 C1,14.7761424 1.22385763,15 1.5,15 L2.5,15 C2.77614237,15 3,15.2238576 3,15.5 C3,15.7761424 2.77614237,16 2.5,16 L1,16 C0.44771525,16 6.76353751e-17,15.5522847 0,15 L0,13.5 C-3.38176876e-17,13.2238576 0.223857625,13 0.5,13 C0.776142375,13 1,13.2238576 1,13.5 Z M15,13.5 C15,13.2238576 15.2238576,13 15.5,13 C15.7761424,13 16,13.2238576 16,13.5 L16,15 C16,15.5522847 15.5522847,16 15,16 L13.5,16 C13.2238576,16 13,15.7761424 13,15.5 C13,15.2238576 13.2238576,15 13.5,15 L14.5,15 C14.7761424,15 15,14.7761424 15,14.5 L15,13.5 Z M1,6.5 L1,9.5 C1,9.77614237 0.776142375,10 0.5,10 C0.223857625,10 3.38176876e-17,9.77614237 0,9.5 L0,6.5 C-3.38176876e-17,6.22385763 0.223857625,6 0.5,6 C0.776142375,6 1,6.22385763 1,6.5 Z M16,6.5 L16,9.5 C16,9.77614237 15.7761424,10 15.5,10 C15.2238576,10 15,9.77614237 15,9.5 L15,6.5 C15,6.22385763 15.2238576,6 15.5,6 C15.7761424,6 16,6.22385763 16,6.5 Z M0,2.5 L0,1 C-6.76353751e-17,0.44771525 0.44771525,1.01453063e-16 1,0 L2.5,0 C2.77614237,-5.07265313e-17 3,0.223857625 3,0.5 C3,0.776142375 2.77614237,1 2.5,1 L1.5,1 C1.22385763,1 1,1.22385763 1,1.5 L1,2.5 C1,2.77614237 0.776142375,3 0.5,3 C0.223857625,3 3.38176876e-17,2.77614237 0,2.5 Z M6,0.5 C6,0.223857625 6.22385763,5.07265313e-17 6.5,0 L9.5,0 C9.77614237,-5.07265313e-17 10,0.223857625 10,0.5 C10,0.776142375 9.77614237,1 9.5,1 L6.5,1 C6.22385763,1 6,0.776142375 6,0.5 Z M15,2.5 L15,1.5 C15,1.22385763 14.7761424,1 14.5,1 L13.5,1 C13.2238576,1 13,0.776142375 13,0.5 C13,0.223857625 13.2238576,5.07265313e-17 13.5,0 L15,0 C15.5522847,-1.01453063e-16 16,0.44771525 16,1 L16,2.5 C16,2.77614237 15.7761424,3 15.5,3 C15.2238576,3 15,2.77614237 15,2.5 Z M4,4 L4,12 L12,4 L4,4 Z M4,3 L12,3 C12.5522847,3 13,3.44771525 13,4 L13,12 C13,12.5522847 12.5522847,13 12,13 L4,13 C3.44771525,13 3,12.5522847 3,12 L3,4 C3,3.44771525 3.44771525,3 4,3 Z'
    }
  }]
});

const selectPossible = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M6,15.5 C6,15.2238576 6.22385763,15 6.5,15 L9.5,15 C9.77614237,15 10,15.2238576 10,15.5 C10,15.7761424 9.77614237,16 9.5,16 L6.5,16 C6.22385763,16 6,15.7761424 6,15.5 Z M1,13.5 L1,14.5 C1,14.7761424 1.22385763,15 1.5,15 L2.5,15 C2.77614237,15 3,15.2238576 3,15.5 C3,15.7761424 2.77614237,16 2.5,16 L1,16 C0.44771525,16 6.76353751e-17,15.5522847 0,15 L0,13.5 C-3.38176876e-17,13.2238576 0.223857625,13 0.5,13 C0.776142375,13 1,13.2238576 1,13.5 Z M15,13.5 C15,13.2238576 15.2238576,13 15.5,13 C15.7761424,13 16,13.2238576 16,13.5 L16,15 C16,15.5522847 15.5522847,16 15,16 L13.5,16 C13.2238576,16 13,15.7761424 13,15.5 C13,15.2238576 13.2238576,15 13.5,15 L14.5,15 C14.7761424,15 15,14.7761424 15,14.5 L15,13.5 Z M1,6.5 L1,9.5 C1,9.77614237 0.776142375,10 0.5,10 C0.223857625,10 3.38176876e-17,9.77614237 0,9.5 L0,6.5 C-3.38176876e-17,6.22385763 0.223857625,6 0.5,6 C0.776142375,6 1,6.22385763 1,6.5 Z M16,6.5 L16,9.5 C16,9.77614237 15.7761424,10 15.5,10 C15.2238576,10 15,9.77614237 15,9.5 L15,6.5 C15,6.22385763 15.2238576,6 15.5,6 C15.7761424,6 16,6.22385763 16,6.5 Z M0,2.5 L0,1 C-6.76353751e-17,0.44771525 0.44771525,1.01453063e-16 1,0 L2.5,0 C2.77614237,-5.07265313e-17 3,0.223857625 3,0.5 C3,0.776142375 2.77614237,1 2.5,1 L1.5,1 C1.22385763,1 1,1.22385763 1,1.5 L1,2.5 C1,2.77614237 0.776142375,3 0.5,3 C0.223857625,3 3.38176876e-17,2.77614237 0,2.5 Z M6,0.5 C6,0.223857625 6.22385763,5.07265313e-17 6.5,0 L9.5,0 C9.77614237,-5.07265313e-17 10,0.223857625 10,0.5 C10,0.776142375 9.77614237,1 9.5,1 L6.5,1 C6.22385763,1 6,0.776142375 6,0.5 Z M15,2.5 L15,1.5 C15,1.22385763 14.7761424,1 14.5,1 L13.5,1 C13.2238576,1 13,0.776142375 13,0.5 C13,0.223857625 13.2238576,5.07265313e-17 13.5,0 L15,0 C15.5522847,-1.01453063e-16 16,0.44771525 16,1 L16,2.5 C16,2.77614237 15.7761424,3 15.5,3 C15.2238576,3 15,2.77614237 15,2.5 Z M4,4 L4,12 L12,12 L12,4 L4,4 Z M4,3 L12,3 C12.5522847,3 13,3.44771525 13,4 L13,12 C13,12.5522847 12.5522847,13 12,13 L4,13 C3.44771525,13 3,12.5522847 3,12 L3,4 C3,3.44771525 3.44771525,3 4,3 Z'
    }
  }]
});

const selectExcluded = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M6,15.5 C6,15.2238576 6.22385763,15 6.5,15 L9.5,15 C9.77614237,15 10,15.2238576 10,15.5 C10,15.7761424 9.77614237,16 9.5,16 L6.5,16 C6.22385763,16 6,15.7761424 6,15.5 Z M1,13.5 L1,14.5 C1,14.7761424 1.22385763,15 1.5,15 L2.5,15 C2.77614237,15 3,15.2238576 3,15.5 C3,15.7761424 2.77614237,16 2.5,16 L1,16 C0.44771525,16 6.76353751e-17,15.5522847 0,15 L0,13.5 C-3.38176876e-17,13.2238576 0.223857625,13 0.5,13 C0.776142375,13 1,13.2238576 1,13.5 Z M15,13.5 C15,13.2238576 15.2238576,13 15.5,13 C15.7761424,13 16,13.2238576 16,13.5 L16,15 C16,15.5522847 15.5522847,16 15,16 L13.5,16 C13.2238576,16 13,15.7761424 13,15.5 C13,15.2238576 13.2238576,15 13.5,15 L14.5,15 C14.7761424,15 15,14.7761424 15,14.5 L15,13.5 Z M1,6.5 L1,9.5 C1,9.77614237 0.776142375,10 0.5,10 C0.223857625,10 3.38176876e-17,9.77614237 0,9.5 L0,6.5 C-3.38176876e-17,6.22385763 0.223857625,6 0.5,6 C0.776142375,6 1,6.22385763 1,6.5 Z M16,6.5 L16,9.5 C16,9.77614237 15.7761424,10 15.5,10 C15.2238576,10 15,9.77614237 15,9.5 L15,6.5 C15,6.22385763 15.2238576,6 15.5,6 C15.7761424,6 16,6.22385763 16,6.5 Z M0,2.5 L0,1 C-6.76353751e-17,0.44771525 0.44771525,1.01453063e-16 1,0 L2.5,0 C2.77614237,-5.07265313e-17 3,0.223857625 3,0.5 C3,0.776142375 2.77614237,1 2.5,1 L1.5,1 C1.22385763,1 1,1.22385763 1,1.5 L1,2.5 C1,2.77614237 0.776142375,3 0.5,3 C0.223857625,3 3.38176876e-17,2.77614237 0,2.5 Z M6,0.5 C6,0.223857625 6.22385763,5.07265313e-17 6.5,0 L9.5,0 C9.77614237,-5.07265313e-17 10,0.223857625 10,0.5 C10,0.776142375 9.77614237,1 9.5,1 L6.5,1 C6.22385763,1 6,0.776142375 6,0.5 Z M15,2.5 L15,1.5 C15,1.22385763 14.7761424,1 14.5,1 L13.5,1 C13.2238576,1 13,0.776142375 13,0.5 C13,0.223857625 13.2238576,5.07265313e-17 13.5,0 L15,0 C15.5522847,-1.01453063e-16 16,0.44771525 16,1 L16,2.5 C16,2.77614237 15.7761424,3 15.5,3 C15.2238576,3 15,2.77614237 15,2.5 Z M4,3 L12,3 C12.5522847,3 13,3.44771525 13,4 L13,12 C13,12.5522847 12.5522847,13 12,13 L4,13 C3.44771525,13 3,12.5522847 3,12 L3,4 C3,3.44771525 3.44771525,3 4,3 Z'
    }
  }]
});

var createListboxSelectionToolbar = (_ref => {
  let {
    layout,
    model,
    translator
  } = _ref;

  if (layout.qListObject.qDimensionInfo.qIsOneAndOnlyOne) {
    return [];
  }

  const canSelectAll = () => ['qOption', 'qAlternative', 'qExcluded', 'qDeselected'].some(sc => layout.qListObject.qDimensionInfo.qStateCounts[sc] > 0);

  const canSelectPossible = () => ['qOption'].some(sc => layout.qListObject.qDimensionInfo.qStateCounts[sc] > 0);

  const canSelectAlternative = () => ['qAlternative'].some(sc => layout.qListObject.qDimensionInfo.qStateCounts[sc] > 0);

  const canSelectExcluded = () => ['qAlternative', 'qExcluded'].some(sc => layout.qListObject.qDimensionInfo.qStateCounts[sc] > 0);

  return [{
    key: 'selectAll',
    type: 'menu-icon-button',
    label: translator.get('Selection.SelectAll'),
    getSvgIconShape: selectAll,
    enabled: canSelectAll,
    action: () => {
      model.selectListObjectAll('/qListObjectDef');
    }
  }, {
    key: 'selectPossible',
    type: 'menu-icon-button',
    label: translator.get('Selection.SelectPossible'),
    getSvgIconShape: selectPossible,
    enabled: canSelectPossible,
    action: () => {
      model.selectListObjectPossible('/qListObjectDef');
    }
  }, {
    key: 'selectAlternative',
    type: 'menu-icon-button',
    label: translator.get('Selection.SelectAlternative'),
    getSvgIconShape: selectAlternative,
    enabled: canSelectAlternative,
    action: () => {
      model.selectListObjectAlternative('/qListObjectDef');
    }
  }, {
    key: 'selectExcluded',
    type: 'menu-icon-button',
    label: translator.get('Selection.SelectExcluded'),
    getSvgIconShape: selectExcluded,
    enabled: canSelectExcluded,
    action: () => {
      model.selectListObjectExcluded('/qListObjectDef');
    }
  }];
});

const more = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M2,6.5 L3,6.5 C3.55228475,6.5 4,6.94771525 4,7.5 L4,8.5 C4,9.05228475 3.55228475,9.5 3,9.5 L2,9.5 C1.44771525,9.5 1,9.05228475 1,8.5 L1,7.5 C1,6.94771525 1.44771525,6.5 2,6.5 Z M7.5,6.5 L8.5,6.5 C9.05228475,6.5 9.5,6.94771525 9.5,7.5 L9.5,8.5 C9.5,9.05228475 9.05228475,9.5 8.5,9.5 L7.5,9.5 C6.94771525,9.5 6.5,9.05228475 6.5,8.5 L6.5,7.5 C6.5,6.94771525 6.94771525,6.5 7.5,6.5 Z M13,6.5 L14,6.5 C14.5522847,6.5 15,6.94771525 15,7.5 L15,8.5 C15,9.05228475 14.5522847,9.5 14,9.5 L13,9.5 C12.4477153,9.5 12,9.05228475 12,8.5 L12,7.5 C12,6.94771525 12.4477153,6.5 13,6.5 Z'
    }
  }]
});

function useActionState(item) {
  const theme = useTheme$1();
  const disabled = typeof item.enabled === 'function' ? !item.enabled() : !!item.disabled;
  const hasSvgIconShape = typeof item.getSvgIconShape === 'function';
  return {
    hidden: item.hidden === true,
    disabled,
    style: {
      backgroundColor: item.active ? theme.palette.btn.active : undefined
    },
    hasSvgIconShape
  };
}

/**
 * @interface
 * @extends HTMLElement
 * @since 2.0.0
 */

const ActionElement = {
  /** @type {'njs-cell-action'} */
  className: 'njs-cell-action'
};
const Item = React.forwardRef((_ref, ref) => {
  let {
    item,
    addAnchor = false
  } = _ref;
  const theme = useTheme$1();
  const {
    hidden,
    disabled,
    style,
    hasSvgIconShape
  } = useActionState(item);
  if (hidden) return null;
  const handleKeyDown = item.keyboardAction ? e => ['Enter', ' ', 'Spacebar'].includes(e.key) && item.keyboardAction() : null;
  return /*#__PURE__*/React.createElement(IconButton, {
    ref: !addAnchor ? ref : null,
    title: item.label,
    onClick: item.action,
    onKeyDown: handleKeyDown,
    disabled: disabled,
    style: style,
    className: ActionElement.className
  }, hasSvgIconShape && SvgIcon(item.getSvgIconShape()), addAnchor && /*#__PURE__*/React.createElement("div", {
    ref: ref,
    style: {
      bottom: -theme.spacing(0.5),
      right: 0,
      position: 'absolute',
      width: '100%',
      height: 0
    }
  }));
});

const close = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M9.34535242,8 L13.3273238,11.9819714 C13.6988326,12.3534802 13.6988326,12.955815 13.3273238,13.3273238 C12.955815,13.6988326 12.3534802,13.6988326 11.9819714,13.3273238 L8,9.34535242 L4.01802863,13.3273238 C3.64651982,13.6988326 3.04418502,13.6988326 2.67267621,13.3273238 C2.3011674,12.955815 2.3011674,12.3534802 2.67267621,11.9819714 L6.65464758,8 L2.67267621,4.01802863 C2.3011674,3.64651982 2.3011674,3.04418502 2.67267621,2.67267621 C3.04418502,2.3011674 3.64651982,2.3011674 4.01802863,2.67267621 L8,6.65464758 L11.9819714,2.67267621 C12.3534802,2.3011674 12.955815,2.3011674 13.3273238,2.67267621 C13.6988326,3.04418502 13.6988326,3.64651982 13.3273238,4.01802863 L9.34535242,8 Z'
    }
  }]
});

const clearSelections = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M6,15.5 L6,15.5 C6,15.2238576 6.22385763,15 6.5,15 L9.5,15 C9.77614237,15 10,15.2238576 10,15.5 L10,15.5 C10,15.7761424 9.77614237,16 9.5,16 L6.5,16 C6.22385763,16 6,15.7761424 6,15.5 Z M1,13.5 L1,14.5 C1,14.7761424 1.22385763,15 1.5,15 L2.5,15 C2.77614237,15 3,15.2238576 3,15.5 L3,15.5 C3,15.7761424 2.77614237,16 2.5,16 L1,16 C0.44771525,16 6.76353751e-17,15.5522847 0,15 L0,13.5 C-3.38176876e-17,13.2238576 0.223857625,13 0.5,13 L0.5,13 C0.776142375,13 1,13.2238576 1,13.5 Z M1,6.5 L1,9.5 C1,9.77614237 0.776142375,10 0.5,10 L0.5,10 C0.223857625,10 3.38176876e-17,9.77614237 0,9.5 L0,6.5 C-3.38176876e-17,6.22385763 0.223857625,6 0.5,6 L0.5,6 C0.776142375,6 1,6.22385763 1,6.5 Z M0,2.5 L0,1 C-6.76353751e-17,0.44771525 0.44771525,1.01453063e-16 1,0 L2.5,0 C2.77614237,-5.07265313e-17 3,0.223857625 3,0.5 L3,0.5 C3,0.776142375 2.77614237,1 2.5,1 L1.5,1 C1.22385763,1 1,1.22385763 1,1.5 L1,2.5 C1,2.77614237 0.776142375,3 0.5,3 L0.5,3 C0.223857625,3 3.38176876e-17,2.77614237 0,2.5 Z M6,0.5 L6,0.5 C6,0.223857625 6.22385763,5.07265313e-17 6.5,0 L9.5,0 C9.77614237,-5.07265313e-17 10,0.223857625 10,0.5 L10,0.5 C10,0.776142375 9.77614237,1 9.5,1 L6.5,1 C6.22385763,1 6,0.776142375 6,0.5 Z M15,2.5 L15,1.5 C15,1.22385763 14.7761424,1 14.5,1 L13.5,1 C13.2238576,1 13,0.776142375 13,0.5 L13,0.5 C13,0.223857625 13.2238576,5.07265313e-17 13.5,0 L15,0 C15.5522847,-1.01453063e-16 16,0.44771525 16,1 L16,2.5 C16,2.77614237 15.7761424,3 15.5,3 L15.5,3 C15.2238576,3 15,2.77614237 15,2.5 Z M9.1661442,6.1661442 C10.7210031,4.61128527 13.2789969,4.61128527 14.8338558,6.1661442 C16.3887147,7.72100313 16.3887147,10.2789969 14.8338558,11.8338558 C13.2789969,13.3887147 10.7210031,13.3887147 9.1661442,11.8338558 C7.61128527,10.2789969 7.61128527,7.77115987 9.1661442,6.1661442 Z M14.1316614,7.72100313 C14.3322884,7.52037618 14.3824451,7.169279 14.1316614,6.9184953 C13.8808777,6.6677116 13.5297806,6.71786834 13.3291536,6.9184953 L12.0250784,8.22257053 L10.7210031,6.9184953 C10.5203762,6.6677116 10.1191223,6.6677116 9.9184953,6.9184953 C9.6677116,7.11912226 9.6677116,7.52037618 9.9184953,7.72100313 L11.2225705,9.02507837 L9.9184953,10.3291536 C9.6677116,10.5297806 9.6677116,10.8808777 9.9184953,11.1316614 C10.169279,11.3824451 10.5203762,11.3824451 10.7210031,11.1316614 L12.0250784,9.82758621 L13.3291536,11.1316614 C13.5297806,11.3824451 13.8808777,11.3824451 14.1316614,11.1316614 C14.3322884,10.9310345 14.3824451,10.5297806 14.1316614,10.3291536 L12.8275862,9.02507837 L14.1316614,7.72100313 Z'
    }
  }]
});

var ClearSelections = (props => SvgIcon(clearSelections(props)));

function useDefaultSelectionActions(_ref) {
  let {
    api,
    onConfirm = () => {},
    onCancel = () => {},
    onKeyDeactivate = () => {}
  } = _ref;
  const {
    translator
  } = useContext(InstanceContext);
  return [{
    key: 'clear',
    type: 'icon-button',
    label: translator.get('Selection.Clear'),
    enabled: () => api.canClear(),
    action: () => api.clear(),
    getSvgIconShape: clearSelections
  }, {
    key: 'cancel',
    type: 'icon-button',
    label: translator.get('Selection.Cancel'),
    enabled: () => api.canCancel(),
    action: () => {
      onCancel();
      api.cancel();
    },
    keyboardAction: e => {
      onKeyDeactivate(e);
      onCancel();
      api.cancel();
    },
    getSvgIconShape: close
  }, {
    key: 'confirm',
    type: 'icon-button',
    label: translator.get('Selection.Confirm'),
    enabled: () => api.canConfirm(),
    action: () => {
      onConfirm();
      api.confirm();
    },
    keyboardAction: e => {
      onKeyDeactivate(e);
      onConfirm();
      api.confirm();
    },
    getSvgIconShape: tick
  }];
}

const useStyles$a = makeStyles$1(theme => ({
  icon: {
    color: theme.palette.text.primary
  }
}));

function MoreItem(_ref) {
  let {
    item,
    onActionClick = () => {}
  } = _ref;
  const {
    hidden,
    disabled,
    hasSvgIconShape
  } = useActionState(item);
  const {
    icon
  } = useStyles$a();

  const handleClick = () => {
    item.action();
    onActionClick();
  };

  return !hidden ? /*#__PURE__*/React.createElement(MenuItem, {
    title: item.label,
    onClick: handleClick,
    disabled: disabled
  }, hasSvgIconShape && /*#__PURE__*/React.createElement(ListItemIcon, {
    className: icon
  }, SvgIcon(item.getSvgIconShape())), /*#__PURE__*/React.createElement(Typography, {
    noWrap: true
  }, item.label)) : null;
}

const More$1 = React.forwardRef((_ref2, ref) => {
  let {
    actions = [],
    show = true,
    alignTo,
    popoverProps = {},
    popoverPaperStyle = {},
    onCloseOrActionClick = () => {}
  } = _ref2;
  const showActions = actions.length > 0;
  return showActions && /*#__PURE__*/React.createElement(Popover // eslint-disable-next-line react/jsx-props-no-spreading
  , _extends$4({}, popoverProps, {
    onClose: onCloseOrActionClick,
    ref: ref,
    open: show,
    anchorEl: alignTo.current,
    getContentAnchorEl: null,
    container: alignTo.current,
    disablePortal: true,
    hideBackdrop: true,
    style: {
      pointerEvents: 'none'
    },
    transitionDuration: 0,
    anchorOrigin: {
      vertical: 'bottom',
      horizontal: 'right'
    },
    transformOrigin: {
      vertical: 'top',
      horizontal: 'right'
    },
    PaperProps: {
      style: _objectSpread2({
        pointerEvents: 'auto',
        maxWidth: '250px'
      }, popoverPaperStyle)
    }
  }), /*#__PURE__*/React.createElement(MenuList, null, actions.map((item, ix) =>
  /*#__PURE__*/
  // eslint-disable-next-line react/no-array-index-key
  React.createElement(MoreItem, {
    key: ix,
    item: item,
    onActionClick: onCloseOrActionClick
  }))));
});

/**
 * @interface
 * @extends HTMLElement
 * @since 2.1.0
 */

const ActionToolbarElement = {
  /** @type {'njs-action-toolbar-popover'} */
  className: 'njs-action-toolbar-popover'
};
const useStyles$9 = makeStyles$1(theme => ({
  itemSpacing: {
    padding: theme.spacing(0, 0.5)
  },
  firstItemSpacing: {
    padding: theme.spacing(0, 0.5, 0, 0)
  },
  lastItemSpacing: {
    padding: theme.spacing(0, 0, 0, 0.5)
  }
}));
const ActionsGroup = React.forwardRef((_ref, ref) => {
  let {
    actions = [],
    first = false,
    last = false,
    addAnchor = false
  } = _ref;
  const {
    itemSpacing,
    firstItemSpacing,
    lastItemSpacing
  } = useStyles$9();
  return actions.length > 0 ? /*#__PURE__*/React.createElement(Grid, {
    item: true,
    container: true,
    spacing: 0,
    wrap: "nowrap"
  }, actions.map((e, ix) => {
    let cls = [];
    const isFirstItem = first && ix === 0;
    const isLastItem = last && actions.length - 1 === ix;

    if (isFirstItem && !isLastItem) {
      cls = [firstItemSpacing];
    }

    if (isLastItem && !isFirstItem) {
      cls = [...cls, lastItemSpacing];
    }

    if (!isFirstItem && !isLastItem && cls.length === 0) {
      cls = [itemSpacing];
    }

    return /*#__PURE__*/React.createElement(Grid, {
      item: true,
      key: e.key,
      className: cls.join(' ').trim()
    }, /*#__PURE__*/React.createElement(Item, {
      key: e.key,
      item: e,
      ref: ix === 0 ? ref : null,
      addAnchor: addAnchor
    }));
  })) : null;
});
const popoverStyle = {
  pointerEvents: 'none'
};
const popoverAnchorOrigin = {
  vertical: 'top',
  horizontal: 'right'
};
const popoverTransformOrigin = {
  vertical: 'bottom',
  horizontal: 'right'
};

function ActionsToolbar(_ref2) {
  let {
    show = true,
    actions = [],
    maxItems = 3,
    selections = {
      show: false,
      api: null,
      onConfirm: () => {},
      onCancel: () => {}
    },
    more: more$1 = {
      enabled: false,
      actions: [],
      alignTo: null,
      popoverProps: {},
      popoverPaperStyle: {}
    },
    popover = {
      show: false,
      anchorEl: null
    },
    focusHandler = null,
    actionsRefMock = null // for testing

  } = _ref2;
  const defaultSelectionActions = useDefaultSelectionActions(selections);
  const {
    itemSpacing
  } = useStyles$9();
  const {
    translator,
    keyboardNavigation
  } = useContext(InstanceContext);
  const [showMoreItems, setShowMoreItems] = useState$1(false);
  const [moreEnabled, setMoreEnabled] = useState$1(more$1.enabled);
  const [moreActions, setMoreActions] = useState$1(more$1.actions);
  const [moreAlignTo, setMoreAlignTo] = useState$1(more$1.alignTo);
  const moreRef = useRef();
  const actionsRef = useRef();
  const theme = useTheme$1();
  const dividerStyle = useMemo$1(() => ({
    margin: theme.spacing(0.5, 0)
  }));

  const getEnabledButton = last => {
    const actionsElement = actionsRef.current || actionsRefMock;
    if (!actionsElement) return null;
    const buttons = actionsElement.querySelectorAll('button:not(.Mui-disabled)');
    return buttons[last ? buttons.length - 1 : 0];
  };

  useEffect$1(() => () => setShowMoreItems(false), [popover.show]);
  useEffect$1(() => {
    setMoreEnabled(more$1.enabled);
  }, [more$1.enabled]);
  useEffect$1(() => {
    if (!focusHandler) return;

    const focusFirst = () => {
      const enabledButton = getEnabledButton(false);
      enabledButton && enabledButton.focus();
    };

    const focusLast = () => {
      const enabledButton = getEnabledButton(true);
      enabledButton && enabledButton.focus();
    };

    focusHandler.on('focus_toolbar_first', focusFirst);
    focusHandler.on('focus_toolbar_last', focusLast);
  }, []);
  const newActions = useMemo$1(() => actions.filter(a => !a.hidden), [actions]);
  if (!selections.show && newActions.length === 0) return null;

  const handleCloseShowMoreItems = () => {
    setShowMoreItems(false);
  };

  const moreItem = {
    key: 'more',
    label: translator.get('Menu.More'),
    // TODO: Add translation
    getSvgIconShape: more,
    hidden: false,
    enabled: () => moreEnabled,
    action: () => setShowMoreItems(!showMoreItems)
  };

  if (newActions.length > maxItems) {
    const newMoreActions = newActions.splice(-(newActions.length - maxItems) - 1);
    setMoreEnabled(true);
    setMoreActions([...newMoreActions, ...more$1.actions]);
    setMoreAlignTo(moreRef);
  }

  const tabCallback = // if keyboardNavigation is true, create a callback to handle tabbing from the first/last button in the toolbar that resets focus on the content
  keyboardNavigation && focusHandler && focusHandler.refocusContent ? evt => {
    if (evt.key !== 'Tab') return;
    const isTabbingOut = evt.shiftKey && getEnabledButton(false) === evt.target || !evt.shiftKey && getEnabledButton(true) === evt.target;

    if (isTabbingOut) {
      evt.preventDefault();
      evt.stopPropagation();
      focusHandler.refocusContent();
    }
  } : null;
  const showActions = newActions.length > 0;
  const showMore = moreActions.length > 0;
  const showDivider = showActions && selections.show || showMore && selections.show;
  const Actions = /*#__PURE__*/React.createElement(Grid, {
    ref: actionsRef,
    onKeyDown: tabCallback,
    container: true,
    spacing: 0,
    wrap: "nowrap"
  }, showActions && /*#__PURE__*/React.createElement(ActionsGroup, {
    actions: newActions,
    first: true,
    last: !showMore && !selections.show
  }), showMore && /*#__PURE__*/React.createElement(ActionsGroup, {
    ref: moreRef,
    actions: [moreItem],
    first: !showActions,
    last: !selections.show,
    addAnchor: true
  }), showDivider && /*#__PURE__*/React.createElement(Grid, {
    item: true,
    className: itemSpacing,
    style: dividerStyle
  }, /*#__PURE__*/React.createElement(Divider, {
    orientation: "vertical"
  })), selections.show && /*#__PURE__*/React.createElement(ActionsGroup, {
    actions: defaultSelectionActions,
    first: !showActions && !showMore,
    last: true
  }), showMoreItems && /*#__PURE__*/React.createElement(More$1, {
    show: showMoreItems,
    actions: moreActions,
    alignTo: moreAlignTo,
    popoverProps: more$1.popoverProps,
    popoverPaperStyle: more$1.popoverPaperStyle,
    onCloseOrActionClick: handleCloseShowMoreItems
  }));
  return popover.show ? /*#__PURE__*/React.createElement(Popover, {
    disableEnforceFocus: true,
    disableAutoFocus: true,
    disableRestoreFocus: true,
    open: popover.show,
    anchorEl: popover.anchorEl,
    anchorOrigin: popoverAnchorOrigin,
    transformOrigin: popoverTransformOrigin,
    hideBackdrop: true,
    style: popoverStyle,
    PaperProps: {
      className: ActionToolbarElement.className,
      style: {
        pointerEvents: 'auto',
        padding: theme.spacing(1, 1)
      }
    }
  }, Actions) : show && Actions;
}

const search = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M15.7873809,13.80959 C16.1870614,14.209868 15.9872212,15.1104934 15.4876205,15.5107714 C15.08794,15.9110493 14.1886588,16.2112578 13.7889782,15.8109798 L11.0911347,13.1091035 L10.9912145,12.5086866 L10.2917736,11.8082001 C9.19265216,12.5086866 7.89369045,13.0090341 6.49480859,13.0090341 C2.89768383,13.0090341 0,10.1070188 0,6.50451703 C0,2.90201529 2.89768383,0 6.49480859,0 C10.0919334,0 12.9896172,2.90201529 12.9896172,6.50451703 C12.9896172,7.90548992 12.4900165,9.20639333 11.7905756,10.3071577 L12.4900165,11.0076442 L13.0895373,11.1077137 L15.7873809,13.80959 Z M11.2909749,6.50451703 C11.2909749,5.20361362 10.7913743,4.00277971 9.89209309,3.00208478 C8.9928119,2.10145935 7.79377031,1.60111188 6.49480859,1.60111188 C5.19584688,1.60111188 3.99680529,2.10145935 2.99760397,3.00208478 C2.09832278,4.00277971 1.59872212,5.20361362 1.59872212,6.50451703 C1.59872212,7.80542043 2.09832278,9.00625434 2.99760397,9.90687978 C3.89688516,10.8075052 5.09592674,11.3078527 6.49480859,11.3078527 C7.79377031,11.4079222 8.9928119,10.9075747 9.89209309,9.90687978 C10.7913743,9.00625434 11.2909749,7.80542043 11.2909749,6.50451703 Z'
    }
  }]
});

var SearchIcon = (props => SvgIcon(search(props)));

const useStyles$8 = makeStyles(theme => ({
  root: {
    border: 'none',
    borderRadius: 0,
    '& fieldset': {
      border: "1px solid ".concat(theme.palette.divider),
      borderWidth: '1px 0 1px 0',
      borderRadius: 0
    },
    '&:hover': {
      border: 'none'
    }
  },
  dense: {
    fontSize: 12,
    paddingLeft: theme.spacing(1),
    '& input': {
      paddingTop: '5px',
      paddingBottom: '5px'
    }
  }
}));
const TREE_PATH = '/qListObjectDef';
function ListBoxSearch(_ref) {
  let {
    model,
    keyboard,
    dense = false
  } = _ref;
  const {
    translator
  } = useContext(InstanceContext);
  const [value, setValue] = useState$1('');

  const onChange = e => {
    setValue(e.target.value);
    model.searchListObjectFor(TREE_PATH, e.target.value);
  };

  const onKeyDown = e => {
    switch (e.key) {
      case 'Enter':
        model.acceptListObjectSearch(TREE_PATH, true);
        setValue('');
        break;

      case 'Escape':
        model.abortListObjectSearch(TREE_PATH);
        break;
    }
  };

  const classes = useStyles$8();
  return /*#__PURE__*/React.createElement(OutlinedInput, {
    startAdornment: /*#__PURE__*/React.createElement(InputAdornment, {
      position: "start"
    }, /*#__PURE__*/React.createElement(SearchIcon, {
      size: dense ? 'small' : 'normal'
    })),
    className: ['search', classes.root, dense && classes.dense].filter(Boolean).join(' '),
    margin: "dense",
    fullWidth: true,
    placeholder: translator.get('Listbox.Search'),
    value: value,
    onChange: onChange,
    onKeyDown: onKeyDown,
    inputProps: {
      tabIndex: keyboard && (!keyboard.enabled || keyboard.active) ? 0 : -1
    }
  });
}

function eventmixin (obj) {
  /* eslint no-param-reassign: 0 */
  Object.keys(nodeEventEmitter.prototype).forEach(key => {
    obj[key] = nodeEventEmitter.prototype[key];
  });
  nodeEventEmitter.init(obj);
  return obj;
}

/* eslint no-underscore-dangle: 0 */

const event = () => {
  let prevented = false;
  return {
    isPrevented: () => prevented,
    preventDefault: () => {
      prevented = true;
    }
  };
};

function createObjectSelections(_ref) {
  let {
    appSelections,
    appModal,
    model
  } = _ref;
  let layout;
  let isActive = false;
  let hasSelected = false;
  /**
   * @class
   * @alias ObjectSelections
   */

  const api =
  /** @lends ObjectSelections# */
  {
    // model,
    id: model.id,

    setLayout(lyt) {
      layout = lyt;
    },

    /**
     * @param {string[]} paths
     * @returns {Promise<undefined>}
     */
    begin(paths) {
      const e = event(); // TODO - event as parameter?

      this.emit('activate', e);

      if (e.isPrevented()) {
        return Promise.resolve();
      }

      isActive = true;
      this.emit('activated');
      return appModal.begin(model, paths, true);
    },

    /**
     * @returns {Promise<undefined>}
     */
    clear() {
      hasSelected = false;
      this.emit('cleared');

      if (layout.qListObject) {
        return model.clearSelections('/qListObjectDef');
      }

      return model.resetMadeSelections();
    },

    /**
     * @returns {Promise<undefined>}
     */
    confirm() {
      hasSelected = false;
      isActive = false;
      this.emit('confirmed');
      this.emit('deactivated');
      return appModal.end(true);
    },

    /**
     * @returns {Promise<undefined>}
     */
    cancel() {
      hasSelected = false;
      isActive = false;
      this.emit('canceled'); // FIXME - spelling?

      this.emit('deactivated');
      return appModal.end(false);
    },

    /**
     * @param {object} s
     * @param {string} s.method
     * @param {any[]} s.params
     * @returns {Promise<boolean>}
     */
    async select(s) {
      const b = this.begin([s.params[0]]);

      if (!appSelections.isModal()) {
        return false;
      }

      await b;
      const qSuccess = await model[s.method](...s.params);
      hasSelected = s.method !== 'resetMadeSelections';

      if (!qSuccess) {
        model.resetMadeSelections();
        return false;
      }

      return true;
    },

    /**
     * @returns {boolean}
     */
    canClear() {
      if (layout && layout.qListObject && layout.qListObject.qDimensionInfo) {
        return !layout.qListObject.qDimensionInfo.qLocked && !layout.qListObject.qDimensionInfo.qIsOneAndOnlyOne;
      }

      return hasSelected;
    },

    /**
     * @returns {boolean}
     */
    canConfirm() {
      if (layout && layout.qListObject && layout.qListObject.qDimensionInfo) {
        return !layout.qListObject.qDimensionInfo.qLocked;
      }

      return hasSelected;
    },

    /**
     * @returns {boolean}
     */
    canCancel() {
      if (layout && layout.qListObject && layout.qListObject.qDimensionInfo) {
        return !layout.qListObject.qDimensionInfo.qLocked;
      }

      return true;
    },

    /**
     * @returns {boolean}
     */
    isActive: () => isActive,

    /**
     * @returns {boolean}
     */
    isModal: () => appSelections.isModal(model),

    /**
     * @param {string[]} paths
     * @returns {Promise<undefined>}
     */
    goModal: paths => appModal.begin(model, paths, false),

    /**
     * @param {boolean} [accept=false]
     * @returns {Promise<undefined>}
     */
    noModal: function () {
      let accept = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
      return appModal.end(accept);
    }
  };
  eventmixin(api);
  return api;
}

function useObjectSelections(app, model) {
  const [appSelections] = useAppSelections(app);
  const [layout] = useLayout$1(model);
  const key = model ? model.id : null;
  const [appModalStore] = useAppModalStore();
  const [objectSelectionsStore] = useObjectSelectionsStore();
  const appModal = appModalStore.get(app.id);
  let objectSelections = objectSelectionsStore.get(key);
  useEffect$1(() => {
    if (!appSelections || !model || objectSelections) return;
    objectSelections = createObjectSelections({
      appSelections,
      appModal,
      model
    });
    objectSelectionsStore.set(key, objectSelections);
    objectSelectionsStore.dispatch(true);
  }, [appSelections, model]);
  useEffect$1(() => {
    if (!objectSelections) return;
    objectSelections.setLayout(layout);
  }, [objectSelections, layout]);
  return [objectSelections];
}

function ListBoxPopover(_ref) {
  let {
    alignTo,
    show,
    close,
    app,
    fieldName,
    stateName = '$'
  } = _ref;
  const open = show && Boolean(alignTo.current);
  const theme = useTheme$1();
  const [model] = useSessionModel({
    qInfo: {
      qType: 'njsListbox'
    },
    qListObjectDef: {
      qStateName: stateName,
      qShowAlternatives: true,
      qInitialDataFetch: [{
        qTop: 0,
        qLeft: 0,
        qWidth: 0,
        qHeight: 0
      }],
      qDef: {
        qSortCriterias: [{
          qSortByState: 1,
          qSortByAscii: 1,
          qSortByNumeric: 1,
          qSortByLoadOrder: 1
        }],
        qFieldDefs: [fieldName]
      }
    }
  }, app, fieldName, stateName);
  const lock = useCallback(() => {
    model.lock('/qListObjectDef');
  }, [model]);
  const unlock = useCallback(() => {
    model.unlock('/qListObjectDef');
  }, [model]);
  const {
    translator
  } = useContext(InstanceContext);
  const moreAlignTo = useRef();
  const [selections] = useObjectSelections(app, model);
  const [layout] = useLayout$1(model);
  useEffect$1(() => {
    if (selections && open) {
      if (!selections.isModal(model)) {
        selections.goModal('/qListObjectDef');
      }
    }
  }, [selections, open]);

  if (!model || !layout || !translator) {
    return null;
  }

  const isLocked = layout.qListObject.qDimensionInfo.qLocked === true;

  const popoverClose = (e, reason) => {
    const accept = reason !== 'escapeKeyDown';
    selections.noModal(accept);
    close();
  };

  const listboxSelectionToolbarItems = createListboxSelectionToolbar({
    layout,
    model,
    translator
  });
  const counts = layout.qListObject.qDimensionInfo.qStateCounts;
  const hasSelections = counts.qSelected + counts.qSelectedExcluded + counts.qLocked + counts.qLockedExcluded > 0;
  return /*#__PURE__*/React.createElement(Popover, {
    open: open,
    onClose: popoverClose,
    anchorEl: alignTo.current,
    anchorOrigin: {
      vertical: 'bottom',
      horizontal: 'center'
    },
    transformOrigin: {
      vertical: 'top',
      horizontal: 'center'
    },
    PaperProps: {
      style: {
        minWidth: '250px'
      }
    }
  }, /*#__PURE__*/React.createElement(Grid, {
    container: true,
    direction: "column",
    spacing: 0
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true,
    container: true,
    style: {
      padding: theme.spacing(1)
    }
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, isLocked ? /*#__PURE__*/React.createElement(IconButton, {
    onClick: unlock,
    disabled: !isLocked
  }, /*#__PURE__*/React.createElement(Lock, {
    title: translator.get('Listbox.Unlock')
  })) : /*#__PURE__*/React.createElement(IconButton, {
    onClick: lock,
    disabled: !hasSelections
  }, /*#__PURE__*/React.createElement(Unlock, {
    title: translator.get('Listbox.Lock')
  }))), /*#__PURE__*/React.createElement(Grid, {
    item: true,
    xs: true
  }), /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(ActionsToolbar, {
    more: {
      enabled: !isLocked,
      actions: listboxSelectionToolbarItems,
      alignTo: moreAlignTo,
      popoverProps: {
        elevation: 0
      },
      popoverPaperStyle: {
        boxShadow: '0 12px 8px -8px rgba(0, 0, 0, 0.2)',
        minWidth: '250px'
      }
    },
    selections: {
      show: true,
      api: selections,
      onConfirm: popoverClose,
      onCancel: () => popoverClose(null, 'escapeKeyDown')
    }
  }))), /*#__PURE__*/React.createElement(Grid, {
    item: true,
    xs: true
  }, /*#__PURE__*/React.createElement("div", {
    ref: moreAlignTo
  }), /*#__PURE__*/React.createElement(ListBoxSearch, {
    model: model
  }), /*#__PURE__*/React.createElement(ListBox, {
    model: model,
    selections: selections,
    direction: "ltr"
  }))));
}

const useStyles$7 = makeStyles(theme => ({
  item: {
    backgroundColor: theme.palette.background.paper,
    position: 'relative',
    cursor: 'pointer',
    padding: '4px',
    '&:hover': {
      backgroundColor: theme.palette.action.hover
    }
  }
}));
function OneField(_ref) {
  let {
    field,
    api,
    stateIx = 0,
    skipHandleShowListBoxPopover = false,
    moreAlignTo = null,
    onClose = () => {}
  } = _ref;
  const {
    translator
  } = useContext(InstanceContext);
  const alignTo = moreAlignTo || useRef();
  const theme = useTheme$1();
  const [showListBoxPopover, setShowListBoxPopover] = useState$1(false);
  const classes = useStyles$7();

  const handleShowListBoxPopover = e => {
    if (e.currentTarget.contains(e.target)) {
      // because click in popover will propagate to parent
      setShowListBoxPopover(!showListBoxPopover);
    }
  };

  const handleCloseShowListBoxPopover = () => {
    setShowListBoxPopover(false);
    onClose();
  };

  const selection = field.selections[stateIx];

  if (typeof selection.qTotal === 'undefined') {
    selection.qTotal = 0;
  }

  const counts = selection.qStateCounts || {
    qSelected: 0,
    qLocked: 0,
    qExcluded: 0,
    qLockedExcluded: 0,
    qSelectedExcluded: 0,
    qAlternative: 0
  };
  const green = (counts.qSelected + counts.qLocked) / selection.qTotal;
  const white = counts.qAlternative / selection.qTotal;
  const grey = (counts.qExcluded + counts.qLockedExcluded + counts.qSelectedExcluded) / selection.qTotal;
  const numSelected = counts.qSelected + counts.qSelectedExcluded + counts.qLocked + counts.qLockedExcluded; // Maintain modal state in app selections

  const noSegments = numSelected === 0 && selection.qTotal === 0;
  let label = '';

  if (selection.qTotal === numSelected && selection.qTotal > 1) {
    label = translator.get('CurrentSelections.All');
  } else if (numSelected > 1 && selection.qTotal) {
    label = translator.get('CurrentSelections.Of', [numSelected, selection.qTotal]);
  } else if (selection.qSelectedFieldSelectionInfo) {
    label = selection.qSelectedFieldSelectionInfo.map(v => v.qName).join(', ');
  }

  if (field.states[stateIx] !== '$') {
    label = "".concat(field.states[stateIx], ": ").concat(label);
  }

  const segments = [{
    color: theme.palette.selected.main,
    ratio: green
  }, {
    color: theme.palette.selected.alternative,
    ratio: white
  }, {
    color: theme.palette.selected.excluded,
    ratio: grey
  }];
  segments.forEach((s, i) => {
    s.offset = i ? segments[i - 1].offset + segments[i - 1].ratio : 0; // eslint-disable-line
  });
  let Header = null;
  let Icon = null;
  let SegmentsIndicator = null;
  let Component = null;

  if (!moreAlignTo) {
    Header = /*#__PURE__*/React.createElement(Grid, {
      item: true,
      xs: true,
      style: {
        minWidth: 0,
        flexGrow: 1,
        opacity: selection.qLocked ? '0.3' : ''
      }
    }, /*#__PURE__*/React.createElement(Typography, {
      noWrap: true,
      style: {
        fontSize: '12px',
        lineHeight: '16px',
        fontWeight: 600
      }
    }, selection.qField), /*#__PURE__*/React.createElement(Typography, {
      noWrap: true,
      style: {
        fontSize: '12px',
        opacity: 0.55,
        lineHeight: '16px'
      }
    }, label));

    if (selection.qLocked) {
      Icon = /*#__PURE__*/React.createElement(Grid, {
        item: true
      }, /*#__PURE__*/React.createElement(IconButton, null, /*#__PURE__*/React.createElement(Lock, null)));
    } else if (!selection.qOneAndOnlyOne) {
      Icon = /*#__PURE__*/React.createElement(Grid, {
        item: true
      }, /*#__PURE__*/React.createElement(IconButton, {
        title: translator.get('Selection.Clear'),
        onClick: e => {
          e.stopPropagation();
          api.clearField(selection.qField, field.states[stateIx]);
        }
      }, /*#__PURE__*/React.createElement(Remove, null)));
    }

    SegmentsIndicator = /*#__PURE__*/React.createElement("div", {
      style: {
        height: '4px',
        position: 'absolute',
        bottom: '0',
        left: '0',
        width: '100%'
      }
    }, noSegments === false && segments.map(s => /*#__PURE__*/React.createElement("div", {
      key: s.color,
      style: {
        position: 'absolute',
        background: s.color,
        height: '100%',
        top: 0,
        width: "".concat(s.ratio * 100, "%"),
        left: "".concat(s.offset * 100, "%")
      }
    })));
    Component = /*#__PURE__*/React.createElement(Grid, {
      container: true,
      spacing: 0,
      ref: alignTo,
      className: classes.item,
      onClick: skipHandleShowListBoxPopover === false && handleShowListBoxPopover || null
    }, Header, Icon, SegmentsIndicator, showListBoxPopover && /*#__PURE__*/React.createElement(ListBoxPopover, {
      alignTo: alignTo,
      show: showListBoxPopover,
      close: handleCloseShowListBoxPopover,
      app: api.model,
      fieldName: selection.qField,
      stateName: field.states[stateIx]
    }));
  }

  return moreAlignTo ? /*#__PURE__*/React.createElement(ListBoxPopover, {
    alignTo: alignTo,
    show: true,
    close: handleCloseShowListBoxPopover,
    app: api.model,
    fieldName: selection.qField,
    stateName: field.states[stateIx]
  }) : Component;
}

const downArrow = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M8,9 L12.5,4.5 L14,6 L9.5,10.5 L8,12 L2,6 L3.5,4.5 L8,9 Z'
    }
  }]
});

var DownArrow = (props => SvgIcon(downArrow(props)));

const useStyles$6 = makeStyles(theme => ({
  item: {
    backgroundColor: theme.palette.background.paper,
    position: 'relative',
    cursor: 'pointer',
    padding: '4px',
    '&:hover': {
      backgroundColor: theme.palette.action.hover
    },
    height: '100%',
    alignItems: 'center'
  },
  badge: {
    padding: theme.spacing(0, 1)
  }
}));
function MultiState(_ref) {
  let {
    field,
    api,
    moreAlignTo = null,
    onClose = () => {}
  } = _ref;
  const classes = useStyles$6(); // If originated from the `more` item show fields directly

  const [showFields, setShowFields] = useState$1(!!moreAlignTo);
  const [showStateIx, setShowStateIx] = useState$1(-1); // If originated from the `more` item align it

  const [anchorEl, setAnchorEl] = useState$1(moreAlignTo ? moreAlignTo.current : null);
  const alignTo = moreAlignTo || useRef();
  const {
    translator
  } = useContext(InstanceContext);
  const clearAllStates = translator.get('Selection.ClearAllStates');

  const handleShowFields = e => {
    if (e.currentTarget.contains(e.target)) {
      // because click in popover will propagate to parent
      setAnchorEl(e.currentTarget);
      alignTo.current = e.currentTarget;
      setShowFields(!showFields);
    }
  };

  const handleCloseShowFields = () => {
    setShowFields(false);
    onClose();
  };

  const handleShowState = (e, ix) => {
    e.stopPropagation();
    setShowFields(false);
    setShowStateIx(ix);
  };

  const handleCloseShowState = () => {
    setShowStateIx(-1);
    onClose();
  };

  const handleClearAllStates = () => {
    field.states.forEach(s => api.clearField(field.name, s));
  };

  let Header = null;

  if (!moreAlignTo) {
    Header = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Grid, {
      item: true,
      xs: true,
      zeroMinWidth: true
    }, /*#__PURE__*/React.createElement(Badge, {
      className: classes.badge,
      color: "secondary",
      badgeContent: field.states.length
    }, /*#__PURE__*/React.createElement(Typography, {
      component: "span",
      noWrap: true,
      style: {
        fontSize: '12px',
        lineHeight: '16px',
        fontWeight: 600
      }
    }, field.name))), /*#__PURE__*/React.createElement(Grid, {
      item: true
    }, /*#__PURE__*/React.createElement("div", {
      style: {
        width: '12px'
      }
    })), /*#__PURE__*/React.createElement(Grid, {
      item: true
    }, /*#__PURE__*/React.createElement(IconButton, null, /*#__PURE__*/React.createElement(DownArrow, null))));
  }

  const Fields = /*#__PURE__*/React.createElement(List, {
    dense: true
  }, /*#__PURE__*/React.createElement(ListItem, {
    title: clearAllStates,
    onClick: handleClearAllStates
  }, /*#__PURE__*/React.createElement(Button, {
    variant: "contained",
    fullWidth: true
  }, clearAllStates)), field.states.map((s, ix) =>
  /*#__PURE__*/
  // eslint-disable-next-line react/no-array-index-key
  React.createElement(ListItem, {
    key: ix,
    title: field.name,
    onClick: e => handleShowState(e, ix)
  }, /*#__PURE__*/React.createElement(Box, {
    border: 1,
    width: "100%",
    borderRadius: "borderRadius",
    borderColor: "divider"
  }, /*#__PURE__*/React.createElement(OneField, {
    field: field,
    api: api,
    stateIx: ix,
    skipHandleShowListBoxPopover: true
  })))));
  const PopoverFields = /*#__PURE__*/React.createElement(Popover, {
    open: showFields,
    onClose: handleCloseShowFields,
    anchorEl: anchorEl,
    anchorOrigin: {
      vertical: 'bottom',
      horizontal: 'center'
    },
    transformOrigin: {
      vertical: 'top',
      horizontal: 'center'
    },
    PaperProps: {
      style: {
        minWidth: '200px',
        width: '200px',
        pointerEvents: 'auto'
      }
    }
  }, Fields);
  const Component = moreAlignTo ? PopoverFields : /*#__PURE__*/React.createElement(Grid, {
    container: true,
    spacing: 0,
    className: classes.item,
    onClick: handleShowFields
  }, Header, showFields && PopoverFields, showStateIx > -1 && /*#__PURE__*/React.createElement(ListBoxPopover, {
    alignTo: alignTo,
    show: showStateIx > -1,
    close: handleCloseShowState,
    app: api.model,
    fieldName: field.selections[showStateIx].qField,
    stateName: field.states[showStateIx]
  }));
  return moreAlignTo && showStateIx > -1 ? /*#__PURE__*/React.createElement(ListBoxPopover, {
    alignTo: alignTo,
    show: showStateIx > -1,
    close: handleCloseShowState,
    app: api.model,
    fieldName: field.selections[showStateIx].qField,
    stateName: field.states[showStateIx]
  }) : Component;
}

const useStyles$5 = makeStyles(theme => ({
  item: {
    backgroundColor: theme.palette.background.paper,
    position: 'relative',
    cursor: 'pointer',
    padding: '4px',
    '&:hover': {
      backgroundColor: theme.palette.action.hover
    },
    height: '100%',
    alignItems: 'center'
  },
  badge: {
    padding: theme.spacing(0, 1)
  }
}));
function More(_ref) {
  let {
    items = [],
    api
  } = _ref;
  const classes = useStyles$5();
  const theme = useTheme$1();
  const [showMoreItems, setShowMoreItems] = useState$1(false);
  const [showItemIx, setShowItemIx] = useState$1(-1);
  const [anchorEl, setAnchorEl] = useState$1(null);
  const alignTo = useRef();

  const handleShowMoreItems = e => {
    if (e.currentTarget.contains(e.target)) {
      // because click in popover will propagate to parent
      setAnchorEl(e.currentTarget);
      alignTo.current = e.currentTarget;
      setShowMoreItems(!showMoreItems);
    }
  };

  const handleCloseShowMoreItem = () => {
    setShowMoreItems(false);
  };

  const handleShowItem = (e, ix) => {
    e.stopPropagation();
    setShowMoreItems(false);
    setShowItemIx(ix);
  };

  const handleCloseShowItem = () => {
    setShowItemIx(-1);
  };

  let CurrentItem = null;

  if (showItemIx > -1) {
    CurrentItem = items[showItemIx].states.length > 1 ? /*#__PURE__*/React.createElement(MultiState, {
      field: items[showItemIx],
      api: api,
      moreAlignTo: alignTo,
      onClose: handleCloseShowItem
    }) : /*#__PURE__*/React.createElement(OneField, {
      field: items[showItemIx],
      api: api,
      skipHandleShowListBoxPopover: true,
      moreAlignTo: alignTo,
      onClose: handleCloseShowItem
    });
  }

  return /*#__PURE__*/React.createElement(Grid, {
    container: true,
    spacing: 0,
    className: classes.item,
    onClick: handleShowMoreItems
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(Box, {
    borderRadius: theme.shape.borderRadius,
    style: {
      padding: '4px 8px 4px 8px',
      backgroundColor: theme.palette.selected.main,
      color: theme.palette.selected.mainContrastText
    }
  }, /*#__PURE__*/React.createElement(Typography, {
    noWrap: true,
    style: {
      fontSize: '12px',
      lineHeight: '16px',
      fontWeight: 600
    },
    color: "inherit"
  }, "+", items.length))), /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(IconButton, null, /*#__PURE__*/React.createElement(DownArrow, null))), showMoreItems && /*#__PURE__*/React.createElement(Popover, {
    open: showMoreItems,
    onClose: handleCloseShowMoreItem,
    anchorEl: anchorEl,
    anchorOrigin: {
      vertical: 'bottom',
      horizontal: 'center'
    },
    transformOrigin: {
      vertical: 'top',
      horizontal: 'center'
    },
    PaperProps: {
      style: {
        minWidth: '200px',
        width: '200px',
        pointerEvents: 'auto'
      }
    }
  }, /*#__PURE__*/React.createElement(List, {
    dense: true
  }, items.map((s, ix) =>
  /*#__PURE__*/
  // eslint-disable-next-line react/no-array-index-key
  React.createElement(ListItem, {
    key: ix,
    title: s.name,
    onClick: e => handleShowItem(e, ix)
  }, /*#__PURE__*/React.createElement(Box, {
    border: 1,
    width: "100%",
    borderRadius: "borderRadius",
    borderColor: "divider"
  }, s.states.length > 1 ? /*#__PURE__*/React.createElement(MultiState, {
    field: s,
    api: api
  }) : /*#__PURE__*/React.createElement(OneField, {
    field: s,
    api: api
  })))))), CurrentItem);
}

const MIN_WIDTH$1 = 120;
const MIN_WIDTH_MORE = 72;

function collect(qSelectionObject, fields) {
  let state = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '$';
  qSelectionObject.qSelections.forEach(selection => {
    const name = selection.qField;
    const field = fields[name] = fields[name] || {
      name,
      states: [],
      selections: []
    }; // eslint-disable-line

    if (field.states.indexOf(state) === -1) {
      field.states.push(state);
      field.selections.push(selection);
    }
  });
}

function getItems(layout) {
  if (!layout) {
    return [];
  }

  const fields = {};

  if (layout.qSelectionObject) {
    collect(layout.qSelectionObject, fields);
  }

  if (layout.alternateStates) {
    layout.alternateStates.forEach(s => collect(s.qSelectionObject, fields, s.stateName));
  }

  return Object.keys(fields).map(key => fields[key]);
}

function SelectedFields(_ref) {
  let {
    api,
    app
  } = _ref;
  const theme = useTheme$1();
  const [currentSelectionsModel] = useCurrentSelectionsModel(app);
  const [layout] = useLayout$1(currentSelectionsModel);
  const [state, setState] = useState$1({
    items: [],
    more: []
  });
  const [modalObjectStore] = useModalObjectStore();
  const [containerRef, containerRect] = useRect$1();
  const [maxItems, setMaxItems] = useState$1(0);

  const isInListboxPopover = () => {
    const object = modalObjectStore.get(app.id);
    return object && object.genericType === 'njsListbox';
  };

  useEffect$1(() => {
    if (!containerRect) return;
    const {
      width
    } = containerRect;
    const maxWidth = Math.floor(width) - MIN_WIDTH_MORE;
    const items = Math.floor(maxWidth / MIN_WIDTH$1);
    setMaxItems(items);
  }, [containerRect]);
  useEffect$1(() => {
    if (!app || !currentSelectionsModel || !layout || !maxItems) {
      return;
    }

    const items = getItems(layout);
    setState(currState => {
      const newItems = items; // Maintain modal state in app selections

      if (isInListboxPopover() && newItems.length + 1 === currState.items.length) {
        const lastDeselectedField = currState.items.filter(f1 => newItems.some(f2 => f1.name === f2.name) === false)[0];
        const {
          qField
        } = lastDeselectedField.selections[0];
        lastDeselectedField.selections = [{
          qField
        }];
        const wasIx = currState.items.indexOf(lastDeselectedField);
        newItems.splice(wasIx, 0, lastDeselectedField);
      }

      let newMoreItems = [];

      if (maxItems < newItems.length) {
        newMoreItems = newItems.splice(maxItems - newItems.length);
      }

      return {
        items: newItems,
        more: newMoreItems
      };
    });
  }, [app, currentSelectionsModel, layout, api.isInModal(), maxItems]);
  return /*#__PURE__*/React.createElement(Grid, {
    ref: containerRef,
    container: true,
    spacing: 0,
    wrap: "nowrap",
    style: {
      height: '100%'
    }
  }, state.items.map(s => /*#__PURE__*/React.createElement(Grid, {
    item: true,
    key: "".concat(s.states.join('::'), "::").concat(s.name),
    style: {
      position: 'relative',
      maxWidth: '240px',
      minWidth: "".concat(MIN_WIDTH$1, "px"),
      background: theme.palette.background.paper,
      borderRight: "1px solid ".concat(theme.palette.divider)
    }
  }, s.states.length > 1 ? /*#__PURE__*/React.createElement(MultiState, {
    field: s,
    api: api
  }) : /*#__PURE__*/React.createElement(OneField, {
    field: s,
    api: api
  }))), state.more.length > 0 && /*#__PURE__*/React.createElement(Grid, {
    item: true,
    style: {
      position: 'relative',
      maxWidth: '98px',
      minWidth: "".concat(MIN_WIDTH_MORE, "px"),
      background: theme.palette.background.paper,
      borderRight: "1px solid ".concat(theme.palette.divider)
    }
  }, /*#__PURE__*/React.createElement(More, {
    items: state.more,
    api: api
  })));
}

const selectionsBack = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M10,15.5 C10,15.7761424 9.77614237,16 9.5,16 L6.5,16 C6.22385763,16 6,15.7761424 6,15.5 C6,15.2238576 6.22385763,15 6.5,15 L9.5,15 C9.77614237,15 10,15.2238576 10,15.5 Z M15,13.5 C15,13.2238576 15.2238576,13 15.5,13 C15.7761424,13 16,13.2238576 16,13.5 L16,15 C16,15.5522847 15.5522847,16 15,16 L13.5,16 C13.2238576,16 13,15.7761424 13,15.5 C13,15.2238576 13.2238576,15 13.5,15 L14.5,15 C14.7761424,15 15,14.7761424 15,14.5 L15,13.5 Z M15,6.5 C15,6.22385763 15.2238576,6 15.5,6 C15.7761424,6 16,6.22385763 16,6.5 L16,9.5 C16,9.77614237 15.7761424,10 15.5,10 C15.2238576,10 15,9.77614237 15,9.5 L15,6.5 Z M16,2.5 C16,2.77614237 15.7761424,3 15.5,3 C15.2238576,3 15,2.77614237 15,2.5 L15,1.5 C15,1.22385763 14.7761424,1 14.5,1 L13.5,1 C13.2238576,1 13,0.776142375 13,0.5 C13,0.223857625 13.2238576,-5.07265313e-17 13.5,0 L15,0 C15.5522847,1.01453063e-16 16,0.44771525 16,1 L16,2.5 Z M10,0.5 C10,0.776142375 9.77614237,1 9.5,1 L6.5,1 C6.22385763,1 6,0.776142375 6,0.5 C6,0.223857625 6.22385763,-5.07265313e-17 6.5,0 L9.5,0 C9.77614237,5.07265313e-17 10,0.223857625 10,0.5 Z M1,2.5 C1,2.77614237 0.776142375,3 0.5,3 C0.223857625,3 5.18696197e-13,2.77614237 5.18696197e-13,2.5 L5.18696197e-13,1 C5.18696197e-13,0.44771525 0.44771525,-1.01453063e-16 1,0 L2.5,0 C2.77614237,5.07265313e-17 3,0.223857625 3,0.5 C3,0.776142375 2.77614237,1 2.5,1 L1.5,1 C1.22385763,1 1,1.22385763 1,1.5 L1,2.5 Z M1,13.5 L1,14.5 C1,14.7761424 1.22385763,15 1.5,15 L2.5,15 C2.77614237,15 3,15.2238576 3,15.5 C3,15.7761424 2.77614237,16 2.5,16 L1,16 C0.44771525,16 5.18696197e-13,15.5522847 5.18696197e-13,15 L5.18696197e-13,13.5 C5.18696197e-13,13.2238576 0.223857625,13 0.5,13 C0.776142375,13 1,13.2238576 1,13.5 Z M4,7 C7.49095643,7 10,10.1337595 10,12.1872632 C10,12.1872632 8.16051135,9.86624054 4,10 L4,12 C4,12 2.66666667,10.8333333 -1.0658141e-14,8.5 C-2.59348099e-13,8.5 1.33333333,7.33333333 4,5 C4,5 4,5.66666667 4,7 Z'
    }
  }]
});

var SelectionsBack = (props => SvgIcon(selectionsBack(props)));

const selectionsForward = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M6,15.5 L6,15.5 C6,15.2238576 6.22385763,15 6.5,15 L9.5,15 C9.77614237,15 10,15.2238576 10,15.5 L10,15.5 C10,15.7761424 9.77614237,16 9.5,16 L6.5,16 C6.22385763,16 6,15.7761424 6,15.5 Z M1,13.5 L1,14.5 C1,14.7761424 1.22385763,15 1.5,15 L2.5,15 C2.77614237,15 3,15.2238576 3,15.5 L3,15.5 C3,15.7761424 2.77614237,16 2.5,16 L1,16 C0.44771525,16 6.76353751e-17,15.5522847 0,15 L0,13.5 C-3.38176876e-17,13.2238576 0.223857625,13 0.5,13 L0.5,13 C0.776142375,13 1,13.2238576 1,13.5 Z M1,6.5 L1,9.5 C1,9.77614237 0.776142375,10 0.5,10 L0.5,10 C0.223857625,10 3.38176876e-17,9.77614237 0,9.5 L0,6.5 C-3.38176876e-17,6.22385763 0.223857625,6 0.5,6 L0.5,6 C0.776142375,6 1,6.22385763 1,6.5 Z M0,2.5 L0,1 C-6.76353751e-17,0.44771525 0.44771525,1.01453063e-16 1,0 L2.5,0 C2.77614237,-5.07265313e-17 3,0.223857625 3,0.5 L3,0.5 C3,0.776142375 2.77614237,1 2.5,1 L1.5,1 C1.22385763,1 1,1.22385763 1,1.5 L1,2.5 C1,2.77614237 0.776142375,3 0.5,3 L0.5,3 C0.223857625,3 3.38176876e-17,2.77614237 0,2.5 Z M6,0.5 L6,0.5 C6,0.223857625 6.22385763,5.07265313e-17 6.5,0 L9.5,0 C9.77614237,-5.07265313e-17 10,0.223857625 10,0.5 L10,0.5 C10,0.776142375 9.77614237,1 9.5,1 L6.5,1 C6.22385763,1 6,0.776142375 6,0.5 Z M15,2.5 L15,1.5 C15,1.22385763 14.7761424,1 14.5,1 L13.5,1 C13.2238576,1 13,0.776142375 13,0.5 L13,0.5 C13,0.223857625 13.2238576,5.07265313e-17 13.5,0 L15,0 C15.5522847,-1.01453063e-16 16,0.44771525 16,1 L16,2.5 C16,2.77614237 15.7761424,3 15.5,3 L15.5,3 C15.2238576,3 15,2.77614237 15,2.5 Z M15,13.5 C15,13.2238576 15.2238576,13 15.5,13 C15.7761424,13 16,13.2238576 16,13.5 L16,15 C16,15.5522847 15.5522847,16 15,16 L13.5,16 C13.2238576,16 13,15.7761424 13,15.5 C13,15.2238576 13.2238576,15 13.5,15 L14.5,15 C14.7761424,15 15,14.7761424 15,14.5 L15,13.5 Z M12,7 C12,5.66666667 12,5 12,5 C14.6666667,7.33333333 16,8.5 16,8.5 C13.3333333,10.8333333 12,12 12,12 L12,10 C7.83948865,9.86624054 6,12.1872632 6,12.1872632 C6,10.1337595 8.50904357,7 12,7 Z'
    }
  }]
});

var SelectionsForward = (props => SvgIcon(selectionsForward(props)));

function Nav(_ref) {
  let {
    api,
    app
  } = _ref;
  const {
    translator
  } = useContext(InstanceContext);
  const [navState] = useAppSelectionsNavigation(app);
  return /*#__PURE__*/React.createElement(Grid, {
    container: true,
    wrap: "nowrap",
    style: {
      height: '100%',
      alignItems: 'center',
      padding: '0 8px'
    }
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(IconButton, {
    style: {
      marginRight: '8px'
    },
    disabled: !navState || !navState.canGoBack,
    title: translator.get('Navigate.Back'),
    onClick: () => api.back()
  }, /*#__PURE__*/React.createElement(SelectionsBack, null))), /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(IconButton, {
    style: {
      marginRight: '8px'
    },
    disabled: !navState || !navState.canGoForward,
    title: translator.get('Navigate.Forward'),
    onClick: () => api.forward()
  }, /*#__PURE__*/React.createElement(SelectionsForward, null))), /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(IconButton, {
    disabled: !navState || !navState.canClear,
    title: translator.get('Selection.ClearAll'),
    onClick: () => api.clear()
  }, /*#__PURE__*/React.createElement(ClearSelections, null))));
}

function AppSelections(_ref) {
  let {
    app
  } = _ref;
  const theme = useTheme$1();
  const [appSelections] = useAppSelections(app);
  if (!appSelections) return null;
  return /*#__PURE__*/React.createElement(Grid, {
    container: true,
    spacing: 0,
    wrap: "nowrap",
    style: {
      backgroundColor: theme.palette.background.paper,
      minHeight: '40px'
    }
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true,
    style: {
      borderRight: "1px solid ".concat(theme.palette.divider)
    }
  }, /*#__PURE__*/React.createElement(Nav, {
    api: appSelections,
    app: app
  })), /*#__PURE__*/React.createElement(Grid, {
    item: true,
    xs: true,
    style: {
      backgroundColor: theme.palette.background.darker,
      overflow: 'hidden'
    }
  }, /*#__PURE__*/React.createElement(SelectedFields, {
    api: appSelections,
    app: app
  })));
}
function mount(_ref2) {
  let {
    element,
    app
  } = _ref2;
  return ReactDOM.createPortal( /*#__PURE__*/React.createElement(AppSelections, {
    app: app
  }), element);
}

var classCallCheck = function (instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
};

var createClass = function () {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  return function (Constructor, protoProps, staticProps) {
    if (protoProps) defineProperties(Constructor.prototype, protoProps);
    if (staticProps) defineProperties(Constructor, staticProps);
    return Constructor;
  };
}();

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var inherits = function (subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  }

  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};

var possibleConstructorReturn = function (self, call) {
  if (!self) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return call && (typeof call === "object" || typeof call === "function") ? call : self;
};

var slicedToArray = function () {
  function sliceIterator(arr, i) {
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = undefined;

    try {
      for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
        _arr.push(_s.value);

        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"]) _i["return"]();
      } finally {
        if (_d) throw _e;
      }
    }

    return _arr;
  }

  return function (arr, i) {
    if (Array.isArray(arr)) {
      return arr;
    } else if (Symbol.iterator in Object(arr)) {
      return sliceIterator(arr, i);
    } else {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }
  };
}();

/**
 * Detect Element Resize.
 * https://github.com/sdecima/javascript-detect-element-resize
 * Sebastian Decima
 *
 * Forked from version 0.5.3; includes the following modifications:
 * 1) Guard against unsafe 'window' and 'document' references (to support SSR).
 * 2) Defer initialization code via a top-level function wrapper (to support SSR).
 * 3) Avoid unnecessary reflows by not measuring size for scroll events bubbling from children.
 * 4) Add nonce for style element.
 **/

// Check `document` and `window` in case of server-side rendering
var windowObject = void 0;
if (typeof window !== 'undefined') {
  windowObject = window;

  // eslint-disable-next-line no-restricted-globals
} else if (typeof self !== 'undefined') {
  // eslint-disable-next-line no-restricted-globals
  windowObject = self;
} else {
  windowObject = global;
}

var cancelFrame = null;
var requestFrame = null;

var TIMEOUT_DURATION = 20;

var clearTimeoutFn = windowObject.clearTimeout;
var setTimeoutFn = windowObject.setTimeout;

var cancelAnimationFrameFn = windowObject.cancelAnimationFrame || windowObject.mozCancelAnimationFrame || windowObject.webkitCancelAnimationFrame;

var requestAnimationFrameFn = windowObject.requestAnimationFrame || windowObject.mozRequestAnimationFrame || windowObject.webkitRequestAnimationFrame;

if (cancelAnimationFrameFn == null || requestAnimationFrameFn == null) {
  // For environments that don't support animation frame,
  // fallback to a setTimeout based approach.
  cancelFrame = clearTimeoutFn;
  requestFrame = function requestAnimationFrameViaSetTimeout(callback) {
    return setTimeoutFn(callback, TIMEOUT_DURATION);
  };
} else {
  // Counter intuitively, environments that support animation frames can be trickier.
  // Chrome's "Throttle non-visible cross-origin iframes" flag can prevent rAFs from being called.
  // In this case, we should fallback to a setTimeout() implementation.
  cancelFrame = function cancelFrame(_ref) {
    var _ref2 = slicedToArray(_ref, 2),
        animationFrameID = _ref2[0],
        timeoutID = _ref2[1];

    cancelAnimationFrameFn(animationFrameID);
    clearTimeoutFn(timeoutID);
  };
  requestFrame = function requestAnimationFrameWithSetTimeoutFallback(callback) {
    var animationFrameID = requestAnimationFrameFn(function animationFrameCallback() {
      clearTimeoutFn(timeoutID);
      callback();
    });

    var timeoutID = setTimeoutFn(function timeoutCallback() {
      cancelAnimationFrameFn(animationFrameID);
      callback();
    }, TIMEOUT_DURATION);

    return [animationFrameID, timeoutID];
  };
}

function createDetectElementResize(nonce) {
  var animationKeyframes = void 0;
  var animationName = void 0;
  var animationStartEvent = void 0;
  var animationStyle = void 0;
  var checkTriggers = void 0;
  var resetTriggers = void 0;
  var scrollListener = void 0;

  var attachEvent = typeof document !== 'undefined' && document.attachEvent;
  if (!attachEvent) {
    resetTriggers = function resetTriggers(element) {
      var triggers = element.__resizeTriggers__,
          expand = triggers.firstElementChild,
          contract = triggers.lastElementChild,
          expandChild = expand.firstElementChild;
      contract.scrollLeft = contract.scrollWidth;
      contract.scrollTop = contract.scrollHeight;
      expandChild.style.width = expand.offsetWidth + 1 + 'px';
      expandChild.style.height = expand.offsetHeight + 1 + 'px';
      expand.scrollLeft = expand.scrollWidth;
      expand.scrollTop = expand.scrollHeight;
    };

    checkTriggers = function checkTriggers(element) {
      return element.offsetWidth !== element.__resizeLast__.width || element.offsetHeight !== element.__resizeLast__.height;
    };

    scrollListener = function scrollListener(e) {
      // Don't measure (which forces) reflow for scrolls that happen inside of children!
      if (e.target.className && typeof e.target.className.indexOf === 'function' && e.target.className.indexOf('contract-trigger') < 0 && e.target.className.indexOf('expand-trigger') < 0) {
        return;
      }

      var element = this;
      resetTriggers(this);
      if (this.__resizeRAF__) {
        cancelFrame(this.__resizeRAF__);
      }
      this.__resizeRAF__ = requestFrame(function animationFrame() {
        if (checkTriggers(element)) {
          element.__resizeLast__.width = element.offsetWidth;
          element.__resizeLast__.height = element.offsetHeight;
          element.__resizeListeners__.forEach(function forEachResizeListener(fn) {
            fn.call(element, e);
          });
        }
      });
    };

    /* Detect CSS Animations support to detect element display/re-attach */
    var animation = false;
    var keyframeprefix = '';
    animationStartEvent = 'animationstart';
    var domPrefixes = 'Webkit Moz O ms'.split(' ');
    var startEvents = 'webkitAnimationStart animationstart oAnimationStart MSAnimationStart'.split(' ');
    var pfx = '';
    {
      var elm = document.createElement('fakeelement');
      if (elm.style.animationName !== undefined) {
        animation = true;
      }

      if (animation === false) {
        for (var i = 0; i < domPrefixes.length; i++) {
          if (elm.style[domPrefixes[i] + 'AnimationName'] !== undefined) {
            pfx = domPrefixes[i];
            keyframeprefix = '-' + pfx.toLowerCase() + '-';
            animationStartEvent = startEvents[i];
            animation = true;
            break;
          }
        }
      }
    }

    animationName = 'resizeanim';
    animationKeyframes = '@' + keyframeprefix + 'keyframes ' + animationName + ' { from { opacity: 0; } to { opacity: 0; } } ';
    animationStyle = keyframeprefix + 'animation: 1ms ' + animationName + '; ';
  }

  var createStyles = function createStyles(doc) {
    if (!doc.getElementById('detectElementResize')) {
      //opacity:0 works around a chrome bug https://code.google.com/p/chromium/issues/detail?id=286360
      var css = (animationKeyframes ? animationKeyframes : '') + '.resize-triggers { ' + (animationStyle ? animationStyle : '') + 'visibility: hidden; opacity: 0; } ' + '.resize-triggers, .resize-triggers > div, .contract-trigger:before { content: " "; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; z-index: -1; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }',
          head = doc.head || doc.getElementsByTagName('head')[0],
          style = doc.createElement('style');

      style.id = 'detectElementResize';
      style.type = 'text/css';

      if (nonce != null) {
        style.setAttribute('nonce', nonce);
      }

      if (style.styleSheet) {
        style.styleSheet.cssText = css;
      } else {
        style.appendChild(doc.createTextNode(css));
      }

      head.appendChild(style);
    }
  };

  var addResizeListener = function addResizeListener(element, fn) {
    if (attachEvent) {
      element.attachEvent('onresize', fn);
    } else {
      if (!element.__resizeTriggers__) {
        var doc = element.ownerDocument;
        var elementStyle = windowObject.getComputedStyle(element);
        if (elementStyle && elementStyle.position === 'static') {
          element.style.position = 'relative';
        }
        createStyles(doc);
        element.__resizeLast__ = {};
        element.__resizeListeners__ = [];
        (element.__resizeTriggers__ = doc.createElement('div')).className = 'resize-triggers';
        var expandTrigger = doc.createElement('div');
        expandTrigger.className = 'expand-trigger';
        expandTrigger.appendChild(doc.createElement('div'));
        var contractTrigger = doc.createElement('div');
        contractTrigger.className = 'contract-trigger';
        element.__resizeTriggers__.appendChild(expandTrigger);
        element.__resizeTriggers__.appendChild(contractTrigger);
        element.appendChild(element.__resizeTriggers__);
        resetTriggers(element);
        element.addEventListener('scroll', scrollListener, true);

        /* Listen for a css animation to detect element display/re-attach */
        if (animationStartEvent) {
          element.__resizeTriggers__.__animationListener__ = function animationListener(e) {
            if (e.animationName === animationName) {
              resetTriggers(element);
            }
          };
          element.__resizeTriggers__.addEventListener(animationStartEvent, element.__resizeTriggers__.__animationListener__);
        }
      }
      element.__resizeListeners__.push(fn);
    }
  };

  var removeResizeListener = function removeResizeListener(element, fn) {
    if (attachEvent) {
      element.detachEvent('onresize', fn);
    } else {
      element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1);
      if (!element.__resizeListeners__.length) {
        element.removeEventListener('scroll', scrollListener, true);
        if (element.__resizeTriggers__.__animationListener__) {
          element.__resizeTriggers__.removeEventListener(animationStartEvent, element.__resizeTriggers__.__animationListener__);
          element.__resizeTriggers__.__animationListener__ = null;
        }
        try {
          element.__resizeTriggers__ = !element.removeChild(element.__resizeTriggers__);
        } catch (e) {
          // Preact compat; see developit/preact-compat/issues/228
        }
      }
    }
  };

  return {
    addResizeListener: addResizeListener,
    removeResizeListener: removeResizeListener
  };
}

var AutoSizer = function (_React$PureComponent) {
  inherits(AutoSizer, _React$PureComponent);

  function AutoSizer() {
    var _ref;

    var _temp, _this, _ret;

    classCallCheck(this, AutoSizer);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = AutoSizer.__proto__ || Object.getPrototypeOf(AutoSizer)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      height: _this.props.defaultHeight || 0,
      width: _this.props.defaultWidth || 0
    }, _this._onResize = function () {
      var _this$props = _this.props,
          disableHeight = _this$props.disableHeight,
          disableWidth = _this$props.disableWidth,
          onResize = _this$props.onResize;


      if (_this._parentNode) {
        // Guard against AutoSizer component being removed from the DOM immediately after being added.
        // This can result in invalid style values which can result in NaN values if we don't handle them.
        // See issue #150 for more context.

        var _height = _this._parentNode.offsetHeight || 0;
        var _width = _this._parentNode.offsetWidth || 0;

        var _style = window.getComputedStyle(_this._parentNode) || {};
        var paddingLeft = parseInt(_style.paddingLeft, 10) || 0;
        var paddingRight = parseInt(_style.paddingRight, 10) || 0;
        var paddingTop = parseInt(_style.paddingTop, 10) || 0;
        var paddingBottom = parseInt(_style.paddingBottom, 10) || 0;

        var newHeight = _height - paddingTop - paddingBottom;
        var newWidth = _width - paddingLeft - paddingRight;

        if (!disableHeight && _this.state.height !== newHeight || !disableWidth && _this.state.width !== newWidth) {
          _this.setState({
            height: _height - paddingTop - paddingBottom,
            width: _width - paddingLeft - paddingRight
          });

          onResize({ height: _height, width: _width });
        }
      }
    }, _this._setRef = function (autoSizer) {
      _this._autoSizer = autoSizer;
    }, _temp), possibleConstructorReturn(_this, _ret);
  }

  createClass(AutoSizer, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var nonce = this.props.nonce;

      if (this._autoSizer && this._autoSizer.parentNode && this._autoSizer.parentNode.ownerDocument && this._autoSizer.parentNode.ownerDocument.defaultView && this._autoSizer.parentNode instanceof this._autoSizer.parentNode.ownerDocument.defaultView.HTMLElement) {
        // Delay access of parentNode until mount.
        // This handles edge-cases where the component has already been unmounted before its ref has been set,
        // As well as libraries like react-lite which have a slightly different lifecycle.
        this._parentNode = this._autoSizer.parentNode;

        // Defer requiring resize handler in order to support server-side rendering.
        // See issue #41
        this._detectElementResize = createDetectElementResize(nonce);
        this._detectElementResize.addResizeListener(this._parentNode, this._onResize);

        this._onResize();
      }
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      if (this._detectElementResize && this._parentNode) {
        this._detectElementResize.removeResizeListener(this._parentNode, this._onResize);
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          children = _props.children,
          className = _props.className,
          disableHeight = _props.disableHeight,
          disableWidth = _props.disableWidth,
          style = _props.style;
      var _state = this.state,
          height = _state.height,
          width = _state.width;

      // Outer div should not force width/height since that may prevent containers from shrinking.
      // Inner component should overflow and use calculated width/height.
      // See issue #68 for more information.

      var outerStyle = { overflow: 'visible' };
      var childParams = {};

      // Avoid rendering children before the initial measurements have been collected.
      // At best this would just be wasting cycles.
      var bailoutOnChildren = false;

      if (!disableHeight) {
        if (height === 0) {
          bailoutOnChildren = true;
        }
        outerStyle.height = 0;
        childParams.height = height;
      }

      if (!disableWidth) {
        if (width === 0) {
          bailoutOnChildren = true;
        }
        outerStyle.width = 0;
        childParams.width = width;
      }

      return createElement(
        'div',
        {
          className: className,
          ref: this._setRef,
          style: _extends({}, outerStyle, style)
        },
        !bailoutOnChildren && children(childParams)
      );
    }
  }]);
  return AutoSizer;
}(PureComponent);

AutoSizer.defaultProps = {
  onResize: function onResize() {},
  disableHeight: false,
  disableWidth: false,
  style: {}
};

/**
 * Hook that confirms selection when
 * user interact outside of passed element ref.
 */

function useConfirmUnfocus(ref, selections) {
  const [_isConfirmed, _setIsConfirmed] = useState$1(false); // Wrap state in ref to use inside eventListener callback

  const isConfirmedRef = useRef(_isConfirmed);

  const setIsConfirmed = c => {
    isConfirmedRef.current = c;

    _setIsConfirmed(c);
  };

  useEffect$1(() => {
    const handleEvent = event => {
      const interactInside = ref.current && ref.current.contains(event.target);
      const isConfirmed = isConfirmedRef.current;

      if (!interactInside && !isConfirmed) {
        selections && selections.confirm.call(selections);
        setIsConfirmed(true);
      } else if (interactInside) {
        setIsConfirmed(false);
      }
    };

    document.addEventListener('mousedown', handleEvent);
    document.addEventListener('keydown', handleEvent);
    return () => {
      document.removeEventListener('mousedown', handleEvent);
      document.removeEventListener('keydown', handleEvent);
    };
  }, [ref, selections]);
}

const useStyles$4 = makeStyles(() => ({
  listBoxHeader: {
    alignSelf: 'center',
    display: 'inline-flex'
  }
}));
function ListBoxInline(_ref) {
  let {
    app,
    fieldIdentifier,
    stateName = '$',
    options = {},
    fieldDef
  } = _ref;
  const {
    title,
    direction,
    listLayout,
    search = true,
    focusSearch = false,
    toolbar = true,
    rangeSelect = true,
    checkboxes = false,
    properties = {},
    sessionModel = undefined,
    selectionsApi = undefined,
    update = undefined,
    fetchStart = undefined,
    dense = false,
    selectDisabled = () => false,
    showGray = true,
    sortByState = 1,
    scrollState = undefined,
    setCount = undefined
  } = options;
  let {
    frequencyMode,
    histogram = false
  } = options;

  if (fieldDef && fieldDef.failedToFetchFieldDef) {
    histogram = false;
    frequencyMode = 'N';
  }

  switch (true) {
    case ['none', 'N', 'NX_FREQUENCY_NONE'].includes(frequencyMode):
      frequencyMode = 'N';
      break;

    case ['value', 'V', 'NX_FREQUENCY_VALUE', 'default'].includes(frequencyMode):
      frequencyMode = 'V';
      break;

    case ['percent', 'P', 'NX_FREQUENCY_PERCENT'].includes(frequencyMode):
      frequencyMode = 'P';
      break;

    case ['relative', 'R', 'NX_FREQUENCY_RELATIVE'].includes(frequencyMode):
      frequencyMode = 'R';
      break;

    default:
      frequencyMode = 'N';
      break;
  }

  const getListdefFrequencyMode = () => histogram && frequencyMode === 'N' ? 'V' : frequencyMode; // Hook that will trigger update when used in useEffects.
  // Modified from: https://medium.com/@teh_builder/ref-objects-inside-useeffect-hooks-eb7c15198780


  const useRefWithCallback = () => {
    const [ref, setInternalRef] = useState$1({});
    const setRef = useCallback(node => {
      setInternalRef({
        current: node
      });
    }, [setInternalRef]);
    return [ref, setRef];
  };

  const listdef = _objectSpread2({
    qInfo: {
      qType: 'njsListbox'
    },
    qListObjectDef: {
      qStateName: stateName,
      qShowAlternatives: true,
      qFrequencyMode: getListdefFrequencyMode(),
      qInitialDataFetch: [{
        qTop: 0,
        qLeft: 0,
        qWidth: 0,
        qHeight: 0
      }],
      qDef: {
        qSortCriterias: [{
          qSortByState: sortByState,
          qSortByAscii: 1,
          qSortByNumeric: 1,
          qSortByLoadOrder: 1
        }]
      }
    },
    title
  }, properties); // Something something lib dimension


  let fieldName;

  if (fieldIdentifier.qLibraryId) {
    listdef.qListObjectDef.qLibraryId = fieldIdentifier.qLibraryId;
    fieldName = fieldIdentifier.qLibraryId;
  } else {
    listdef.qListObjectDef.qDef.qFieldDefs = [fieldIdentifier];
    fieldName = fieldIdentifier;
  }

  if (frequencyMode !== 'N' || histogram) {
    const field = fieldIdentifier.qLibraryId ? fieldDef : fieldName;
    listdef.frequencyMax = {
      qValueExpression: "Max(AGGR(Count([".concat(field, "]), [").concat(field, "]))")
    };
  }

  let [model] = useSessionModel(listdef, sessionModel ? null : app, fieldName, stateName);

  if (sessionModel) {
    model = sessionModel;
  }

  let selections = useObjectSelections(selectionsApi ? {} : app, model)[0];

  if (selectionsApi) {
    selections = selectionsApi;
  }

  const theme = useTheme$1();
  const classes = useStyles$4();
  const lock = useCallback(() => {
    model.lock('/qListObjectDef');
  }, [model]);
  const unlock = useCallback(() => {
    model.unlock('/qListObjectDef');
  }, [model]);
  const {
    translator,
    keyboardNavigation
  } = useContext(InstanceContext);
  const moreAlignTo = useRef();
  const [searchContainer, searchContainerRef] = useRefWithCallback();
  const [layout] = useLayout$1(model);
  const [showToolbar, setShowToolbar] = useState$1(false);
  const [showSearch, setShowSearch] = useState$1(false);
  const [keyboardActive, setKeyboardActive] = useState$1(false);
  const handleKeyDown = getListboxInlineKeyboardNavigation({
    setKeyboardActive
  }); // Expose the keyboard flags in the same way as the keyboard hook does.

  const keyboard = {
    enabled: keyboardNavigation,
    // this will be static until we can access the useKeyboard hook
    active: keyboardActive
  };
  useEffect$1(() => {
    const show = () => setShowToolbar(true);

    const hide = () => setShowToolbar(false);

    if (selections) {
      if (!selections.isModal(model)) {
        selections.on('deactivated', hide);
        selections.on('activated', show);
      }
    }

    return () => {
      if (selections) {
        selections.removeListener('deactivated', show);
        selections.removeListener('activated', hide);
      }
    };
  }, [selections]);
  useEffect$1(() => {
    if (selections) {
      setShowToolbar(selections.isActive());
    }
  }, [selections]);
  const listBoxRef = useRef(null);
  useConfirmUnfocus(listBoxRef, selections);
  useEffect$1(() => {
    if (!searchContainer || !searchContainer.current) {
      return;
    } // Focus search field on toggle-show or when focusSearch is true.


    if (search && focusSearch || search === 'toggle' && showSearch) {
      const input = searchContainer.current.querySelector('input');
      input && input.focus();
    }
  }, [searchContainer && searchContainer.current, showSearch, search, focusSearch]);

  if (!model || !layout || !translator) {
    return null;
  }

  const isLocked = layout.qListObject.qDimensionInfo.qLocked === true;
  const listboxSelectionToolbarItems = toolbar ? createListboxSelectionToolbar({
    layout,
    model,
    translator
  }) : [];
  const counts = layout.qListObject.qDimensionInfo.qStateCounts;
  const hasSelections = counts.qSelected + counts.qSelectedExcluded + counts.qLocked + counts.qLockedExcluded > 0;
  const searchVisible = (search === true || search === 'toggle' && showSearch) && !selectDisabled();
  const minHeight = 49 + (searchVisible ? 40 : 0) + 49;

  const onShowSearch = () => {
    const newValue = !showSearch;
    setShowSearch(newValue);
  };

  const getSearchOrUnlock = () => search === 'toggle' && !hasSelections ? /*#__PURE__*/React.createElement(IconButton, {
    onClick: onShowSearch,
    tabIndex: -1,
    title: translator.get('Listbox.Search')
  }, /*#__PURE__*/React.createElement(SearchIcon, null)) : /*#__PURE__*/React.createElement(IconButton, {
    onClick: lock,
    tabIndex: -1,
    disabled: !hasSelections
  }, /*#__PURE__*/React.createElement(Unlock, null));

  return /*#__PURE__*/React.createElement(Grid, {
    container: true,
    tabIndex: keyboard.enabled && !keyboard.active ? 0 : -1,
    direction: "column",
    spacing: 0,
    style: {
      height: '100%',
      minHeight: "".concat(minHeight, "px")
    },
    onKeyDown: handleKeyDown,
    ref: listBoxRef
  }, toolbar && /*#__PURE__*/React.createElement(Grid, {
    item: true,
    container: true,
    style: {
      padding: theme.spacing(1)
    }
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, isLocked ? /*#__PURE__*/React.createElement(IconButton, {
    tabIndex: -1,
    onClick: unlock,
    disabled: !isLocked
  }, /*#__PURE__*/React.createElement(Lock, {
    title: translator.get('Listbox.Unlock')
  })) : getSearchOrUnlock()), /*#__PURE__*/React.createElement(Grid, {
    item: true,
    className: classes.listBoxHeader
  }, /*#__PURE__*/React.createElement(Typography, {
    variant: "h6",
    noWrap: true
  }, layout.title || layout.qListObject.qDimensionInfo.qFallbackTitle)), /*#__PURE__*/React.createElement(Grid, {
    item: true,
    xs: true
  }), /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(ActionsToolbar, {
    more: {
      enabled: !isLocked,
      actions: listboxSelectionToolbarItems,
      alignTo: moreAlignTo,
      popoverProps: {
        elevation: 0
      },
      popoverPaperStyle: {
        boxShadow: '0 12px 8px -8px rgba(0, 0, 0, 0.2)',
        minWidth: '250px'
      }
    },
    selections: {
      show: showToolbar,
      api: selections,
      onConfirm: () => {},
      onCancel: () => {}
    }
  }))), searchVisible && /*#__PURE__*/React.createElement(Grid, {
    item: true,
    ref: searchContainerRef
  }, /*#__PURE__*/React.createElement(ListBoxSearch, {
    model: model,
    dense: dense,
    keyboard: keyboard
  })), /*#__PURE__*/React.createElement(Grid, {
    item: true,
    xs: true
  }, /*#__PURE__*/React.createElement("div", {
    ref: moreAlignTo
  }), /*#__PURE__*/React.createElement(AutoSizer, null, _ref2 => {
    let {
      height,
      width
    } = _ref2;
    return /*#__PURE__*/React.createElement(ListBox, {
      model: model,
      selections: selections,
      direction: direction,
      listLayout: listLayout,
      frequencyMode: frequencyMode,
      histogram: histogram,
      rangeSelect: rangeSelect,
      checkboxes: checkboxes,
      height: height,
      width: width,
      update: update,
      fetchStart: fetchStart,
      dense: dense,
      selectDisabled: selectDisabled,
      keyboard: keyboard,
      showGray: showGray,
      scrollState: scrollState,
      sortByState: sortByState,
      setCount: setCount
    });
  })));
}

function ListBoxFetchMasterItem(_ref) {
  let {
    app,
    fieldIdentifier,
    stateName = '$',
    options = {}
  } = _ref;
  const [fieldDef, setFieldDef] = useState$1('');
  const [isFetchingData, setIsFetchingData] = useState$1(false);
  useEffect$1(() => {
    async function fetchData() {
      setIsFetchingData(true);

      try {
        const dim = await app.getDimension(fieldIdentifier.qLibraryId);
        const dimLayout = await dim.getLayout();
        setFieldDef(dimLayout.qDim.qFieldDefs ? dimLayout.qDim.qFieldDefs[0] : '');
        setIsFetchingData(false);
      } catch (e) {
        setIsFetchingData(false);
        setFieldDef({
          failedToFetchFieldDef: true
        });
        throw new Error("Disabling frequency count and histogram: ".concat(e && e.message));
      }
    }

    fetchData();
  }, []);

  if (isFetchingData) {
    return null;
  }

  return /*#__PURE__*/React.createElement(ListBoxInline, {
    app: app,
    fieldIdentifier: fieldIdentifier,
    stateName: stateName,
    options: options,
    fieldDef: fieldDef
  });
}
function ListBoxPortal(_ref2) {
  let {
    app,
    fieldIdentifier,
    stateName,
    element,
    options
  } = _ref2;
  const isFrequencyMaxNeeded = options.histogram || options.frequencyMode !== 'N';
  const TheComponent = fieldIdentifier.qLibraryId && isFrequencyMaxNeeded ? ListBoxFetchMasterItem : ListBoxInline;
  return ReactDOM.createPortal( /*#__PURE__*/React.createElement(TheComponent, {
    app: app,
    fieldIdentifier: fieldIdentifier,
    stateName: stateName,
    element: element,
    options: options
  }), element);
}

const idGen = [[10, 31], [0, 31], [0, 31], [0, 31], [0, 31], [0, 31]];

function toChar(_ref) {
  let [min, max] = _ref;
  return (min + (Math.random() * (max - min) | 0)).toString(32);
}

function uid() {
  return idGen.map(toChar).join('');
}

function addIndex(array, index) {
  for (let i = 0; i < array.length; ++i) {
    if (array[i] >= 0 && array[i] >= index) {
      ++array[i];
    }
  }

  array.push(index);
}

function removeIndex(array, index) {
  let removeIdx = 0;

  for (let i = 0; i < array.length; ++i) {
    if (array[i] > index) {
      --array[i];
    } else if (array[i] === index) {
      removeIdx = i;
    }
  }

  array.splice(removeIdx, 1);
  return removeIdx;
}

const nxDimension = f => ({
  qDef: {
    qFieldDefs: [f]
  }
});

const nxMeasure = f => ({
  qDef: {
    qDef: f
  }
});

function hcHandler(_ref) {
  let {
    dc: hc,
    def,
    properties
  } = _ref;
  hc.qDimensions = hc.qDimensions || [];
  hc.qMeasures = hc.qMeasures || [];
  hc.qInterColumnSortOrder = hc.qInterColumnSortOrder || [];
  hc.qInitialDataFetch = hc.qInitialDataFetch || [];
  hc.qColumnOrder = hc.qColumnOrder || [];
  hc.qExpansionState = hc.qExpansionState || [];
  const objectProperties = properties;
  const handler = {
    dimensions() {
      return hc.qDimensions;
    },

    measures() {
      return hc.qMeasures;
    },

    addDimension(d) {
      const dimension = typeof d === 'string' ? nxDimension(d) : _objectSpread2(_objectSpread2({}, d), {}, {
        qDef: d.qDef || {}
      });
      dimension.qDef.cId = dimension.qDef.cId || uid(); // ====== add default objects and arrays for NxDimension =====
      // TODO - apply autosort properties based on tags

      dimension.qDef.qSortCriterias = dimension.qDef.qSortCriterias || [{
        qSortByLoadOrder: 1,
        qSortByNumeric: 1,
        qSortByAscii: 1
      }];
      dimension.qOtherTotalSpec = dimension.qOtherTotalSpec || {};
      dimension.qAttributeExpressions = dimension.qAttributeExpressions || [];
      dimension.qAttributeDimensions = dimension.qAttributeDimensions || []; // ========= end defaults =============

      if (hc.qDimensions.length < handler.maxDimensions()) {
        hc.qDimensions.push(dimension);
        addIndex(hc.qInterColumnSortOrder, hc.qDimensions.length - 1);
        def.dimensions.added(dimension, objectProperties);
      } else {
        hc.qLayoutExclude = hc.qLayoutExclude || {};
        hc.qLayoutExclude.qHyperCubeDef = hc.qLayoutExclude.qHyperCubeDef || {};
        hc.qLayoutExclude.qHyperCubeDef.qDimensions = hc.qLayoutExclude.qHyperCubeDef.qDimensions || [];
        hc.qLayoutExclude.qHyperCubeDef.qMeasures = hc.qLayoutExclude.qHyperCubeDef.qMeasures || [];
        hc.qLayoutExclude.qHyperCubeDef.qDimensions.push(dimension);
      }
    },

    removeDimension(idx) {
      const dimension = hc.qDimensions.splice(idx, 1)[0];
      removeIndex(hc.qInterColumnSortOrder, idx);
      def.dimensions.removed(dimension, objectProperties, idx);
    },

    addMeasure(m) {
      const measure = typeof m === 'string' ? nxMeasure(m) : _objectSpread2(_objectSpread2({}, m), {}, {
        qDef: m.qDef || {}
      });
      measure.qDef.cId = measure.qDef.cId || uid(); // ====== add default objects and arrays for NxMeasure =====

      measure.qSortBy = measure.qSortBy || {
        qSortByLoadOrder: 1,
        qSortByNumeric: -1
      };
      measure.qAttributeDimensions = measure.qAttributeDimensions || [];
      measure.qAttributeExpressions = measure.qAttributeExpressions || [];

      if (hc.qMeasures.length < handler.maxMeasures()) {
        hc.qMeasures.push(measure);
        addIndex(hc.qInterColumnSortOrder, hc.qDimensions.length + hc.qMeasures.length - 1);
        def.measures.added(measure, objectProperties);
      } else {
        hc.qLayoutExclude = hc.qLayoutExclude || {};
        hc.qLayoutExclude.qHyperCubeDef = hc.qLayoutExclude.qHyperCubeDef || {};
        hc.qLayoutExclude.qHyperCubeDef.qDimensions = hc.qLayoutExclude.qHyperCubeDef.qDimensions || [];
        hc.qLayoutExclude.qHyperCubeDef.qMeasures = hc.qLayoutExclude.qHyperCubeDef.qMeasures || [];
        hc.qLayoutExclude.qHyperCubeDef.qMeasures.push(measure);
      }
    },

    removeMeasure(idx) {
      const measure = hc.qMeasures.splice(idx, 1)[0];
      removeIndex(hc.qInterColumnSortOrder, hc.qDimensions.length + idx);
      def.measures.removed(measure, objectProperties, idx);
    },

    maxDimensions() {
      return def.dimensions.max(hc.qMeasures.length);
    },

    maxMeasures() {
      return def.measures.max(hc.qDimensions.length);
    },

    canAddDimension() {
      return hc.qDimensions.length < handler.maxDimensions();
    },

    canAddMeasure() {
      return hc.qMeasures.length < handler.maxMeasures();
    }

  };
  return handler;
}

/**
 * @interface LibraryField
 * @property {string} qLibraryId
 * @property {'dimension'|'measure'} type
 */

function fieldType(f) {
  if ( // a string starting with '=' is just a convention we use
  typeof f === 'string' && f[0] === '=' || // based on NxMeasure and NxInlineMeasureDef
  typeof f === 'object' && f.qDef && f.qDef.qDef || // use 'type' instead of 'qType' since this is not a real property
  typeof f === 'object' && f.qLibraryId && f.type === 'measure') {
    return 'measure';
  }

  return 'dimension';
}
function populateData(_ref) {
  let {
    sn,
    properties,
    fields
  } = _ref;

  if (!fields.length) {
    return;
  }

  const target = sn.qae.data.targets[0];

  if (!target) {
    {
      console.warn('Attempting to add fields to an object without a specified data target'); // eslint-disable-line no-console
    }

    return;
  }

  const {
    propertyPath
  } = target;
  const parts = propertyPath.split('/');
  let p = properties;

  for (let i = 0; i < parts.length; i++) {
    const s = parts[i];
    p = s ? p[s] : p;
  }

  const hc = hcHandler({
    dc: p,
    def: target,
    properties
  });
  fields.forEach(f => {
    const type = fieldType(f);

    if (type === 'measure') {
      hc.addMeasure(f);
    } else {
      hc.addDimension(f);
    }
  });
}

/**
 * Used for exporting and importing properties between backend models. An object that exports to
 * ExportFormat should put dimensions and measures inside one data group. If an object has two hypercubes,
 * each of the cubes should export dimensions and measures in two separate data groups.
 * An object that imports from this structure is responsible for putting the existing properties where they should be
 * in the new model.
 * @interface ExportFormat
 * @since 1.1.0
 * @property {(ExportDataDef[])=} data
 * @property {object=} properties
 */

/**
 * @since 1.1.0
 * @interface ExportDataDef
 * @property {EngineAPI.INxDimension[]} dimensions
 * @property {EngineAPI.INxMeasure[]} measures
 * @property {EngineAPI.INxDimension[]} excludedDimensions
 * @property {EngineAPI.INxMeasure[]} excludedMeasures
 * @property {number[]} interColumnSortOrder
 */

/**
 * @since 1.1.0
 * @ignore
 * @param {number} nDataGroups
 * @return {ExportFormat}
 */
function createExportFormat() {
  let nDataGroups = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
  const exportFormat = {
    data: [],
    properties: {}
  };

  for (let i = 0; i < nDataGroups; ++i) {
    exportFormat.data.push({
      dimensions: [],
      measures: [],
      excludedDimensions: [],
      excludedMeasures: [],
      interColumnSortOrder: []
    });
  }

  return exportFormat;
}

/**
 * Gets a value from a data object structure.
 *
 * @ignore
 * @param data The data object.
 * @param reference Reference to the value.
 * @param defaultValue Default value to return if no value was found.
 * @returns {*} The default value if specified, otherwise undefined.
 */
const getValue = (data, reference, defaultValue) => {
  if (data === undefined || data === null || reference === undefined || reference === null) {
    return defaultValue;
  }

  const steps = reference.split('.');
  let dataContainer = data;

  for (let i = 0; i < steps.length; ++i) {
    const step = steps[i];

    if (step === '') {
      continue; // eslint-disable-line no-continue
    }

    if (dataContainer[step] === undefined || dataContainer[step] === null) {
      return defaultValue;
    }

    dataContainer = dataContainer[step];
  }

  return dataContainer;
};
/**
 * Sets a value in a data object using a dot notated reference to point out the path.
 *
 * Example:
 * If data is an empty object, reference is "my.value" and value the is "x", then
 * the resulting data object will be: { my:	{ value: "x" } }
 *
 * @ignore
 * @param data The data object. Must be an object.
 * @param reference Reference to the value.
 * @param value Arbitrary value to set. If the value is set to undefined, the value property will be removed.
 */


const setValue = (data, reference, value) => {
  if (data === undefined || data === null || reference === undefined || reference === null) {
    return;
  }

  const steps = reference.split('.');
  const propertyName = steps[steps.length - 1];
  let dataContainer = data;

  for (let i = 0; i < steps.length - 1; ++i) {
    const step = steps[i];

    if (dataContainer[step] === undefined || dataContainer[step] === null) {
      dataContainer[step] = Number.isNaN(+steps[i + 1]) ? {} : [];
    }

    dataContainer = dataContainer[step];
  }

  if (typeof value !== 'undefined' && propertyName !== '__proto__' && propertyName !== 'constructor') {
    dataContainer[propertyName] = value;
  } else {
    delete dataContainer[propertyName];
  }
};

const isEmpty = object => Object.keys(object).length === 0 && object.constructor === Object;

var utils = {
  getValue,
  setValue,
  isEmpty
};

/* eslint-disable no-param-reassign */

/**
 * Returns true if the second array is a ordered subset of the first.
 *
 * @ignore
 * @param array1
 * @param array2
 * @returns {boolean}
 */
function isOrderedSubset(outer, subset) {
  if (!outer || !subset || !outer.length || !subset.length) {
    return false;
  }

  let start = outer.indexOf(subset[0]);

  if (start !== -1) {
    for (let i = 0; i < subset.length; i++) {
      const next = outer.indexOf(subset[i]);

      if (start > next) {
        return false;
      }

      start = next;
    }

    return true;
  }

  return false;
}
/**
 * Used for adding an index to an index array. An index array contains indices from 0-N in any order and
 * is used for keeping track of how items in another arrayed could be presented in a specific order.
 *
 * @ignore
 * @param array
 * @param index
 */


function indexAdded(array, index) {
  let i;

  for (i = 0; i < array.length; ++i) {
    if (array[i] >= 0 && array[i] >= index) {
      ++array[i];
    }
  }

  array.push(index);
}
/**
 * Used for removing an index from an index array. An index array contains indices from 0-N in any order and
 * is used for keeping track of how items in another arrayed could be presented in a specific order.
 *
 * @ignore
 * @param array
 * @param index
 */


function indexRemoved(array, index) {
  let removeIndex = 0;
  let i;

  for (i = 0; i < array.length; ++i) {
    if (array[i] > index) {
      --array[i];
    } else if (array[i] === index) {
      removeIndex = i;
    }
  }

  array.splice(removeIndex, 1);
  return removeIndex;
}

var arrayUtils = {
  isOrderedSubset,
  indexAdded,
  indexRemoved
};

/* eslint-disable no-prototype-builtins */
const MAX_SAFE_INTEGER = 2 ** 53 - 1;
/**
 * Restore properties that were temporarily changed during conversion.
 *
 * @ignore
 * @param properties PropertyTree
 */

function restoreChangedProperties(properties) {
  Object.keys(properties.qLayoutExclude.changed).forEach(property => {
    if (properties.qLayoutExclude.changed[property].to === utils.getValue(properties, property)) {
      // only revert back to old value if the current value is the same as it was changed to during conversion
      utils.setValue(properties, property, properties.qLayoutExclude.changed[property].from);
    }
  });
}
/**
 * Used to check if a property key is part of the master item information
 *
 * @ignore
 * @param propertyName Name of the key in the properties object
 * @returns {boolean}
 */


function isMasterItemProperty(propertyName) {
  return ['qMetaDef', 'descriptionExpression', 'labelExpression'].indexOf(propertyName) !== -1;
}

function importCommonProperties(newProperties, exportFormat, initialProperties) {
  // always copy type and visualization
  const qType = utils.getValue(exportFormat, 'properties.qInfo.qType') === 'masterobject' ? 'masterobject' : utils.getValue(initialProperties, 'qInfo.qType');
  utils.setValue(newProperties, 'qInfo.qType', qType);
  newProperties.visualization = initialProperties.visualization;
}

function copyPropertyIfExist(propertyName, source, target) {
  if (source.hasOwnProperty(propertyName)) {
    target[propertyName] = source[propertyName];
  }
}

function copyPropertyOrSetDefault(propertyName, source, target, defaultValue) {
  if (source.hasOwnProperty(propertyName)) {
    target[propertyName] = source[propertyName];
  } else {
    target[propertyName] = defaultValue;
  }
}

function getOthersLabel() {
  return 'Others'; // TODO: translator.get('properties.dimensionLimits.others')
}

function createDefaultDimension(dimensionDef, dimensionProperties) {
  const def = extend$2(true, {}, dimensionProperties, dimensionDef);

  if (!utils.getValue(def, 'qOtherTotalSpec.qOtherCounted')) {
    utils.setValue(def, 'qOtherTotalSpec.qOtherCounted', {
      qv: '10'
    });
  }

  if (!utils.getValue(def, 'qOtherTotalSpec.qOtherLimit')) {
    utils.setValue(def, 'qOtherTotalSpec.qOtherLimit', {
      qv: '0'
    });
  }

  if (!def.hasOwnProperty('othersLabel')) {
    def.othersLabel = getOthersLabel();
  }

  return def;
}

function createDefaultMeasure(measureDef, measureProperties) {
  return extend$2(true, {}, measureProperties, measureDef);
}

function resolveValue$1(data, input, defaultValue) {
  if (typeof data === 'function') {
    return data(input);
  }

  return !Number.isNaN(+data) ? data : defaultValue;
}

function getHypercubePath(qae) {
  const path = utils.getValue(qae, 'data.targets.0.propertyPath', '');
  const steps = path.split('/');

  if (steps.length && steps[steps.length - 1] === 'qHyperCubeDef') {
    steps.length -= 1;
  }

  return steps.join('.');
}

function getDefaultDimension() {
  return {
    qDef: {
      autoSort: true,
      cId: '',
      othersLabel: getOthersLabel()
    },
    qLibraryId: '',
    qNullSuppression: false,
    qOtherLabel: 'Others',
    qOtherTotalSpec: {
      qOtherLimitMode: 'OTHER_GE_LIMIT',
      qOtherMode: 'OTHER_OFF',
      qOtherSortMode: 'OTHER_SORT_DESCENDING',
      qSuppressOther: false
    }
  };
}

function getDefaultMeasure() {
  return {
    qDef: {
      autoSort: true,
      cId: '',
      numFormatFromTemplate: true
    },
    qLibraryId: '',
    qTrendLines: []
  };
}

function setInterColumnSortOrder(_ref) {
  let {
    exportFormat,
    newHyperCubeDef
  } = _ref;
  const dataGroup = exportFormat.data[0];
  const nCols = newHyperCubeDef.qDimensions.length + newHyperCubeDef.qMeasures.length;
  newHyperCubeDef.qInterColumnSortOrder = dataGroup.interColumnSortOrder.concat();
  let i = newHyperCubeDef.qInterColumnSortOrder.length;

  if (i !== nCols) {
    if (newHyperCubeDef.qLayoutExclude) {
      // Store them if needed
      newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qInterColumnSortOrder = dataGroup.interColumnSortOrder.concat();
    }

    while (i !== nCols) {
      if (i < nCols) {
        arrayUtils.indexAdded(newHyperCubeDef.qInterColumnSortOrder, i);
        ++i;
      } else {
        --i;
        arrayUtils.indexRemoved(newHyperCubeDef.qInterColumnSortOrder, i);
      }
    }
  }
}

function createNewProperties(_ref2) {
  let {
    exportFormat,
    initialProperties,
    hypercubePath
  } = _ref2;
  let newProperties = {
    qLayoutExclude: {
      disabled: {},
      quarantine: {}
    }
  };
  Object.keys(exportFormat.properties).forEach(key => {
    if (key === 'qLayoutExclude') {
      if (exportFormat.properties[key].quarantine) {
        newProperties.qLayoutExclude.quarantine = extend$2(true, {}, exportFormat.properties[key].quarantine);
      }
    } else if (key === 'qHyperCubeDef' && hypercubePath) {
      utils.setValue(newProperties, "".concat(hypercubePath, ".qHyperCubeDef"), exportFormat.properties.qHyperCubeDef);
    } else if (initialProperties.hasOwnProperty(key) || isMasterItemProperty(key)) {
      // TODO: qExtendsId ??
      newProperties[key] = exportFormat.properties[key];
    } else {
      newProperties.qLayoutExclude.disabled[key] = exportFormat.properties[key];
    }
  });
  newProperties = extend$2(true, {}, initialProperties, newProperties);

  if (newProperties.components === null) {
    newProperties.components = [];
  }

  return newProperties;
}

function getMaxMinDimensionMeasure(_ref3) {
  let {
    exportFormat,
    dataDefinition = {}
  } = _ref3;
  const dataGroup = exportFormat.data[0];
  const dimensionDef = dataDefinition.dimensions || {
    max: 0
  };
  const measureDef = dataDefinition.measures || {
    max: 0
  };
  const maxMeasures = resolveValue$1(measureDef.max, dataGroup.dimensions.length, MAX_SAFE_INTEGER);
  const minMeasures = resolveValue$1(measureDef.min, dataGroup.dimensions.length, 0);
  const maxDimensions = resolveValue$1(dimensionDef.max, maxMeasures, MAX_SAFE_INTEGER);
  const minDimensions = resolveValue$1(dimensionDef.min, minMeasures, 0);
  return {
    maxDimensions,
    minDimensions,
    maxMeasures,
    minMeasures
  };
}

function shouldInitLayoutExclude(_ref4) {
  let {
    exportFormat,
    maxDimensions,
    minDimensions,
    maxMeasures,
    minMeasures
  } = _ref4;
  const dataGroup = exportFormat.data[0];
  return dataGroup.dimensions.length > maxDimensions && maxDimensions > 0 || dataGroup.measures.length > maxMeasures && maxMeasures > 0 || dataGroup.excludedDimensions.length > 0 && dataGroup.dimensions.length + dataGroup.excludedDimensions.length > minDimensions || dataGroup.excludedMeasures.length > 0 && dataGroup.measures.length + dataGroup.excludedMeasures.length > minMeasures || !maxMeasures && dataGroup.measures.length > 0 || !maxDimensions && dataGroup.dimensions.length > 0;
}

function initLayoutExclude(_ref5) {
  let {
    exportFormat,
    maxDimensions,
    minDimensions,
    maxMeasures,
    minMeasures,
    newHyperCubeDef
  } = _ref5;
  const dataGroup = exportFormat.data[0];

  if (!newHyperCubeDef.qLayoutExclude) {
    newHyperCubeDef.qLayoutExclude = {};
  }

  if (!newHyperCubeDef.qLayoutExclude.qHyperCubeDef) {
    newHyperCubeDef.qLayoutExclude.qHyperCubeDef = {};
  }

  if (dataGroup.dimensions.length > maxDimensions && maxDimensions > 0 || dataGroup.excludedDimensions && dataGroup.excludedDimensions.length && dataGroup.dimensions.length + dataGroup.excludedDimensions.length > minDimensions) {
    if (!newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qDimensions) {
      newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qDimensions = [];
    }
  }

  if (dataGroup.measures.length > maxMeasures && maxMeasures > 0 || dataGroup.excludedMeasures && dataGroup.excludedMeasures.length && dataGroup.measures.length + dataGroup.excludedMeasures.length > minMeasures) {
    if (!newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qMeasures) {
      newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qMeasures = [];
    }
  }

  if (!maxMeasures && dataGroup.measures.length) {
    // if the object don't support measures put them in alternative measures instead
    if (!newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qMeasures) {
      newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qMeasures = [];
    }
  }

  if (!maxDimensions && dataGroup.dimensions.length) {
    // if the object don't support dimensions put them in alternative dimensions instead
    if (!newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qDimensions) {
      newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qDimensions = [];
    }
  }
}

function addDefaultDimensions(_ref6) {
  let {
    exportFormat,
    maxDimensions,
    minDimensions,
    newHyperCubeDef,
    defaultDimension
  } = _ref6;
  const dataGroup = exportFormat.data[0];
  let i;

  if (maxDimensions > 0) {
    for (i = 0; i < dataGroup.dimensions.length; ++i) {
      if (newHyperCubeDef.qDimensions.length < maxDimensions) {
        newHyperCubeDef.qDimensions.push(createDefaultDimension(dataGroup.dimensions[i], defaultDimension));
      } else {
        newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qDimensions.push(createDefaultDimension(dataGroup.dimensions[i], defaultDimension));
      }
    }
  } else if (dataGroup.dimensions.length) {
    for (i = 0; i < dataGroup.dimensions.length; ++i) {
      newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qDimensions.push(createDefaultDimension(dataGroup.dimensions[i], defaultDimension));
    }
  }

  if (dataGroup.excludedDimensions.length) {
    for (i = 0; i < dataGroup.excludedDimensions.length; ++i) {
      if (newHyperCubeDef.qDimensions.length < minDimensions) {
        newHyperCubeDef.qDimensions.push(createDefaultDimension(dataGroup.excludedDimensions[i], defaultDimension));
      } else {
        newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qDimensions.push(createDefaultDimension(dataGroup.excludedDimensions[i], defaultDimension));
      }
    }
  }
}

function addDefaultMeasures(_ref7) {
  let {
    exportFormat,
    maxMeasures,
    minMeasures,
    newHyperCubeDef,
    defaultMeasure
  } = _ref7;
  const dataGroup = exportFormat.data[0];
  let i;

  if (maxMeasures > 0) {
    for (i = 0; i < dataGroup.measures.length; ++i) {
      if (newHyperCubeDef.qMeasures.length < maxMeasures) {
        newHyperCubeDef.qMeasures.push(createDefaultMeasure(dataGroup.measures[i], defaultMeasure));
      } else {
        newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qMeasures.push(createDefaultMeasure(dataGroup.measures[i], defaultMeasure));
      }
    }
  } else if (dataGroup.measures.length) {
    for (i = 0; i < dataGroup.measures.length; ++i) {
      newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qMeasures.push(createDefaultMeasure(dataGroup.measures[i], defaultMeasure));
    }
  }

  if (dataGroup.excludedMeasures.length) {
    for (i = 0; i < dataGroup.excludedMeasures.length; ++i) {
      if (newHyperCubeDef.qMeasures.length < minMeasures) {
        newHyperCubeDef.qMeasures.push(createDefaultMeasure(dataGroup.excludedMeasures[i], defaultMeasure));
      } else {
        newHyperCubeDef.qLayoutExclude.qHyperCubeDef.qMeasures.push(createDefaultMeasure(dataGroup.excludedMeasures[i], defaultMeasure));
      }
    }
  }
}

function updateDimensionsOnAdded(_ref8) {
  let {
    newProperties,
    dataDefinition,
    hypercubePath
  } = _ref8;

  if (dataDefinition.dimensions && typeof dataDefinition.dimensions.added === 'function') {
    const newHyperCubeDef = utils.getValue(newProperties, hypercubePath || '').qHyperCubeDef;
    const dimensions = [...newHyperCubeDef.qDimensions];
    newHyperCubeDef.qDimensions = [];
    dimensions.forEach(dimension => {
      newHyperCubeDef.qDimensions.push(dimension);
      dataDefinition.dimensions.added(dimension, newProperties);
    });
  }
}

function updateMeasuresOnAdded(_ref9) {
  let {
    newProperties,
    dataDefinition,
    hypercubePath
  } = _ref9;

  if (dataDefinition.measures && typeof dataDefinition.measures.added === 'function') {
    const newHyperCubeDef = utils.getValue(newProperties, hypercubePath || '').qHyperCubeDef;
    const measures = [...newHyperCubeDef.qMeasures];
    newHyperCubeDef.qMeasures = [];
    measures.forEach(measure => {
      newHyperCubeDef.qMeasures.push(measure);
      dataDefinition.measures.added(measure, newProperties);
    });
  }
}

var helpers = {
  restoreChangedProperties,
  isMasterItemProperty,
  importCommonProperties,
  copyPropertyIfExist,
  copyPropertyOrSetDefault,
  createDefaultDimension,
  createDefaultMeasure,
  resolveValue: resolveValue$1,
  getHypercubePath,
  getDefaultDimension,
  getDefaultMeasure,
  setInterColumnSortOrder,
  createNewProperties,
  getMaxMinDimensionMeasure,
  shouldInitLayoutExclude,
  initLayoutExclude,
  addDefaultDimensions,
  addDefaultMeasures,
  updateDimensionsOnAdded,
  updateMeasuresOnAdded
};

/* eslint-disable no-prototype-builtins */
function exportProperties(_ref) {
  let {
    propertyTree,
    hypercubePath
  } = _ref;
  const exportFormat = createExportFormat();
  const properties = propertyTree.qProperty;
  const hcdParent = utils.getValue(properties, hypercubePath || '');
  const hcd = hcdParent.qHyperCubeDef;
  const dataGroup = exportFormat.data[0];

  if (!hcd.qInterColumnSortOrder) {
    hcd.qInterColumnSortOrder = [];
  } // export dimensions


  dataGroup.dimensions.push(...hcd.qDimensions); // excluded dimensions

  if (hcd.qLayoutExclude && hcd.qLayoutExclude.qHyperCubeDef && hcd.qLayoutExclude.qHyperCubeDef.qDimensions) {
    dataGroup.excludedDimensions.push(...hcd.qLayoutExclude.qHyperCubeDef.qDimensions);
  } // export measures


  dataGroup.measures.push(...hcd.qMeasures); // excluded measures

  if (hcd.qLayoutExclude && hcd.qLayoutExclude.qHyperCubeDef && hcd.qLayoutExclude.qHyperCubeDef.qMeasures) {
    dataGroup.excludedMeasures.push(...hcd.qLayoutExclude.qHyperCubeDef.qMeasures);
  } // export sort order


  dataGroup.interColumnSortOrder = hcd.qInterColumnSortOrder.concat(); // if we have a excluded sort order, try apply that instead

  if (hcd.qLayoutExclude && hcd.qLayoutExclude.qHyperCubeDef && hcd.qLayoutExclude.qHyperCubeDef.qInterColumnSortOrder) {
    const order = hcd.qLayoutExclude.qHyperCubeDef.qInterColumnSortOrder.concat(); // If the exporting sort order hasn't changed compared to the excluded we can apply the full excluded instead

    if (arrayUtils.isOrderedSubset(order, dataGroup.interColumnSortOrder)) {
      dataGroup.interColumnSortOrder = order;
    }
  }

  delete hcd.qLayoutExclude;
  Object.keys(properties).forEach(prop => {
    exportFormat.properties[prop] = properties[prop];
  });

  if (hypercubePath) {
    exportFormat.properties.qHyperCubeDef = hcdParent.qHyperCubeDef;
    delete hcdParent.qHyperCubeDef;
  }

  if (!properties.qLayoutExclude) {
    properties.qLayoutExclude = {};
  }

  if (properties.qLayoutExclude.disabled) {
    Object.keys(properties.qLayoutExclude.disabled).forEach(prop => {
      if (!exportFormat.properties.hasOwnProperty(prop)) {
        exportFormat.properties[prop] = properties.qLayoutExclude.disabled[prop];
      }
    });
    delete properties.qLayoutExclude.disabled;
  }

  if (properties.qLayoutExclude.changed) {
    helpers.restoreChangedProperties(properties);
    delete properties.qLayoutExclude.changed;
  }

  if (!properties.qLayoutExclude.quarantine || utils.isEmpty(properties.qLayoutExclude.quarantine)) {
    delete properties.qLayoutExclude;
  }

  return exportFormat;
}

/* eslint-disable no-param-reassign */
function importProperties(_ref) {
  let {
    exportFormat,
    initialProperties = {},
    dataDefinition = {},
    defaultPropertyValues = {},
    hypercubePath
  } = _ref;
  const newPropertyTree = {
    qChildren: []
  };
  const newProperties = helpers.createNewProperties({
    exportFormat,
    initialProperties,
    hypercubePath
  });
  const initHyperCubeDef = utils.getValue(initialProperties, hypercubePath || '').qHyperCubeDef;
  const newHyperCubeDef = utils.getValue(newProperties, hypercubePath || '').qHyperCubeDef;
  const {
    maxDimensions,
    minDimensions,
    maxMeasures,
    minMeasures
  } = helpers.getMaxMinDimensionMeasure({
    exportFormat,
    dataDefinition
  });
  const {
    defaultDimension = helpers.getDefaultDimension(),
    defaultMeasure = helpers.getDefaultMeasure()
  } = defaultPropertyValues; // empty dimensions and measures of new hypercube

  newHyperCubeDef.qDimensions.length = 0;
  newHyperCubeDef.qMeasures.length = 0; // create layout exclude structures if needed

  if (helpers.shouldInitLayoutExclude({
    exportFormat,
    maxDimensions,
    minDimensions,
    maxMeasures,
    minMeasures
  })) {
    helpers.initLayoutExclude({
      exportFormat,
      maxDimensions,
      minDimensions,
      maxMeasures,
      minMeasures,
      newHyperCubeDef
    });
  } // and now fill them in.


  helpers.addDefaultDimensions({
    exportFormat,
    maxDimensions,
    minDimensions,
    newHyperCubeDef,
    defaultDimension
  });
  helpers.addDefaultMeasures({
    exportFormat,
    maxMeasures,
    minMeasures,
    newHyperCubeDef,
    defaultMeasure
  });
  helpers.setInterColumnSortOrder({
    exportFormat,
    newHyperCubeDef
  });
  helpers.copyPropertyIfExist('qMaxStackedCells', initHyperCubeDef, newHyperCubeDef);
  helpers.copyPropertyIfExist('qNoOfLeftDims', initHyperCubeDef, newHyperCubeDef);
  helpers.copyPropertyOrSetDefault('qInitialDataFetch', initHyperCubeDef, newHyperCubeDef, [{
    qTop: 0,
    qLeft: 0,
    qWidth: 0,
    qHeight: 0
  }]);
  helpers.copyPropertyOrSetDefault('qMode', initHyperCubeDef, newHyperCubeDef, 'S');
  helpers.copyPropertyOrSetDefault('qReductionMode', initHyperCubeDef, newHyperCubeDef, 'N');
  helpers.copyPropertyOrSetDefault('qSortbyYValue', initHyperCubeDef, newHyperCubeDef);
  helpers.copyPropertyOrSetDefault('qIndentMode', initHyperCubeDef, newHyperCubeDef);
  helpers.copyPropertyOrSetDefault('qShowTotalsAbove', initHyperCubeDef, newHyperCubeDef); // always copy type and visualization

  helpers.importCommonProperties(newProperties, exportFormat, initialProperties);
  helpers.updateDimensionsOnAdded({
    newProperties,
    dataDefinition,
    hypercubePath
  });
  helpers.updateMeasuresOnAdded({
    newProperties,
    dataDefinition,
    hypercubePath
  });
  newPropertyTree.qProperty = newProperties;
  return newPropertyTree;
}

/**
 * @interface hyperCubeConversion
 * @since 1.1.0
 * @implements {ConversionType}
 */

var hypercube = /** @lends hyperCubeConversion */
{
  exportProperties: ar => exportProperties(ar),
  importProperties: ar => importProperties(ar)
};

const getType$1 = async _ref => {
  let {
    halo,
    name,
    version
  } = _ref;
  const {
    types
  } = halo;
  const SN = await types.get({
    name,
    version
  }).supernova();
  return SN;
};

const getPath = qae => utils.getValue(qae, 'data.targets.0.propertyPath');

const getDefaultExportPropertiesFn = path => {
  const steps = path.split('/');

  if (steps.indexOf('qHyperCubeDef') > -1) {
    return hypercube.exportProperties;
  }

  return undefined; // TODO: add listbox and other
};

const getExportPropertiesFnc = qae => {
  if (qae.exportProperties) {
    return qae.exportProperties;
  }

  const path = getPath(qae);
  return getDefaultExportPropertiesFn(path);
};

const getDefaultImportPropertiesFnc = path => {
  const steps = path.split('/');

  if (steps.indexOf('qHyperCubeDef') > -1) {
    return hypercube.importProperties;
  }

  return undefined; // TODO: add listbox and other
};

const getImportPropertiesFnc = qae => {
  if (qae.importProperties) {
    return qae.importProperties;
  }

  const path = getPath(qae);
  return getDefaultImportPropertiesFnc(path);
};

const convertTo = async _ref2 => {
  let {
    halo,
    model,
    cellRef,
    newType
  } = _ref2;
  const propertyTree = await model.getFullPropertyTree();
  const sourceQae = cellRef.current.getQae();
  const exportProperties = getExportPropertiesFnc(sourceQae);
  const targetSnType = await getType$1({
    halo,
    name: newType
  });
  const targetQae = targetSnType.qae;
  const importProperties = getImportPropertiesFnc(targetQae);
  const exportFormat = exportProperties({
    propertyTree,
    hypercubePath: helpers.getHypercubePath(sourceQae)
  });
  const initial = utils.getValue(targetQae, 'properties.initial', {});

  const initialProperties = _objectSpread2({
    qInfo: {
      qType: newType
    },
    visualization: newType
  }, initial);

  const newPropertyTree = importProperties({
    exportFormat,
    initialProperties,
    dataDefinition: utils.getValue(targetQae, 'data.targets.0.', {}),
    hypercubePath: helpers.getHypercubePath(targetQae)
  });
  return newPropertyTree;
};
/**
 * @interface ConversionType
 * @since 1.1.0
 * @property {importProperties} importProperties
 * @property {exportProperties} exportProperties
 */

/**
 * @interface
 * @alias Conversion
 * @since 1.1.0
 * @description Provides conversion functionality to extensions.
 * @example
 * import { conversion } from '@nebula.js/stardust';
 *
 * export default function() {
 *   return {
 *     qae: {
 *       ...
 *       importProperties: ( exportFormat, initialProperties ) =>  conversion.hyperCube.importProperties(exportFormat, initialProperties),
 *       exportProperties: ( fullPropertyTree ) => conversion.hyperCube.exportProperties(fullPropertyTree)
 *     },
 *     ...
 *   };
 * }
 *
 */

const conversion = {
  /**
   * @type {hyperCubeConversion}
   * @since 1.1.0
   * @description Provides conversion functionality to extensions with hyperCubes.
   */
  hypercube
};

const warning = props => _objectSpread2(_objectSpread2({}, props), {}, {
  shapes: [{
    type: 'path',
    attrs: {
      d: 'M8.86225926,1.6 L15.7815749,13.5 C16.2829746,14.3 15.8818548,15 14.9793354,15 L1.04042422,15 C0.0853772072,15 -0.232971797,14.3650794 0.172002787,13.6135407 L7.05722041,1.6 C7.55862009,0.8 8.36085958,0.8 8.86225926,1.6 Z M7.962,2.007 C7.95987183,2.02476599 7.95607967,2.03712023 7.94920396,2.05249845 L1.1033193,14 L14.915544,14 L7.99777452,2.10265906 L7.97779697,2.06138411 L7.96394459,2.01964415 L7.962,2.007 Z M7.5,11 L8.5,11 C8.76666667,11 8.95432099,11.1580247 8.99272977,11.4038409 L9,11.5 L9,12.5 C9,12.7666667 8.84197531,12.954321 8.59615912,12.9927298 L8.5,13 L7.5,13 C7.23333333,13 7.04567901,12.8419753 7.00727023,12.5961591 L7,12.5 L7,11.5 C7,11.2333333 7.15802469,11.045679 7.40384088,11.0072702 L7.5,11 L8.5,11 L7.5,11 Z M7.5,5 L8.5,5 C8.76666667,5 8.95432099,5.15802469 8.99272977,5.40384088 L9,5.5 L9,9.5 C9,9.76666667 8.84197531,9.95432099 8.59615912,9.99272977 L8.5,10 L7.5,10 C7.23333333,10 7.04567901,9.84197531 7.00727023,9.59615912 L7,9.5 L7,5.5 C7,5.23333333 7.15802469,5.04567901 7.40384088,5.00727023 L7.5,5 L8.5,5 L7.5,5 Z'
    }
  }]
});

var WarningTriangle = (props => SvgIcon(warning(props)));

/* eslint-disable react/no-array-index-key */

function DescriptionRow(_ref) {
  let {
    d
  } = _ref;
  const theme = useTheme$1();
  let color = 'inherit';
  let styleColor = theme.palette.success.main;

  if (d.missing) {
    styleColor = theme.palette.warning.main;
  } else if (d.error) {
    color = 'error';
    styleColor = theme.palette.error.main;
  }

  const style = {
    color: styleColor
  };
  const WrappedIcon = /*#__PURE__*/React.createElement(Typography, {
    style: {
      lineHeight: '30px',
      paddingRight: theme.spacing(1)
    }
  }, /*#__PURE__*/React.createElement(Icon, null, d.missing || d.error ? /*#__PURE__*/React.createElement(WarningTriangle, {
    style: style
  }) : /*#__PURE__*/React.createElement(Tick, {
    style: style
  })));
  return /*#__PURE__*/React.createElement(Grid, {
    item: true,
    container: true,
    alignItems: "center",
    wrap: "nowrap"
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, WrappedIcon), /*#__PURE__*/React.createElement(Grid, {
    container: true,
    item: true,
    zeroMinWidth: true,
    wrap: "nowrap"
  }, /*#__PURE__*/React.createElement(Typography, {
    noWrap: true,
    component: "p"
  }, /*#__PURE__*/React.createElement(Typography, {
    component: "span",
    variant: "subtitle2",
    color: color
  }, d.description), /*#__PURE__*/React.createElement(Typography, {
    component: "span"
  }, " "), /*#__PURE__*/React.createElement(Typography, {
    component: "span",
    variant: "subtitle2",
    color: d.error ? 'error' : 'inherit',
    style: {
      fontWeight: 400
    }
  }, d.label))));
}

function Descriptions(_ref2) {
  let {
    data
  } = _ref2;
  const theme = useTheme$1();
  return /*#__PURE__*/React.createElement(Grid, {
    container: true,
    item: true,
    style: {
      maxWidth: '300px',
      overflow: 'hidden'
    }
  }, data.map((e, ix) => {
    const Rows = e.descriptions.map((d, dix) => /*#__PURE__*/React.createElement(DescriptionRow, {
      d: d,
      key: dix
    }));
    return Rows.length > 0 && /*#__PURE__*/React.createElement(Grid, {
      container: true,
      item: true,
      key: ix,
      direction: "column",
      style: {
        paddingBottom: theme.spacing(2)
      }
    }, /*#__PURE__*/React.createElement(Typography, {
      noWrap: true,
      key: ix,
      variant: "subtitle1",
      align: "left",
      color: "textSecondary"
    }, e.title), Rows);
  }));
}

function Error$1(_ref3) {
  let {
    title = 'Error',
    message = '',
    data = []
  } = _ref3;
  return /*#__PURE__*/React.createElement(Grid, {
    container: true,
    direction: "column",
    alignItems: "center",
    justifyContent: "center",
    style: {
      position: 'relative',
      height: '100%',
      width: '100%'
    }
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(WarningTriangle, {
    style: {
      fontSize: '38px'
    }
  })), /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(Typography, {
    variant: "h6",
    align: "center",
    "data-tid": "error-title"
  }, title)), /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(Typography, {
    variant: "subtitle1",
    align: "center",
    "data-tid": "error-message"
  }, message)), /*#__PURE__*/React.createElement(Descriptions, {
    data: data
  }));
}

const _excluded$2 = ["size"];
const useStyles$3 = makeStyles(theme => ({
  root: {
    position: 'relative',
    display: 'inline-block'
  },
  front: {
    color: theme.palette.secondary.main,
    animationDuration: '1500ms',
    position: 'absolute',
    left: 0
  },
  back: {
    color: theme.palette.divider
  }
}));
const SIZES = {
  small: 16,
  medium: 32,
  large: 64,
  xlarge: 128
};
function Progress(_ref) {
  let {
    size = 'medium'
  } = _ref,
      props = _objectWithoutProperties$1(_ref, _excluded$2);

  const classes = useStyles$3();
  const s = SIZES[size];
  return /*#__PURE__*/React.createElement("div", {
    className: classes.root
  }, /*#__PURE__*/React.createElement(CircularProgress, _extends$4({
    variant: "determinate",
    value: 100,
    className: classes.back,
    size: s,
    thickness: 3
  }, props)), /*#__PURE__*/React.createElement(CircularProgress, _extends$4({
    variant: "indeterminate",
    disableShrink: true,
    className: classes.front,
    size: s,
    thickness: 3
  }, props)));
}

const _excluded$1 = ["cancel", "translator"],
      _excluded2 = ["retry", "translator"];
const useStyles$2 = makeStyles$1(() => ({
  stripes: {
    '&::before': {
      position: 'absolute',
      height: '100%',
      width: '100%',
      top: 0,
      left: 0,
      content: '""',
      backgroundSize: '14.14px 14.14px',
      backgroundImage: 'linear-gradient(135deg, currentColor 10%, rgba(0,0,0,0) 10%, rgba(0,0,0,0) 50%, currentColor 50%, currentColor 59%, rgba(0,0,0,0) 60%, rgba(0,0,0,0) 103%)',
      opacity: 0.1
    }
  }
}));
function Cancel(_ref) {
  let {
    cancel,
    translator
  } = _ref,
      props = _objectWithoutProperties$1(_ref, _excluded$1);

  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Grid, {
    container: true,
    item: true,
    direction: "column",
    alignItems: "center",
    spacing: 2
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(Progress, null)), /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(Typography, {
    variant: "h6",
    align: "center",
    "data-tid": "update-active"
  }, translator.get('Object.Update.Active')))), /*#__PURE__*/React.createElement(Grid, _extends$4({
    item: true
  }, props), /*#__PURE__*/React.createElement(Button, {
    variant: "contained",
    onClick: cancel
  }, translator.get('Cancel'))));
}
function Retry(_ref2) {
  let {
    retry,
    translator
  } = _ref2,
      props = _objectWithoutProperties$1(_ref2, _excluded2);

  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(WarningTriangle, {
    style: {
      fontSize: '38px'
    }
  })), /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(Typography, {
    variant: "h6",
    align: "center",
    "data-tid": "update-cancelled"
  }, translator.get('Object.Update.Cancelled'))), /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, /*#__PURE__*/React.createElement(Button, _extends$4({
    variant: "contained",
    onClick: retry
  }, props), translator.get('Retry'))));
}
function LongRunningQuery(_ref3) {
  let {
    canCancel,
    canRetry,
    api
  } = _ref3;
  const {
    stripes,
    cancel,
    retry
  } = useStyles$2();
  const {
    translator
  } = useContext(InstanceContext);
  return /*#__PURE__*/React.createElement(Grid, {
    container: true,
    direction: "column",
    alignItems: "center",
    justifyContent: "center",
    className: stripes,
    style: {
      position: 'absolute',
      width: '100%',
      height: '100%',
      left: 0,
      top: 0
    },
    spacing: 2
  }, canCancel && /*#__PURE__*/React.createElement(Cancel, {
    cancel: api.cancel,
    translator: translator,
    className: cancel
  }), canRetry && /*#__PURE__*/React.createElement(Retry, {
    retry: api.retry,
    translator: translator,
    className: retry
  }));
}

/* eslint-disable react/jsx-props-no-spreading */
function Loading() {
  return /*#__PURE__*/React.createElement(Grid, {
    container: true,
    direction: "column",
    alignItems: "center",
    justifyContent: "center",
    style: {
      position: 'absolute',
      width: '100%',
      height: '100%',
      left: 0,
      top: 0
    },
    spacing: 2
  }, /*#__PURE__*/React.createElement(Progress, {
    size: "large"
  }));
}

const ITEM_WIDTH = 32;
const ITEM_SPACING = 4;
const DIVIDER = 1;
const NUMBER_OF_ITEMS = 6;
const MIN_WIDTH = (ITEM_WIDTH + ITEM_SPACING) * NUMBER_OF_ITEMS + DIVIDER + ITEM_SPACING;
/**
 * @interface
 * @extends HTMLElement
 * @since 2.0.0
 */

const CellTitle = {
  /** @type {'njs-cell-title'} */
  className: 'njs-cell-title'
};
/**
 * @interface
 * @extends HTMLElement
 * @since 2.0.0
 */

const CellSubTitle = {
  /** @type {'njs-cell-sub-title'} */
  className: 'njs-cell-sub-title'
};
const useStyles$1 = makeStyles$1(theme => ({
  containerStyle: {
    flexGrow: 0
  },
  containerTitleStyle: {
    paddingBottom: theme.spacing(1)
  }
}));

function Header(_ref) {
  let {
    layout,
    sn,
    anchorEl,
    hovering,
    focusHandler
  } = _ref;
  const showTitle = layout.showTitles && !!layout.title;
  const showSubtitle = layout.showTitles && !!layout.subtitle;
  const showInSelectionActions = layout.qSelectionInfo && layout.qSelectionInfo.qInSelections;
  const [actions, setActions] = useState$1([]);
  const {
    containerStyle,
    containerTitleStyle
  } = useStyles$1();
  const [containerRef, containerRect] = useRect$1();
  const [shouldShowPopoverToolbar, setShouldShowPopoverToolbar] = useState$1(false);
  useEffect$1(() => {
    if (!sn || !sn.component || !sn.component.isHooked) {
      return;
    }

    sn.component.observeActions(a => {
      setActions([...a, ...(sn && sn.selectionToolbar && sn.selectionToolbar.items || [])]);
    });
  }, [sn]);
  useEffect$1(() => {
    if (!containerRect) return;
    const {
      width
    } = containerRect;
    setShouldShowPopoverToolbar(width < MIN_WIDTH);
  }, [containerRect]);
  const showTitles = showTitle || showSubtitle;
  const classes = [containerStyle, ...(showTitles ? [containerTitleStyle] : [])];
  const showPopoverToolbar = (hovering || showInSelectionActions) && (shouldShowPopoverToolbar || !showTitles);
  const showToolbar = showTitles && !showPopoverToolbar && !shouldShowPopoverToolbar;
  const Toolbar = /*#__PURE__*/React.createElement(ActionsToolbar, {
    show: showToolbar,
    selections: {
      show: showInSelectionActions,
      api: sn.component.selections,
      onKeyDeactivate: focusHandler.refocusContent
    },
    actions: actions,
    popover: {
      show: showPopoverToolbar,
      anchorEl
    },
    focusHandler: focusHandler
  });
  return /*#__PURE__*/React.createElement(Grid, {
    ref: containerRef,
    item: true,
    container: true,
    wrap: "nowrap",
    className: classes.join(' ')
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true,
    zeroMinWidth: true,
    xs: true
  }, /*#__PURE__*/React.createElement(Grid, {
    container: true,
    wrap: "nowrap",
    direction: "column"
  }, showTitle && /*#__PURE__*/React.createElement(Typography, {
    variant: "h6",
    noWrap: true,
    className: CellTitle.className
  }, layout.title), showSubtitle && /*#__PURE__*/React.createElement(Typography, {
    variant: "body2",
    noWrap: true,
    className: CellSubTitle.className
  }, layout.subtitle))), /*#__PURE__*/React.createElement(Grid, {
    item: true
  }, Toolbar));
}

/**
 * @interface
 * @extends HTMLElement
 * @since 2.0.0
 */

const CellFooter = {
  /** @type {'njs-cell-footer'} */
  className: 'njs-cell-footer'
};
const useStyles = makeStyles$1(theme => ({
  itemStyle: {
    minWidth: 0,
    paddingTop: theme.spacing(1)
  }
}));

function Footer(_ref) {
  let {
    layout
  } = _ref;
  const {
    itemStyle
  } = useStyles();
  return layout && layout.showTitles && layout.footnote ? /*#__PURE__*/React.createElement(Grid, {
    container: true
  }, /*#__PURE__*/React.createElement(Grid, {
    item: true,
    className: itemStyle
  }, /*#__PURE__*/React.createElement(Typography, {
    noWrap: true,
    variant: "body2",
    className: CellFooter.className
  }, layout.footnote))) : null;
}

class RenderDebouncer {
  constructor() {
    this.timer = null;
    this.next = null;
    this.running = false;
  }

  start() {
    if (this.running) {
      return;
    }

    this.running = true;
    this.scheduleNext();
  }

  scheduleNext() {
    this.timer = setTimeout(() => {
      this.doNext();
    }, 10);
  }

  async doNext() {
    const fn = this.next;
    this.next = null;

    if (fn) {
      await fn();
      this.scheduleNext();
    } else {
      this.stop();
    }
  }

  schedule(fn) {
    this.next = fn;
    this.start();
  }

  stop() {
    if (!this.running) {
      return;
    }

    clearTimeout(this.timer);
    this.timer = null;
    this.running = false;
  }

}

/**
 * @interface VizElementAttributes
 * @extends NamedNodeMap
 * @property {string} data-render-count
 */

/**
 * @interface
 * @extends HTMLElement
 * @property {VizElementAttributes} attributes
 */

const VizElement = {
  /** @type {'njs-viz'} */
  className: 'njs-viz'
};

function Supernova(_ref) {
  let {
    sn,
    snOptions: options,
    snPlugins: plugins,
    layout,
    appLayout,
    halo
  } = _ref;
  const {
    component
  } = sn;
  const {
    theme: themeName,
    language,
    constraints,
    keyboardNavigation
  } = useContext(InstanceContext);
  const [renderDebouncer] = useState$1(() => new RenderDebouncer());
  const [isMounted, setIsMounted] = useState$1(false);
  const [renderCnt, setRenderCnt] = useState$1(0);
  const [containerRef, containerRect, containerNode] = useRect$1();
  const [snNode, setSnNode] = useState$1(null);
  const snRef = useCallback(ref => {
    if (!ref) {
      return;
    }

    setSnNode(ref);
  }, []); // Mount / Unmount

  useEffect$1(() => {
    if (!snNode) return undefined;
    component.created({
      options
    });
    component.mounted(snNode);
    setIsMounted(true);
    return () => {
      renderDebouncer.stop();
      component.willUnmount();
    };
  }, [snNode, component]); // Render

  useEffect$1(() => {
    if (!isMounted || !snNode || !containerRect) {
      return;
    } // TODO remove in-selections guard for old component API


    if (!component.isHooked && layout && layout.qSelectionInfo && layout.qSelectionInfo.qInSelections) {
      return;
    }

    renderDebouncer.schedule(() => {
      const permissions = [];

      if (!constraints.passive) {
        permissions.push('passive');
      }

      if (!constraints.active) {
        permissions.push('interact');
      }

      if (!constraints.select) {
        permissions.push('select');
      }

      if (halo.app && halo.app.session) {
        permissions.push('fetch');
      }

      return Promise.resolve(component.render({
        layout,
        options,
        plugins,
        embed: halo.public.nebbie,
        context: _objectSpread2({
          constraints,
          // halo.public.theme is a singleton so themeName is used as dep to make sure this effect is triggered
          theme: halo.public.theme,
          appLayout,
          keyboardNavigation
        }, component.isHooked ? {} : {
          logicalSize: sn.logicalSize({
            layout
          }),
          localeInfo: (appLayout || {}).qLocaleInfo,
          permissions
        })
      })).then(done => {
        if (done === false) {
          return;
        }

        if (renderCnt === 0 && typeof options.onInitialRender === 'function') {
          options.onInitialRender.call(null);
        }

        setRenderCnt(renderCnt + 1);
      });
    });
  }, [containerRect, options, plugins, snNode, containerNode, layout, appLayout, themeName, language, constraints, isMounted, keyboardNavigation]);
  return /*#__PURE__*/React.createElement("div", {
    ref: containerRef,
    "data-render-count": renderCnt,
    style: {
      position: 'relative',
      height: '100%'
    },
    className: VizElement.className
  }, /*#__PURE__*/React.createElement("div", {
    ref: snRef,
    style: {
      position: 'absolute',
      width: '100%',
      height: '100%'
    }
  }));
}

/**
 * @interface
 * @extends HTMLElement
 */

const CellElement = {
  /** @type {'njs-cell'} */
  className: 'njs-cell'
};

const initialState = err => ({
  loading: false,
  loaded: false,
  longRunningQuery: false,
  error: err ? {
    title: err.message
  } : null,
  sn: null,
  visualization: null
});

const contentReducer = (state, action) => {
  // console.log('content reducer', action.type);
  switch (action.type) {
    case 'LOADING':
      {
        return _objectSpread2(_objectSpread2({}, state), {}, {
          loading: true
        });
      }

    case 'LOADED':
      {
        return _objectSpread2(_objectSpread2({}, state), {}, {
          loaded: true,
          loading: false,
          longRunningQuery: false,
          error: null,
          sn: action.sn,
          visualization: action.visualization
        });
      }

    case 'RENDER':
      {
        return _objectSpread2(_objectSpread2({}, state), {}, {
          loaded: true,
          loading: false,
          longRunningQuery: false,
          error: null
        });
      }

    case 'LONG_RUNNING_QUERY':
      {
        return _objectSpread2(_objectSpread2({}, state), {}, {
          longRunningQuery: true
        });
      }

    case 'ERROR':
      {
        return _objectSpread2(_objectSpread2({}, state), {}, {
          loading: false,
          longRunningQuery: false,
          error: action.error
        });
      }

    default:
      {
        throw new Error("Unhandled type: ".concat(action.type));
      }
  }
};

function LoadingSn(_ref) {
  let {
    delay = 750
  } = _ref;
  const [showLoading, setShowLoading] = useState$1(false);
  useEffect$1(() => {
    const handle = setTimeout(() => setShowLoading(true), delay);
    return () => clearTimeout(handle);
  }, []);
  return showLoading ? /*#__PURE__*/React.createElement(Loading, null) : null;
}

const handleModal = _ref2 => {
  let {
    sn,
    layout,
    model
  } = _ref2;
  const selections = sn && sn.component && sn.component.selections;

  if (!selections || !selections.id || !model.id) {
    return;
  }

  if (selections.id === model.id) {
    if (layout && layout.qSelectionInfo && layout.qSelectionInfo.qInSelections && !selections.isModal()) {
      const {
        targets
      } = sn.generator.qae.data;
      const firstPropertyPath = targets[0].propertyPath;
      selections.goModal(firstPropertyPath);
    }

    if (!layout.qSelectionInfo || !layout.qSelectionInfo.qInSelections) {
      if (selections.isModal()) {
        selections.noModal();
      }
    }
  }
};

const filterData = d => d.qError ? d.qError.qErrorCode === 7005 : true;

const validateInfo = (min, info, getDescription, translatedError, translatedCalcCond) => [...Array(min).keys()].map(i => {
  const exists = !!(info && info[i]);
  const softError = exists && info[i].qError && info[i].qError.qErrorCode === 7005;
  const error = exists && !softError && info[i].qError;
  const delimiter = ':';
  const calcCondMsg = softError && info[i].qCalcCondMsg;
  const label = "".concat( // eslint-disable-next-line no-nested-ternary
  error ? translatedError : softError ? calcCondMsg || translatedCalcCond : exists && info[i].qFallbackTitle || '');
  const customDescription = getDescription(i);
  const description = customDescription ? "".concat(customDescription).concat(label.length ? delimiter : '') : null;
  return {
    description,
    label,
    missing: info && !exists && !error && i >= info.length || softError,
    error
  };
});

const getInfo = info => info && (Array.isArray(info) ? info : [info]) || [];

const validateTarget = (translator, layout, properties, def) => {
  const minD = def.dimensions.min();
  const minM = def.measures.min();
  const c = def.resolveLayout(layout);
  const reqDimErrors = validateInfo(minD, getInfo(c.qDimensionInfo), i => def.dimensions.description(properties, i), translator.get('Visualization.Invalid.Dimension'), translator.get('Visualization.UnfulfilledCalculationCondition'));
  const reqMeasErrors = validateInfo(minM, getInfo(c.qMeasureInfo), i => def.measures.description(properties, i), translator.get('Visualization.Invalid.Measure'), translator.get('Visualization.UnfulfilledCalculationCondition'));
  return {
    reqDimErrors,
    reqMeasErrors
  };
};

const validateCubes = (translator, targets, layout) => {
  let hasUnfulfilledErrors = false;
  let aggMinD = 0;
  let aggMinM = 0;
  let hasLayoutErrors = false;
  let hasLayoutUnfulfilledCalculcationCondition = false;
  const layoutErrors = [];

  for (let i = 0; i < targets.length; ++i) {
    const def = targets[i];
    const minD = def.dimensions.min();
    const minM = def.measures.min();
    const c = def.resolveLayout(layout);
    const d = getInfo(c.qDimensionInfo).filter(filterData); // Filter out optional calc conditions

    const m = getInfo(c.qMeasureInfo).filter(filterData); // Filter out optional calc conditions

    aggMinD += minD;
    aggMinM += minM;

    if (d.length < minD || m.length < minM) {
      hasUnfulfilledErrors = true;
    }

    if (c.qError) {
      hasLayoutErrors = true;
      hasLayoutUnfulfilledCalculcationCondition = c.qError.qErrorCode === 7005;
      const title = // eslint-disable-next-line no-nested-ternary
      hasLayoutUnfulfilledCalculcationCondition && c.qCalcCondMsg ? c.qCalcCondMsg : hasLayoutUnfulfilledCalculcationCondition ? translator.get('Visualization.UnfulfilledCalculationCondition') : translator.get('Visualization.LayoutError');
      layoutErrors.push({
        title,
        descriptions: []
      });
    }
  }

  return {
    hasUnfulfilledErrors,
    aggMinD,
    aggMinM,
    hasLayoutErrors,
    layoutErrors
  };
};

const validateTargets = async (translator, layout, _ref3, model) => {
  let {
    targets
  } = _ref3;
  // Use a flattened requirements structure to combine all targets
  const {
    hasUnfulfilledErrors,
    aggMinD,
    aggMinM,
    hasLayoutErrors,
    layoutErrors
  } = validateCubes(translator, targets, layout);
  const reqDimErrors = [];
  const reqMeasErrors = [];
  let loopCacheProperties = null;

  for (let i = 0; i < targets.length; ++i) {
    const def = targets[i];

    if (!hasLayoutErrors && hasUnfulfilledErrors) {
      // eslint-disable-next-line no-await-in-loop
      const properties = loopCacheProperties || (await model.getProperties());
      loopCacheProperties = properties;
      const res = validateTarget(translator, layout, properties, def);
      reqDimErrors.push(...res.reqDimErrors);
      reqMeasErrors.push(...res.reqMeasErrors);
    }
  }

  const fulfilledDims = reqDimErrors.filter(e => !(e.missing || e.error)).length;
  const reqDimErrorsTitle = translator.get('Visualization.Incomplete.Dimensions', [fulfilledDims, aggMinD]);
  const fulfilledMeas = reqMeasErrors.filter(e => !(e.missing || e.error)).length;
  const reqMeasErrorsTitle = translator.get('Visualization.Incomplete.Measures', [fulfilledMeas, aggMinM]);
  const reqErrors = [{
    title: reqDimErrorsTitle,
    descriptions: [...reqDimErrors]
  }, {
    title: reqMeasErrorsTitle,
    descriptions: [...reqMeasErrors]
  }];
  const showError = hasLayoutErrors || hasUnfulfilledErrors;
  const data = hasLayoutErrors ? layoutErrors : reqErrors;
  const title = hasLayoutErrors ? layoutErrors[0].title : translator.get('Visualization.Incomplete');
  return [showError, {
    title,
    data
  }];
};

const getType = async _ref4 => {
  let {
    types,
    name,
    version
  } = _ref4;
  const SN = await types.get({
    name,
    version
  }).supernova();
  return SN;
};

const loadType = async _ref5 => {
  let {
    dispatch,
    types,
    visualization,
    version,
    model,
    app,
    selections,
    nebbie,
    focusHandler
  } = _ref5;

  try {
    const snType = await getType({
      types,
      name: visualization,
      version
    });
    const sn = snType.create({
      model,
      app,
      selections,
      nebbie,
      focusHandler
    });
    return sn;
  } catch (err) {
    dispatch({
      type: 'ERROR',
      error: {
        title: err.message
      }
    });
  }

  return undefined;
};

const Cell = forwardRef((_ref6, ref) => {
  let {
    halo,
    model,
    initialSnOptions,
    initialSnPlugins,
    initialError,
    onMount,
    currentId
  } = _ref6;
  const {
    app,
    types
  } = halo;
  const {
    nebbie
  } = halo.public;
  const {
    disableCellPadding = false
  } = halo.context || {};
  const {
    translator,
    language,
    keyboardNavigation
  } = useContext(InstanceContext);
  const theme = useTheme$1();
  const [cellRef, cellRect, cellNode] = useRect$1();
  const [state, dispatch] = useReducer(contentReducer, initialState(initialError));
  const [layout, {
    validating,
    canCancel,
    canRetry
  }, longrunning] = useLayout$1(model);
  const [appLayout] = useAppLayout$1(app);
  const [contentRef, contentRect, contentNode] = useRect$1();
  const [snOptions, setSnOptions] = useState$1(initialSnOptions);
  const [snPlugins, setSnPlugins] = useState$1(initialSnPlugins);
  const [selections] = useObjectSelections(app, model);
  const [hovering, setHover] = useState$1(false);
  const hoveringDebouncer = useRef({
    enter: null,
    leave: null
  });
  const focusHandler = useRef({
    focusToolbarButton(last) {
      // eslint-disable-next-line react/no-this-in-sfc
      this.emit(last ? 'focus_toolbar_last' : 'focus_toolbar_first');
    }

  });
  useEffect$1(() => {
    eventmixin(focusHandler.current);
  }, []);

  focusHandler.current.blurCallback = resetFocus => {
    halo.root.toggleFocusOfCells();

    if (resetFocus && contentNode) {
      contentNode.focus();
    }
  };

  focusHandler.current.refocusContent = () => {
    state.sn.component && typeof state.sn.component.focus === 'function' && state.sn.component.focus();
  };

  const handleOnMouseEnter = () => {
    if (hoveringDebouncer.current.leave) {
      clearTimeout(hoveringDebouncer.current.leave);
    }

    if (hoveringDebouncer.enter) return;
    hoveringDebouncer.current.enter = setTimeout(() => {
      setHover(true);
      hoveringDebouncer.current.enter = null;
    }, 250);
  };

  const handleOnMouseLeave = () => {
    if (hoveringDebouncer.current.enter) {
      clearTimeout(hoveringDebouncer.current.enter);
    }

    if (hoveringDebouncer.current.leave) return;
    hoveringDebouncer.current.leave = setTimeout(() => {
      setHover(false);
      hoveringDebouncer.current.leave = null;
    }, 750);
  };

  const handleKeyDown = e => {
    // Enter or space
    if (['Enter', ' ', 'Spacebar'].includes(e.key)) {
      halo.root.toggleFocusOfCells(currentId);
    }
  };

  useEffect$1(() => {
    if (initialError || !appLayout || !layout) {
      return undefined;
    }

    const validate = async sn => {
      const [showError, error] = await validateTargets(translator, layout, sn.generator.qae.data, model);

      if (showError) {
        dispatch({
          type: 'ERROR',
          error
        });
      } else {
        dispatch({
          type: 'RENDER'
        });
      }

      handleModal({
        sn: state.sn,
        layout,
        model
      });
    };

    const load = async (visualization, version) => {
      dispatch({
        type: 'LOADING'
      });
      const sn = await loadType({
        dispatch,
        types,
        visualization,
        version,
        model,
        app,
        selections,
        nebbie,
        focusHandler: focusHandler.current
      });

      if (sn) {
        dispatch({
          type: 'LOADED',
          sn,
          visualization
        });
        onMount();
      }

      return undefined;
    }; // Validate if it's still the same type


    if (state.visualization === layout.visualization && state.sn) {
      validate(state.sn);
      return undefined;
    } // Load supernova


    const withVersion = types.getSupportedVersion(layout.visualization, layout.version);

    if (!withVersion) {
      dispatch({
        type: 'ERROR',
        error: {
          title: "Could not find a version of '".concat(layout.visualization, "' that supports current object version. Did you forget to register ").concat(layout.visualization, "?")
        }
      });
      return undefined;
    }

    load(layout.visualization, withVersion);
    return () => {};
  }, [types, state.sn, model, layout, appLayout, language]); // Long running query

  useEffect$1(() => {
    if (!validating) {
      return undefined;
    }

    const handle = setTimeout(() => dispatch({
      type: 'LONG_RUNNING_QUERY'
    }), 2000);
    return () => clearTimeout(handle);
  }, [validating]); // Expose cell ref api

  useImperativeHandle$1(ref, () => ({
    getQae() {
      return state.sn.generator.qae;
    },

    toggleFocus(active) {
      if (typeof state.sn.component.focus === 'function') {
        if (active) {
          state.sn.component.focus();
        } else {
          state.sn.component.blur();
        }
      }
    },

    setSnOptions,
    setSnPlugins,

    async takeSnapshot() {
      const {
        width,
        height
      } = cellRect; // clone layout to avoid mutation

      let clonedLayout = JSON.parse(JSON.stringify(layout));

      if (typeof state.sn.component.setSnapshotData === 'function') {
        clonedLayout = (await state.sn.component.setSnapshotData(clonedLayout)) || clonedLayout;
      }

      return {
        // TODO - this snapshot format needs to be documented and governed
        key: String(+Date.now()),
        meta: {
          language: translator.language(),
          theme: theme.name,
          appLayout,
          // direction: 'ltr',
          size: {
            width: Math.round(width),
            height: Math.round(height)
          }
        },
        layout: clonedLayout
      };
    },

    async exportImage() {
      if (typeof halo.config.snapshot.capture !== 'function') {
        throw new Error('Stardust embed has not been configured with snapshot.capture callback');
      }

      const snapshot = await this.takeSnapshot(); // eslint-disable-line

      return halo.config.snapshot.capture(snapshot);
    }

  }), [state.sn, contentRect, cellRect, layout, theme.name, appLayout]); // console.log('content', state);

  let Content = null;

  if (state.loading && !state.longRunningQuery) {
    Content = /*#__PURE__*/React.createElement(LoadingSn, null);
  } else if (state.error) {
    Content = /*#__PURE__*/React.createElement(Error$1, state.error);
  } else if (state.loaded) {
    Content = /*#__PURE__*/React.createElement(Supernova, {
      key: layout.visualization,
      sn: state.sn,
      halo: halo,
      snOptions: snOptions,
      snPlugins: snPlugins,
      layout: layout,
      appLayout: appLayout
    });
  }

  return /*#__PURE__*/React.createElement(Paper, {
    style: {
      position: 'relative',
      width: '100%',
      height: '100%',
      overflow: 'hidden'
    },
    elevation: 0,
    square: true,
    className: CellElement.className,
    ref: cellRef,
    onMouseEnter: handleOnMouseEnter,
    onMouseLeave: handleOnMouseLeave
  }, /*#__PURE__*/React.createElement(Grid, {
    container: true,
    direction: "column",
    spacing: 0,
    style: _objectSpread2(_objectSpread2({
      position: 'relative',
      width: '100%',
      height: '100%'
    }, !disableCellPadding ? {
      padding: theme.spacing(1)
    } : {}), state.longRunningQuery ? {
      opacity: '0.3'
    } : {})
  }, cellNode && layout && state.sn && /*#__PURE__*/React.createElement(Header, {
    layout: layout,
    sn: state.sn,
    anchorEl: cellNode,
    hovering: hovering,
    focusHandler: focusHandler.current
  }, "\xA0"), /*#__PURE__*/React.createElement(Grid, {
    tabIndex: keyboardNavigation ? 0 : -1,
    onKeyDown: keyboardNavigation ? handleKeyDown : null,
    item: true,
    xs: true,
    style: {
      height: '100%'
    },
    ref: contentRef
  }, Content), /*#__PURE__*/React.createElement(Footer, {
    layout: layout
  })), state.longRunningQuery && /*#__PURE__*/React.createElement(LongRunningQuery, {
    canCancel: canCancel,
    canRetry: canRetry,
    api: longrunning
  }));
});

function glue(_ref) {
  let {
    halo,
    element,
    model,
    initialSnOptions,
    initialSnPlugins,
    onMount,
    initialError
  } = _ref;
  const {
    root
  } = halo;
  const cellRef = React.createRef();
  const currentId = uid();
  const portal = ReactDOM.createPortal( /*#__PURE__*/React.createElement(Cell, {
    ref: cellRef,
    halo: halo,
    model: model,
    currentId: currentId,
    initialSnOptions: initialSnOptions,
    initialSnPlugins: initialSnPlugins,
    initialError: initialError,
    onMount: onMount
  }), element, model.id);

  const unmount = () => {
    root.remove(portal);
    model.removeListener('closed', unmount);
  };

  model.on('closed', unmount);
  root.add(portal); // Cannot use model.id as it is not unique in a given mashup

  root.addCell(currentId, cellRef);
  return [unmount, cellRef];
}

function isObject$1(v) {
  return v != null && !Array.isArray(v) && typeof v === 'object';
}

function isEqual(a, b) {
  if (isObject$1(a) && isObject$1(b)) {
    return JSON.stringify(a) === JSON.stringify(b);
  }

  if (Array.isArray(a) || Array.isArray(b)) {
    return false;
  }

  return a === b;
} // eslint-disable-next-line default-param-last


function getPatches() {
  let path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '/';
  let obj = arguments.length > 1 ? arguments[1] : undefined;
  let old = arguments.length > 2 ? arguments[2] : undefined;
  const patches = [];
  Object.keys(obj).forEach(prop => {
    const v = obj[prop];

    if (typeof old[prop] === 'object' && typeof v === 'object' && !Array.isArray(v)) {
      patches.push(...getPatches("".concat(path).concat(prop, "/"), obj[prop], old[prop]));
    } else if (!isEqual(v, old[prop])) {
      patches.push({
        qPath: path + prop,
        qOp: 'add',
        qValue: JSON.stringify(obj[prop])
      });
    }
  });
  return patches;
}

/**
 * An object literal containing meta information about the plugin and a function containing the plugin implementation.
 * @interface Plugin
 * @property {object} info Object that can hold various meta info about the plugin
 * @property {string} info.name The name of the plugin
 * @property {function} fn The implementation of the plugin. Input and return value is up to the plugin implementation to decide based on its purpose.
 * @experimental
 * @since 1.2.0
 * @example
 * const plugin = {
 *   info: {
 *     name: "example-plugin",
 *     type: "meta-type",
 *   },
 *   fn: () => {
 *     // Plugin implementation goes here
 *   }
 * };
 */
function validatePlugins(plugins) {
  if (!Array.isArray(plugins)) {
    throw new Error('Invalid plugin format: plugins should be an array!');
  }

  plugins.forEach(p => {
    if (typeof p !== 'object') {
      throw new Error('Invalid plugin format: a plugin should be an object');
    }

    if (typeof p.info !== 'object' || typeof p.info.name !== 'string') {
      throw new Error('Invalid plugin format: a plugin should have an info object containing a name');
    }

    if (typeof p.fn !== 'function') {
      throw new Error("Invalid plugin format: The plugin \"".concat(p.info.name, "\" has no \"fn\" function"));
    }
  });
}

const noopi = () => {};

function viz() {
  let {
    model,
    halo,
    initialError,
    onDestroy = async () => {}
  } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  let unmountCell = noopi;
  let cellRef = null;
  let mountedReference = null;
  let onMount = null;
  const mounted = new Promise(resolve => {
    onMount = resolve;
  });
  let initialSnOptions = {};
  let initialSnPlugins = [];

  const setSnOptions = async opts => {
    if (mountedReference) {
      (async () => {
        await mounted;
        cellRef.current.setSnOptions(_objectSpread2(_objectSpread2({}, initialSnOptions), opts));
      })();
    } else {
      // Handle setting options before mount
      initialSnOptions = _objectSpread2(_objectSpread2({}, initialSnOptions), opts);
    }
  };

  const setSnPlugins = async plugins => {
    validatePlugins(plugins);

    if (mountedReference) {
      (async () => {
        await mounted;
        cellRef.current.setSnPlugins(plugins);
      })();
    } else {
      // Handle setting plugins before mount
      initialSnPlugins = plugins;
    }
  };
  /**
   * @class
   * @alias Viz
   * @classdesc A controller to further modify a visualization after it has been rendered.
   * @example
   * const viz = await embed(app).render({
   *   element,
   *   type: 'barchart'
   * });
   * viz.destroy();
   */


  const api =
  /** @lends Viz# */
  {
    /**
     * The id of this visualization's generic object.
     * @type {string}
     */
    id: model.id,

    /**
     * Destroys the visualization and removes it from the the DOM.
     * @example
     * const viz = await embed(app).render({
     *   element,
     *   id: 'abc'
     * });
     * viz.destroy();
     */
    async destroy() {
      await onDestroy();
      unmountCell();
      unmountCell = noopi;
    },

    /**
     * Converts the visualization to a different registered type
     * @since 1.1.0
     * @param {string} newType - Which registered type to convert to.
     * @param {boolean=} forceUpdate - Whether to run setProperties or not, defaults to true.
     * @returns {Promise<object>} Promise object that resolves to the full property tree of the converted visualization.
     * @example
     * const viz = await embed(app).render({
     *   element,
     *   id: 'abc'
     * });
     * viz.convertTo('barChart');
     */
    async convertTo(newType) {
      let forceUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
      const propertyTree = await convertTo({
        halo,
        model,
        cellRef,
        newType
      });

      if (forceUpdate) {
        if (model.__snInterceptor) {
          await model.__snInterceptor.setProperties.call(model, propertyTree.qProperty);
        } else {
          await model.setProperties(propertyTree.qProperty);
        }
      }

      return propertyTree;
    },

    // ===== unexposed experimental API - use at own risk ======
    __DO_NOT_USE__: {
      mount(element) {
        if (mountedReference) {
          throw new Error('Already mounted');
        }

        mountedReference = element;
        [unmountCell, cellRef] = glue({
          halo,
          element,
          model,
          initialSnOptions,
          initialSnPlugins,
          initialError,
          onMount
        });
        return mounted;
      },

      async applyProperties(props) {
        const current = await model.getEffectiveProperties();
        const patches = getPatches('/', props, current);

        if (patches.length) {
          return model.applyPatches(patches, true);
        }

        return undefined;
      },

      options(opts) {
        setSnOptions(opts);
      },

      plugins(plugins) {
        setSnPlugins(plugins);
      },

      exportImage() {
        return cellRef.current.exportImage();
      },

      takeSnapshot() {
        return cellRef.current.takeSnapshot();
      },

      getModel() {
        return model;
      }

    } // old QVisualization API
    // close() {},
    // exportData() {},
    // exportImg() {},
    // exportPdf() {},
    // setOptions() {}, // applied soft patch
    // resize() {},
    // show() {},
    // toggleDataView() {},

  };
  return api;
}

/* eslint no-underscore-dangle:0 */
async function init(model, optional, halo, initialError) {
  let onDestroy = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : async () => {};
  const api = viz({
    model,
    halo,
    initialError,
    onDestroy
  });

  if (optional.options) {
    api.__DO_NOT_USE__.options(optional.options);
  }

  if (optional.plugins) {
    api.__DO_NOT_USE__.plugins(optional.plugins);
  }

  if (optional.element) {
    await api.__DO_NOT_USE__.mount(optional.element);
  }

  return api;
}

/**
 * @typedef {string | EngineAPI.INxDimension | EngineAPI.INxMeasure | LibraryField} Field
 */

/**
 * @interface CreateConfig
 * @description Rendering configuration for creating and rendering a new object
 * @extends BaseConfig
 * @property {string} type
 * @property {string=} version
 * @property {(Field[])=} fields
 * @property {EngineAPI.IGenericObjectProperties=} properties
 */

async function createSessionObject(_ref, halo) {
  let {
    type,
    version,
    fields,
    properties,
    options,
    plugins,
    element
  } = _ref;
  let mergedProps = {};
  let error;

  try {
    const t = halo.types.get({
      name: type,
      version
    });
    mergedProps = await t.initialProperties(properties);
    const sn = await t.supernova();

    if (fields) {
      populateData({
        sn,
        properties: mergedProps,
        fields
      }, halo);
    }

    if (properties && sn && sn.qae.properties.onChange) {
      sn.qae.properties.onChange.call({}, mergedProps);
    }
  } catch (e) {
    error = e; // minimal dummy object properties to allow it to be created
    // and rendered with the error

    mergedProps = {
      qInfo: {
        qType: type
      },
      visualization: type
    }; // console.error(e); // eslint-disable-line
  }

  const model = await halo.app.createSessionObject(mergedProps);
  modelStore.set(model.id, model);
  const unsubscribe = subscribe(model);

  const onDestroy = async () => {
    await halo.app.destroySessionObject(model.id);
    unsubscribe();
  };

  return init(model, {
    options,
    plugins,
    element
  }, halo, error, onDestroy);
}

/**
 * @interface BaseConfig
 * @description Basic rendering configuration for rendering an object
 * @property {HTMLElement} element
 * @property {object=} options
 * @property {Plugin[]} [plugins]
 */

/**
 * @interface GetConfig
 * @description Rendering configuration for rendering an existing object
 * @extends BaseConfig
 * @property {string} id
 */

async function getObject(_ref, halo) {
  let {
    id,
    options,
    plugins,
    element
  } = _ref;
  const key = "".concat(id);
  let rpc = rpcRequestModelStore.get(key);

  if (!rpc) {
    rpc = halo.app.getObject(id);
    rpcRequestModelStore.set(key, rpc);
  }

  const model = await rpc;
  modelStore.set(key, model);
  return init(model, {
    options,
    plugins,
    element
  }, halo);
}

function flagsFn () {
  let flags = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  /**
   * @interface Flags
   */
  return (
    /** @lends Flags */
    {
      /**
       * Checks whether the specified flag is enabled.
       * @param {string} flag - The value flag to check.
       * @returns {boolean} True if the specified flag is enabled, false otherwise.
       */
      isEnabled: f => flags[f] === true
    }
  );
}

/* eslint no-param-reassign: 0, no-restricted-globals: 0 */
const extend = extend$2.bind(null, true);
const JSONPatch = {};
const {
  isArray
} = Array;

function isObject(v) {
  return v != null && !Array.isArray(v) && typeof v === 'object';
}

function isUndef(v) {
  return typeof v === 'undefined';
}

function isFunction(v) {
  return typeof v === 'function';
}
/**
 * Generate an exact duplicate (with no references) of a specific value.
 *
 * @private
 * @param {Object} The value to duplicate
 * @returns {Object} a unique, duplicated value
 */


function generateValue(val) {
  if (val) {
    return extend({}, {
      val
    }).val;
  }

  return val;
}
/**
 * An additional type checker used to determine if the property is of internal
 * use or not a type that can be translated into JSON (like functions).
 *
 * @private
 * @param {Object} obj The object which has the property to check
 * @param {String} The property name to check
 * @returns {Boolean} Whether the property is deemed special or not
 */


function isSpecialProperty(obj, key) {
  return isFunction(obj[key]) || key.substring(0, 2) === '$$' || key.substring(0, 1) === '_';
}
/**
 * Finds the parent object from a JSON-Pointer ("/foo/bar/baz" = "bar" is "baz" parent),
 * also creates the object structure needed.
 *
 * @private
 * @param {Object} data The root object to traverse through
 * @param {String} The JSON-Pointer string to use when traversing
 * @returns {Object} The parent object
 */


function getParent(data, str) {
  const seperator = '/';
  const parts = str.substring(1).split(seperator).slice(0, -1);
  let numPart;
  parts.forEach((part, i) => {
    if (i === parts.length) {
      return;
    }

    numPart = +part;
    const newPart = !isNaN(numPart) ? [] : {};
    data[numPart || part] = isUndef(data[numPart || part]) ? newPart : data[part];
    data = data[numPart || part];
  });
  return data;
}
/**
 * Cleans an object of all its properties, unless they're deemed special or
 * cannot be removed by configuration.
 *
 * @private
 * @param {Object} obj The object to clean
 */


function emptyObject(obj) {
  Object.keys(obj).forEach(key => {
    const config = Object.getOwnPropertyDescriptor(obj, key);

    if (config.configurable && !isSpecialProperty(obj, key)) {
      delete obj[key];
    }
  });
}
/**
 * Compare an object with another, could be object, array, number, string, bool.
 * @private
 *
 * @param {Object} a The first object to compare
 * @param {Object} a The second object to compare
 * @returns {Boolean} Whether the objects are identical
 */


function compare(a, b) {
  let isIdentical = true;

  if (isObject(a) && isObject(b)) {
    if (Object.keys(a).length !== Object.keys(b).length) {
      return false;
    }

    Object.keys(a).forEach(key => {
      if (!compare(a[key], b[key])) {
        isIdentical = false;
      }
    });
    return isIdentical;
  }

  if (isArray(a) && isArray(b)) {
    if (a.length !== b.length) {
      return false;
    }

    for (let i = 0, l = a.length; i < l; i += 1) {
      if (!compare(a[i], b[i])) {
        return false;
      }
    }

    return true;
  }

  return a === b;
}
/**
 * Generates patches by comparing two arrays.
 *
 * @private
 * @param {Array} oldA The old (original) array, which will be patched
 * @param {Array} newA The new array, which will be used to compare against
 * @returns {Array} An array of patches (if any)
 */


function patchArray(original, newA, basePath) {
  let patches = [];
  const oldA = original.slice();
  let tmpIdx = -1;

  function findIndex(a, id, idx) {
    if (a[idx] && isUndef(a[idx].qInfo)) {
      return null;
    }

    if (a[idx] && a[idx].qInfo.qId === id) {
      // shortcut if identical
      return idx;
    }

    for (let ii = 0, ll = a.length; ii < ll; ii += 1) {
      if (a[ii] && a[ii].qInfo.qId === id) {
        return ii;
      }
    }

    return -1;
  }

  if (compare(newA, oldA)) {
    // array is unchanged
    return patches;
  }

  if (!isUndef(newA[0]) && isUndef(newA[0].qInfo)) {
    // we cannot create patches without unique identifiers, replace array...
    patches.push({
      op: 'replace',
      path: basePath,
      value: newA
    });
    return patches;
  }

  for (let i = oldA.length - 1; i >= 0; i -= 1) {
    tmpIdx = findIndex(newA, oldA[i].qInfo && oldA[i].qInfo.qId, i);

    if (tmpIdx === -1) {
      patches.push({
        op: 'remove',
        path: "".concat(basePath, "/").concat(i)
      });
      oldA.splice(i, 1);
    } else {
      patches = patches.concat(JSONPatch.generate(oldA[i], newA[tmpIdx], "".concat(basePath, "/").concat(i)));
    }
  }

  for (let i = 0, l = newA.length; i < l; i += 1) {
    tmpIdx = findIndex(oldA, newA[i].qInfo && newA[i].qInfo.qId);

    if (tmpIdx === -1) {
      patches.push({
        op: 'add',
        path: "".concat(basePath, "/").concat(i),
        value: newA[i]
      });
      oldA.splice(i, 0, newA[i]);
    } else if (tmpIdx !== i) {
      patches.push({
        op: 'move',
        path: "".concat(basePath, "/").concat(i),
        from: "".concat(basePath, "/").concat(tmpIdx)
      });
      oldA.splice(i, 0, oldA.splice(tmpIdx, 1)[0]);
    }
  }

  return patches;
}
/**
 * Generate an array of JSON-Patch:es following the JSON-Patch Specification Draft.
 *
 * See [specification draft](http://tools.ietf.org/html/draft-ietf-appsawg-json-patch-10)
 *
 * Does NOT currently generate patches for arrays (will replace them)
 * @private
 *
 * @param {Object} original The object to patch to
 * @param {Object} newData The object to patch from
 * @param {String} [basePath] The base path to use when generating the paths for
 *                            the patches (normally not used)
 * @returns {Array} An array of patches
 */


JSONPatch.generate = function generate(original, newData, basePath) {
  basePath = basePath || '';
  let patches = [];
  Object.keys(newData).forEach(key => {
    const val = generateValue(newData[key]);
    const oldVal = original[key];
    const tmpPath = "".concat(basePath, "/").concat(key);

    if (compare(val, oldVal) || isSpecialProperty(newData, key)) {
      return;
    }

    if (isUndef(oldVal)) {
      // property does not previously exist
      patches.push({
        op: 'add',
        path: tmpPath,
        value: val
      });
    } else if (isObject(val) && isObject(oldVal)) {
      // we need to generate sub-patches for this, since it already exist
      patches = patches.concat(JSONPatch.generate(oldVal, val, tmpPath));
    } else if (isArray(val) && isArray(oldVal)) {
      patches = patches.concat(patchArray(oldVal, val, tmpPath));
    } else {
      // it's a simple property (bool, string, number)
      patches.push({
        op: 'replace',
        path: "".concat(basePath, "/").concat(key),
        value: val
      });
    }
  });
  Object.keys(original).forEach(key => {
    if (isUndef(newData[key]) && !isSpecialProperty(original, key)) {
      // this property does not exist anymore
      patches.push({
        op: 'remove',
        path: "".concat(basePath, "/").concat(key)
      });
    }
  });
  return patches;
};
/**
 * Apply a list of patches to an object.
 * @private
 *
 * @param {Object} original The object to patch
 * @param {Array} patches The list of patches to apply
 */


JSONPatch.apply = function apply(original, patches) {
  patches.forEach(patch => {
    let parent = getParent(original, patch.path);
    let key = patch.path.split('/').splice(-1)[0];
    let target = key && isNaN(+key) ? parent[key] : parent[+key] || parent;
    const from = patch.from ? patch.from.split('/').splice(-1)[0] : null;

    if (patch.path === '/') {
      parent = null;
      target = original;
    }

    if (patch.op === 'add' || patch.op === 'replace') {
      if (isArray(parent)) {
        // trust indexes from patches, so don't replace the index if it's an add
        if (key === '-') {
          key = parent.length;
        }

        parent.splice(+key, patch.op === 'add' ? 0 : 1, patch.value);
      } else if (isArray(target) && isArray(patch.value)) {
        const newValues = patch.value.slice(); // keep array reference if possible...

        target.length = 0;
        target.push(...newValues);
      } else if (isObject(target) && isObject(patch.value)) {
        // keep object reference if possible...
        emptyObject(target);
        extend(target, patch.value);
      } else if (!parent) {
        throw new Error('Patchee is not an object we can patch');
      } else {
        // simple value
        parent[key] = patch.value;
      }
    } else if (patch.op === 'move') {
      const oldParent = getParent(original, patch.from);

      if (isArray(parent)) {
        parent.splice(+key, 0, oldParent.splice(+from, 1)[0]);
      } else {
        parent[key] = oldParent[from];
        delete oldParent[from];
      }
    } else if (patch.op === 'remove') {
      if (isArray(parent)) {
        parent.splice(+key, 1);
      } else {
        delete parent[key];
      }
    }
  });
};
/**
 * Deep clone an object.
 * @private
 *
 * @param {Object} obj The object to clone
 * @returns {Object} A new object identical to the `obj`
 */


JSONPatch.clone = function clone(obj) {
  return extend({}, obj);
};
/**
 * Creates a JSON-patch.
 * @private
 *
 * @param {String} op The operation of the patch. Available values: "add", "remove", "move"
 * @param {Object} [val] The value to set the `path` to. If `op` is `move`, `val`
 *                       is the "from JSON-path" path
 * @param {String} path The JSON-path for the property to change (e.g. "/qHyperCubeDef/columnOrder")
 * @returns {Object} A patch following the JSON-patch specification
 */


JSONPatch.createPatch = function createPatch(op, val, path) {
  const patch = {
    op: op.toLowerCase(),
    path
  };

  if (patch.op === 'move') {
    patch.from = val;
  } else if (typeof val !== 'undefined') {
    patch.value = val;
  }

  return patch;
};
/**
 * Apply the differences of two objects (keeping references if possible).
 * Identical to running `JSONPatch.apply(original, JSONPatch.generate(original, newData));`
 * @private
 *
 * @param {Object} original The object to update/patch
 * @param {Object} newData the object to diff against
 *
 * @example
 * var obj1 = { foo: [1,2,3], bar: { baz: true, qux: 1 } };
 * var obj2 = { foo: [4,5,6], bar: { baz: false } };
 * JSONPatch.updateObject(obj1, obj2);
 * // => { foo: [4,5,6], bar: { baz: false } };
 */


JSONPatch.updateObject = function updateObject(original, newData) {
  if (!Object.keys(original).length) {
    extend(original, newData);
    return;
  }

  JSONPatch.apply(original, JSONPatch.generate(original, newData));
};

const mixin$1 = obj => {
  /* eslint no-param-reassign: 0 */
  Object.keys(nodeEventEmitter.prototype).forEach(key => {
    obj[key] = nodeEventEmitter.prototype[key];
  });
  nodeEventEmitter.init(obj);
  return obj;
};

const actionWrapper = component => item => {
  const wrapped = mixin$1(_objectSpread2(_objectSpread2({}, item), {}, {
    action() {
      if (typeof item.action === 'function') {
        item.action.call(wrapped, component);
      }

      wrapped.emit('changed');
    },

    enabled() {
      if (typeof item.enabled === 'function') {
        return item.enabled.call(wrapped, component);
      }

      return true;
    },

    active: typeof item.active === 'function' ? function active() {
      return item.active.call(wrapped, component);
    } : undefined
  }));
  return wrapped;
};

function actionhero (_ref) {
  let {
    sn,
    component
  } = _ref;
  const actions = {};
  const selectionToolbarItems = [];
  const w = actionWrapper(component);
  ((sn.definition.selectionToolbar || {}).items || []).forEach(item => {
    const wrapped = w(item); // TODO - check if key exists

    actions[item.key] = wrapped;
    selectionToolbarItems.push(wrapped);
  });
  (sn.definition.actions || []).forEach(item => {
    const wrapped = w(item); // TODO - check if key exists

    actions[item.key] = wrapped;
  });
  return {
    actions,
    selectionToolbarItems,

    destroy() {
      selectionToolbarItems.length = 0;
    }

  };
}

/* eslint no-underscore-dangle: 0 */

/* eslint no-param-reassign: 0 */

/* eslint no-console: 0 */

/* eslint no-use-before-define: 0 */
// Hooks implementation heavily inspired by preact hooks
let currentComponent;
let currentIndex;

function depsChanged(prevDeps, deps) {
  if (!prevDeps) {
    return true;
  }

  if (deps.length !== prevDeps.length) {
    return true;
  }

  for (let i = 0; i < deps.length; i++) {
    if (prevDeps[i] !== deps[i]) {
      return true;
    }
  }

  return false;
}

function initiate(component) {
  let {
    explicitResize = false
  } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  component.__hooks = {
    obsolete: false,
    error: false,
    waitForData: false,
    chain: {
      promise: null,
      resolve: () => {}
    },
    list: [],
    snaps: [],
    actions: {
      list: []
    },
    pendingEffects: [],
    pendingLayoutEffects: [],
    pendingPromises: [],
    resizer: {
      setters: [],
      explicitResize
    },
    accessibility: {
      setter: null
    }
  };
}
function teardown(component) {
  flushPending(component.__hooks.list, true);
  component.__hooks.obsolete = true;
  component.__hooks.list.length = 0;
  component.__hooks.pendingEffects.length = 0;
  component.__hooks.pendingLayoutEffects.length = 0;
  component.__hooks.actions = null;
  component.__hooks.imperativeHandle = null;
  component.__hooks.resizer = null;
  component.__hooks.accessibility = null;
  component.__actionsDispatch = null;
  clearTimeout(component.__hooks.micro);
  cancelAnimationFrame(component.__hooks.macro);
}
async function run(component) {
  if (component.__hooks.obsolete) {
    return Promise.resolve();
  }

  currentIndex = -1;
  currentComponent = component;
  let num = -1;

  if (currentComponent.__hooks.initiated) {
    num = currentComponent.__hooks.list.length;
  }

  try {
    currentComponent.fn.call(null);
  } catch (e) {
    console.error(e);
  }

  currentComponent.__hooks.initiated = true;

  {
    if (num > -1 && num !== currentComponent.__hooks.list.length) {
      console.error('Detected a change in the order of hooks called.');
    }
  }

  const hooks = currentComponent.__hooks;
  dispatchActions(currentComponent);
  currentIndex = undefined;
  currentComponent = undefined;

  if (!hooks.chain.promise) {
    hooks.chain.promise = new Promise(resolve => {
      hooks.chain.resolve = resolve;
    });
  }

  flushMicro(hooks);
  scheduleMacro(hooks);
  return hooks.chain.promise;
}

function flushPending(list, skipUpdate) {
  try {
    list.forEach(fx => {
      // teardown existing
      typeof fx.teardown === 'function' ? fx.teardown() : null; // update

      if (!skipUpdate) {
        fx.teardown = fx.value[0]();
      }
    });
  } catch (e) {
    console.error(e);
  }

  list.length = 0;
}

function flushMicro(hooks) {
  flushPending(hooks.pendingLayoutEffects);
}

function flushMacro(hooks) {
  flushPending(hooks.pendingEffects);
  hooks.macro = null;
  maybeEndChain(hooks); // eslint-disable-line no-use-before-define
}

function maybeEndChain(hooks) {
  if (hooks.pendingPromises.length || hooks.micro || hooks.macro) {
    return;
  }

  hooks.chain.promise = null;
  hooks.chain.resolve(!hooks.waitForData);
}

function runSnaps(component, layout) {
  try {
    return Promise.all(component.__hooks.snaps.map(h => Promise.resolve(h.fn(layout)))).then(snaps => snaps[snaps.length - 1]);
  } catch (e) {
    console.error(e);
  }

  return Promise.resolve();
}
function getImperativeHandle(component) {
  return component.__hooks.imperativeHandle;
}

function dispatchActions(component) {
  if (component.__actionsDispatch && component.__hooks.actions.changed) {
    component.__actionsDispatch(component.__hooks.actions.list.slice());

    component.__hooks.actions.changed = false;
  }
}

function observeActions(component, callback) {
  component.__actionsDispatch = callback;

  if (component.__hooks) {
    component.__hooks.actions.changed = true;
    dispatchActions(component);
  }
}

function getHook(idx) {
  if (typeof currentComponent === 'undefined') {
    throw new Error('Invalid stardust hook call. Hooks can only be called inside a visualization component.');
  }

  const hooks = currentComponent.__hooks;

  if (idx >= hooks.list.length) {
    hooks.list.push({});
  }

  return hooks.list[idx];
}

function scheduleMicro(component) {
  if (component.__hooks.micro) {
    return;
  }

  component.__hooks.micro = setTimeout(() => {
    component.__hooks.micro = null;
    run(component);
  }, 0);
}

function scheduleMacro(hooks) {
  if (hooks.macro) {
    return;
  }

  hooks.macro = requestAnimationFrame(() => {
    flushMacro(hooks);
  });
}

function useInternalContext(name) {
  getHook(++currentIndex);
  const ctx = currentComponent.context;
  return ctx[name];
}

function updateRectOnNextRun(component) {
  if (component.__hooks) {
    component.__hooks.resizer.update = true;
  }
} // ========  EXTERNAL =========

function hook(cb) {
  return {
    __hooked: true,
    fn: cb,
    initiate,
    run,
    teardown,
    runSnaps,
    focus,
    blur,
    observeActions,
    getImperativeHandle,
    updateRectOnNextRun
  };
}
/**
 * @template S
 * @interface SetStateFn
 * @param {S|function(S):S} newState - The new state
 */

/**
 * Creates a stateful value.
 * @entry
 * @template S
 * @param {S|function():S} initialState - The initial state.
 * @returns {Array<S,SetStateFn<S>>} The value and a function to update it.
 * @example
 * import { useState } from '@nebula.js/stardust';
 * // ...
 * // initiate with simple primitive value
 * const [zoomed, setZoomed] = useState(false);
 *
 * // update
 * setZoomed(true);
 *
 * // lazy initiation
 * const [value, setValue] = useState(() => heavy());
 *
 */

function useState(initial) {
  const h = getHook(++currentIndex);

  if (!h.value) {
    // initiate
    h.component = currentComponent;

    const setState = s => {
      if (h.component.__hooks.obsolete) {
        {
          throw new Error('Calling setState on an unmounted component is a no-op and indicates a memory leak in your component.');
        }
      }

      const v = typeof s === 'function' ? s(h.value[0]) : s;

      if (v !== h.value[0]) {
        h.value[0] = v;
        scheduleMicro(h.component);
      }
    };

    h.value = [typeof initial === 'function' ? initial() : initial, setState];
  }

  return h.value;
}
/**
 * @typedef {function():(void | function():void)} EffectCallback
 */

/**
 * Triggers a callback function when a dependent value changes.
 * @entry
 * @param {EffectCallback} effect - The callback.
 * @param {Array<any>=} deps - The dependencies that should trigger the callback.
 * @example
 * import { useEffect } from '@nebula.js/stardust';
 * // ...
 * useEffect(() => {
 *   console.log('mounted');
 *   return () => {
 *     console.log('unmounted');
 *   };
 * }, []);
 */

function useEffect(cb, deps) {
  {
    if (typeof deps !== 'undefined' && !Array.isArray(deps)) {
      throw new Error('Invalid dependencies. Second argument must be an array.');
    }
  }

  const h = getHook(++currentIndex);

  if (depsChanged(h.value ? h.value[1] : undefined, deps)) {
    h.value = [cb, deps];

    if (currentComponent.__hooks.pendingEffects.indexOf(h) === -1) {
      currentComponent.__hooks.pendingEffects.push(h);
    }
  }
} // don't expose this hook since it's no different than useEffect except for the timing

function useLayoutEffect(cb, deps) {
  {
    if (typeof deps !== 'undefined' && !Array.isArray(deps)) {
      throw new Error('Invalid dependencies. Second argument must be an array.');
    }
  }

  const h = getHook(++currentIndex);

  if (depsChanged(h.value ? h.value[1] : undefined, deps)) {
    h.value = [cb, deps];

    currentComponent.__hooks.pendingLayoutEffects.push(h);
  }
}
/**
 * Creates a stateful value when a dependent changes.
 * @entry
 * @template T
 * @param {function():T} factory - The factory function.
 * @param {Array<any>} deps - The dependencies.
 * @returns {T} The value returned from the factory function.
 * @example
 * import { useMemo } from '@nebula.js/stardust';
 * // ...
 * const v = useMemo(() => {
 *   return doSomeHeavyCalculation();
 * }), []);
 */


function useMemo(fn, deps) {
  {
    if (!deps) {
      console.warn('useMemo called without dependencies.');
    }
  }

  const h = getHook(++currentIndex);

  if (depsChanged(h.value ? h.value[0] : undefined, deps)) {
    h.value = [deps, fn()];
  }

  return h.value[1];
}
/**
 * Runs a callback function when a dependent changes.
 * @entry
 * @template P
 * @param {function():Promise<P>} factory - The factory function that calls the promise.
 * @param {Array<any>=} deps - The dependencies.
 * @returns {Array<P,Error>} The resolved value.
 * @example
 * import { usePromise } from '@nebula.js/stardust';
 * import { useModel } from '@nebula.js/stardust';
 * // ...
 * const model = useModel();
 * const [resolved, rejected] = usePromise(() => model.getLayout(), []);
 */

function usePromise(p, deps) {
  const [obj, setObj] = useState(() => ({
    resolved: undefined,
    rejected: undefined,
    state: 'pending'
  }));
  const h = getHook(++currentIndex);

  if (!h.component) {
    h.component = currentComponent;
  }

  useLayoutEffect(() => {
    let canceled = false;

    h.teardown = () => {
      canceled = true;
      h.teardown = null;

      const idx = h.component.__hooks.pendingPromises.indexOf(h);

      if (idx > -1) {
        h.component.__hooks.pendingPromises.splice(idx, 1);
      }
    }; // setObj({
    //   ...obj,
    //   state: 'pending',
    // });


    p().then(v => {
      if (canceled) {
        return;
      }

      h.teardown && h.teardown();
      setObj({
        resolved: v,
        rejected: undefined,
        state: 'resolved'
      });
    }).catch(e => {
      if (canceled) {
        return;
      }

      h.teardown && h.teardown();
      setObj({
        resolved: undefined,
        rejected: e,
        state: 'resolved'
      });
    });

    h.component.__hooks.pendingPromises.push(h);

    return () => {
      h.teardown && h.teardown();
    };
  }, deps);
  return [obj.resolved, obj.rejected];
} // ---- composed hooks ------

/**
 * Gets the HTMLElement this visualization is rendered into.
 * @entry
 * @returns {HTMLElement}
 * @example
 * import { useElement } from '@nebula.js/stardust';
 * // ...
 * const el = useElement();
 * el.innerHTML = 'Hello!';
 */

function useElement() {
  return useInternalContext('element');
}
/**
 * @interface Rect
 * @property {number} top
 * @property {number} left
 * @property {number} width
 * @property {number} height
 */

/**
 * Gets the size of the HTMLElement the visualization is rendered into.
 * @entry
 * @returns {Rect} The size of the element.
 * @example
 * import { useRect } from '@nebula.js/stardust';
 * // ...
 * const rect = useRect();
 * useEffect(() => {
 *   console.log('resize');
 * }, [rect.width, rect.height])
 */

function useRect() {
  const element = useElement();
  const ref = currentComponent.__hooks.resizer;
  const [rect, setRect] = useState(() => {
    const {
      left,
      top,
      width,
      height
    } = element.getBoundingClientRect();
    return {
      left,
      top,
      width,
      height
    };
  });
  ref.current = rect;

  if (ref.setters.indexOf(setRect) === -1) {
    ref.setters.push(setRect);
  } // a forced resize should alwas update size regardless of whether ResizeObserver is available


  if (ref.update && ref.resize) {
    ref.update = false;
    ref.resize();
  }

  useLayoutEffect(() => {
    if (ref.initiated) {
      return undefined;
    }

    ref.initiated = true;

    const handleResize = () => {
      // TODO - should we really care about left/top?
      const {
        left,
        top,
        width,
        height
      } = element.getBoundingClientRect();
      const r = ref.current;

      if (r.width !== width || r.height !== height || r.left !== left || r.top !== top) {
        ref.setters.forEach(setR => setR({
          left,
          top,
          width,
          height
        }));
      }
    };

    ref.resize = () => {
      handleResize();
    }; // if component is configured with explicitResize, then we skip the
    // size observer and let the user control the resize themselves


    if (ref.explicitResize) {
      return () => {
        ref.resize = undefined;
      };
    } // TODO - document that ResizeObserver needs to be polyfilled by the user
    // if they want auto resize to work


    if (typeof ResizeObserver === 'function') {
      let resizeObserver = new ResizeObserver(handleResize);
      resizeObserver.observe(element);
      return () => {
        resizeObserver.unobserve(element);
        resizeObserver.disconnect(element);
        resizeObserver = null;
        ref.resize = undefined;
      };
    }

    return undefined;
  }, [element]);
  return rect;
}
/**
 * Gets the layout of the generic object associated with this visualization.
 * @entry
 * @returns {EngineAPI.IGenericObjectLayout}
 * @example
 * import { useLayout } from '@nebula.js/stardust';
 * // ...
 * const layout = useLayout();
 * console.log(layout);
 */

function useLayout() {
  return useInternalContext('layout');
}
/**
 * Gets the layout of the generic object associated with this visualization.
 *
 * Unlike the regular layout, a _stale_ layout is not changed when a generic object enters
 * the modal state. This is mostly notable in that `qSelectionInfo.qInSelections` in the layout is
 * always `false`.
 * The returned value from `useStaleLayout()` and `useLayout()` are identical when the object
 * is not in a modal state.
 * @entry
 * @returns {EngineAPI.IGenericObjectLayout}
 * @example
 * import { useStaleLayout } from '@nebula.js/stardust';
 * // ...
 * const staleLayout = useStaleLayout();
 * console.log(staleLayout);
 */

function useStaleLayout() {
  const layout = useInternalContext('layout');
  const [ref] = useState({
    current: layout
  });

  if (!layout.qSelectionInfo || !layout.qSelectionInfo.qInSelections) {
    ref.current = layout;
  }

  return ref.current;
}
/**
 * Gets the layout of the app associated with this visualization.
 * @entry
 * @returns {EngineAPI.INxAppLayout} The app layout
 * @example
 * import { useAppLayout } from '@nebula.js/stardust';
 * // ...
 * const appLayout = useAppLayout();
 * console.log(appLayout.qLocaleInfo);
 */

function useAppLayout() {
  return useInternalContext('appLayout');
}
/**
 * Gets the generic object API of the generic object connected to this visualization.
 * @entry
 * @returns {EngineAPI.IGenericObject|undefined}
 * @example
 * import { useModel } from '@nebula.js/stardust';
 * // ...
 * const model = useModel();
 * useEffect(() => {
 *   model.getInfo().then(info => {
 *     console.log(info);
 *   })
 * }, []);
 */

function useModel() {
  const model = useInternalContext('model');
  return model && model.session ? model : undefined;
}
/**
 * Gets the doc API.
 * @entry
 * @returns {EngineAPI.IApp|undefined} The doc API.
 * @example
 * import { useApp } from '@nebula.js/stardust';
 * // ...
 * const app = useApp();
 * useEffect(() => {
 *   app.getAllInfos().then(infos => {
 *     console.log(infos);
 *   })
 * }, []);
 */

function useApp() {
  const app = useInternalContext('app');
  return app && app.session ? app : undefined;
}
/**
 * Gets the global API.
 * @entry
 * @returns {EngineAPI.IGlobal|undefined} The global API.
 * @example
 * import { useGlobal } from '@nebula.js/stardust';
 *
 * // ...
 * const g = useGlobal();
 * useEffect(() => {
 *   g.engineVersion().then(version => {
 *     console.log(version);
 *   })
 * }, []);
 */

function useGlobal() {
  const global = useInternalContext('global');
  return global && global.session ? global : undefined;
}
/**
 * Gets the object selections.
 * @entry
 * @returns {ObjectSelections} The object selections.
 * @example
 * import { useSelections } from '@nebula.js/stardust';
 * import { useElement } from '@nebula.js/stardust';
 * import { useEffect } from '@nebula.js/stardust';
 * // ...
 * const selections = useSelections();
 * const element = useElement();
 * useEffect(() => {
 *   const onClick = () => {
 *     selections.begin('/qHyperCubeDef');
 *   };
 *   element.addEventListener('click', onClick);
 *   return () => {
 *     element.removeEventListener('click', onClick);
 *   };
 * }, []);
 */

function useSelections() {
  return useInternalContext('selections');
}
/**
 * Gets the theme.
 * @entry
 * @returns {Theme} The theme.
 * @example
 * import { useTheme } from '@nebula.js/stardust';
 *
 * const theme = useTheme();
 * console.log(theme.getContrastinColorTo('#ff0000'));
 */

function useTheme() {
  return useInternalContext('theme');
}
/**
 * Gets the embed instance used.
 * @entry
 * @experimental
 * @since 1.7.0
 * @returns {Embed} The embed instance used.
 * @example
 * import { useEmbed } from '@nebula.js/stardust';
 *
 * const embed = useEmbed();
 * embed.render(...)
 */

function useEmbed() {
  return useInternalContext('nebbie');
}
/**
 * Gets the translator.
 * @entry
 * @returns {Translator} The translator.
 * @example
 * import { useTranslator } from '@nebula.js/stardust';
 * // ...
 * const translator = useTranslator();
 * console.log(translator.get('SomeString'));
 */

function useTranslator() {
  return useInternalContext('translator');
}
/**
 * Gets the device type. ('touch' or 'desktop')
 * @entry
 * @returns {string} device type.
 * @example
 * import { useDeviceType } from '@nebula.js/stardust';
 * // ...
 * const deviceType = useDeviceType();
 * if (deviceType === 'touch') { ... };
 */

function useDeviceType() {
  return useInternalContext('deviceType');
}
/**
 * Gets the array of plugins provided when rendering the visualization.
 * @entry
 * @returns {Plugin[]} array of plugins.
 * @example
 * // provide plugins that can be used when rendering
 * embed(app).render({
 *   element,
 *   type: 'my-chart',
 *   plugins: [plugin]
 * });
 *
 * @example
 * // It's up to the chart implementation to make use of plugins in any way
 * import { usePlugins } from '@nebula.js/stardust';
 * // ...
 * const plugins = usePlugins();
 * plugins.forEach((plugin) => {
 *   // Invoke plugin
 *   plugin.fn();
 * });
 */

function usePlugins() {
  return useInternalContext('plugins');
}
/**
 * @template A
 * @interface ActionDefinition
 * @property {A} action
 * @property {boolean=} hidden
 * @property {boolean=} disabled
 * @property {object=} icon
 * @property {string} [icon.viewBox="0 0 16 16"]
 * @property {Array<object>} icon.shapes
 * @property {string} icon.shapes[].type
 * @property {object=} icon.shapes[].attrs
 */

/**
 * Registers a custom action.
 * @entry
 * @template A
 * @param {function():ActionDefinition<A>} factory
 * @param {Array<any>=} deps
 * @returns {A}
 *
 * @example
 * import { useAction } from '@nebula.js/stardust';
 * // ...
 * const [zoomed, setZoomed] = useState(false);
 * const act = useAction(() => ({
 *   hidden: false,
 *   disabled: zoomed,
 *   action() {
 *     setZoomed(prev => !prev);
 *   },
 *   icon: {}
 * }), [zoomed]);
 */

function useAction(fn, deps) {
  const [ref] = useState({
    action() {
      ref._config.action.call(null);
    }

  });

  if (!ref.component) {
    ref.component = currentComponent;

    currentComponent.__hooks.actions.list.push(ref);
  }

  useMemo(() => {
    const a = fn();
    ref._config = a;
    ref.active = a.active || false;
    ref.disabled = a.disabled || false;
    ref.hidden = a.hidden || false;
    ref.label = a.label || '';
    ref.getSvgIconShape = a.icon ? () => a.icon : undefined;
    ref.key = a.key || ref.component.__hooks.actions.list.length;
    ref.component.__hooks.actions.changed = true;
  }, deps);
  return ref.action;
}
/**
 * @interface Constraints
 * @property {boolean=} passive Whether or not passive constraints are on. Should block any passive interaction by users, ie: tooltips
 * @property {boolean=} active Whether or not active constraints are on. Should block any active interaction by users, ie: scroll, click
 * @property {boolean=} select Whether or not active select are on. Should block any selection action. Implied when active is true.
 */

/**
 * Gets the desired constraints that should be applied when rendering the visualization.
 *
 * The constraints are set on the embed configuration before the visualization is rendered
 * and should respected by you when implementing the visualization.
 * @entry
 * @returns {Constraints}
 * @example
 * // configure embed to disallow active interactions when rendering
 * embed(app, {
 *  context: {
 *    constraints: {
 *      active: true, // do not allow interactions
 *    }
 *  }
 * }).render({ element, id: 'sdfsdf' });
 *
 * @example
 * import { useConstraints } from '@nebula.js/stardust';
 * // ...
 * const constraints = useConstraints();
 * useEffect(() => {
 *   if (constraints.active) {
 *     // do not add any event listener if active constraint is set
 *     return undefined;
 *   }
 *   const listener = () => {};
 *   element.addEventListener('click', listener);
 *   return () => {
 *     element.removeEventListener('click', listener);
 *   };
 * }, [constraints])
 *
 */

function useConstraints() {
  return useInternalContext('constraints');
}
/**
 * Gets the options object provided when rendering the visualization.
 *
 * This is an empty object by default but enables customization of the visualization through this object.
 * Options are different from setting properties on the generic object in that options
 * are only temporary settings applied to the visualization when rendered.
 *
 * You have the responsibility to provide documentation of the options you support, if any.
 * @entry
 * @returns {object}
 *
 * @example
 * // when embedding the visualization, anything can be set in options
 * embed(app).render({
 *   element,
 *   type: 'my-chart',
 *   options: {
 *     showNavigation: true,
 *   }
 * });
 *
 * @example
 * // it is up to you use and implement the provided options
 * import { useOptions } from '@nebula.js/stardust';
 * import { useEffect } from '@nebula.js/stardust';
 * // ...
 * const options = useOptions();
 * useEffect(() => {
 *   if (!options.showNavigation) {
 *     // hide navigation
 *   } else {
 *     // show navigation
 *   }
 * }, [options.showNavigation]);
 *
 */

function useOptions() {
  return useInternalContext('options');
}
/**
 * TODO before making public - expose getImperativeHandle on Viz
 * Exposes an API to the external environment.
 *
 * This is an empty object by default, but enables you to provide a custom API of your visualization to
 * make it possible to control after it has been rendered.
 *
 * You can only use this hook once, calling it more than once is considered an error.
 * @entry
 * @private
 * @template T
 * @param {function():T} factory
 * @param {Array<any>=} deps
 * @example
 * import { useImperativeHandle } form '@nebula.js/stardust';
 * // ...
 * useImperativeHandle(() => ({
 *   resetZoom() {
 *     setZoomed(false);
 *   }
 * }));
 *
 * @example
 * // when embedding the visualization, you can get a handle to this API
 * // and use it to control the visualization
 * const ctl = await embed(app).render({
 *   element,
 *   type: 'my-chart',
 * });
 * ctl.getImperativeHandle().resetZoom();
 */

function useImperativeHandle(fn, deps) {
  const h = getHook(++currentIndex);

  if (!h.imperative) {
    {
      if (currentComponent.__hooks.imperativeHandle) {
        throw new Error('useImperativeHandle already used.');
      }
    }

    h.imperative = true;
  }

  if (depsChanged(h.value ? h.value[0] : undefined, deps)) {
    const v = fn();
    h.value = [deps, v];
    currentComponent.__hooks.imperativeHandle = v;
  }
}
/**
 * Registers a callback that is called when a snapshot is taken.
 * @entry
 * @param {function(EngineAPI.IGenericObjectLayout): Promise<EngineAPI.IGenericObjectLayout>} snapshotCallback
 * @example
 * import { onTakeSnapshot } from '@nebula.js/stardust';
 * import { useState } from '@nebula.js/stardust';
 * import { useLayout } from '@nebula.js/stardust';
 *
 * const layout = useLayout();
 * const [zoomed] = useState(layout.isZoomed || false);
 *
 * onTakeSnapshot((copyOfLayout) => {
 *   copyOfLayout.isZoomed = zoomed;
 *   return Promise.resolve(copyOfLayout);
 * });
 */

function onTakeSnapshot(cb) {
  const h = getHook(++currentIndex);

  if (!h.value) {
    h.value = 1;

    currentComponent.__hooks.snaps.push(h);
  }

  h.fn = cb;
}
/**
 * @interface RenderState
 * @property {any} pending
 * @property {any} restore
 */

/**
 * Gets render state instance.
 *
 * Used to update properties and get a new layout without triggering onInitialRender.
 * @entry
 * @experimental
 * @returns {RenderState} The render state.
 * @example
 * import { useRenderState } from '@nebula.js/stardust';
 *
 * const renderState = useRenderState();
 * useState(() => {
 *   if(needProperteisUpdate(...)) {
 *      useRenderState.pending();
 *      updateProperties(...);
 *   } else {
 *      useRenderState.restore();
 *      ...
 *   }
 * }, [...]);
 */

function useRenderState() {
  getHook(++currentIndex);
  const hooks = currentComponent.__hooks;
  return {
    pending: () => {
      hooks.waitForData = true;
    },
    restore: () => {
      hooks.waitForData = false;
    }
  };
}
/**
 * @experimental
 * @interface Keyboard
 * @property {boolean} enabled Whether or not Nebula handles keyboard navigation or not.
 * @property {boolean} active Set to true when the chart is activated, ie a user tabs to the chart and presses Enter or Space.
 * @property {function=} blur Function used by the visualization to tell Nebula to it wants to relinquish focus
 * @property {function=} focus Function used by the visualization to tell Nebula to it wants focus
 * @property {function=} focusSelection Function used by the visualization to tell Nebula to focus the selection toolbar
 */

/**
 * Gets the desired keyboard settings and status to applied when rendering the visualization.
 * A visualization should in general only have tab stops if either `keyboard.enabled` is false or if active is true.
 * This means that either Nebula isn't configured to handle keyboard input or the chart is currently focused.
 * Enabling or disabling keyboardNavigation are set on the embed configuration and
 * should be respected by the visualization.
 * @entry
 * @returns {Keyboard}
 * @example
 * // configure nebula to enable navigation between charts
 * embed(app, {
 *   context: {
 *     keyboardNavigation: true, // tell Nebula to handle navigation
 *   }
 * }).render({ element, id: 'sdfsdf' });
 *
 * @example
 * import { useKeyboard } from '@nebula.js/stardust';
 * // ...
 * const keyboard = useKeyboard();
 * useEffect(() => {
 *  // Set a tab stop on our button if in focus or if Nebulas navigation is disabled
 *  button.setAttribute('tabIndex', keyboard.active || !keyboard.enabled ? 0 : -1);
 *  // If navigation is enabled and focus has shifted, lets focus the button
 *  keyboard.enabled && keyboard.active && button.focus();
 * }, [keyboard])
 *
 */

function useKeyboard() {
  const keyboardNavigation = useInternalContext('keyboardNavigation');
  const focusHandler = useInternalContext('focusHandler');

  if (!currentComponent.__hooks.accessibility.exitFunction) {
    const exitFunction = function (resetFocus) {
      const acc = this.__hooks.accessibility;

      if (acc.enabled && acc.active) {
        blur(this);
        focusHandler && focusHandler.blurCallback && focusHandler.blurCallback(resetFocus);
      }
    }.bind(currentComponent);

    currentComponent.__hooks.accessibility.exitFunction = exitFunction;

    const focusFunction = function () {
      const acc = this.__hooks.accessibility;

      if (acc.enabled && !acc.active) {
        focusHandler && focusHandler.blurCallback && focusHandler.blurCallback(false);
        focus(this);
      }
    }.bind(currentComponent);

    currentComponent.__hooks.accessibility.focusFunction = focusFunction;

    const focusSelectionFunction = function (focusLast) {
      const acc = this.__hooks.accessibility;

      if (acc.enabled) {
        focusHandler && focusHandler.focusToolbarButton && focusHandler.focusToolbarButton(focusLast);
      }
    }.bind(currentComponent);

    currentComponent.__hooks.accessibility.focusSelectionFunction = focusSelectionFunction;
  }

  const focusFunc = currentComponent.__hooks.accessibility.focusFunction;
  const exitFunc = currentComponent.__hooks.accessibility.exitFunction;
  const focusSelectionFunc = currentComponent.__hooks.accessibility.focusSelectionFunction;
  const [acc, setAcc] = useState({
    active: false,
    enabled: keyboardNavigation,
    blur: exitFunc,
    focus: focusFunc,
    focusSelection: focusSelectionFunc
  });
  currentComponent.__hooks.accessibility.setter = setAcc;
  currentComponent.__hooks.accessibility.enabled = keyboardNavigation;
  useEffect(() => setAcc({
    active: false,
    enabled: keyboardNavigation,
    blur: exitFunc,
    focus: focusFunc,
    focusSelection: focusSelectionFunc
  }), [keyboardNavigation]);
  return acc;
}
function focus(component) {
  const acc = component.__hooks.accessibility;

  if (acc.active) {
    return;
  }

  acc.active = true;

  if (acc && acc.setter) {
    acc.setter({
      active: true,
      enabled: acc.enabled,
      blur: acc.exitFunction,
      focus: acc.focusFunction,
      focusSelection: acc.focusSelectionFunction
    });
  }
}
function blur(component) {
  const acc = component.__hooks.accessibility; // Incomplete/Invalid/Legacy viz hasn't been initialized with hooks

  if (!acc || !acc.active) {
    return;
  }

  acc.active = false;

  if (acc && acc.setter) {
    acc.setter({
      active: false,
      enabled: acc.enabled,
      blur: acc.exitFunction,
      focus: acc.focusFunction,
      focusSelection: acc.focusSelectionFunction
    });
  }
}

const defaultComponent = {
  app: null,
  model: null,
  actions: null,
  selections: null,
  created: () => {},
  mounted: () => {},
  render: () => {},
  resize: () => {},
  willUnmount: () => {},
  destroy: () => {},
  emit: () => {},
  getViewState: () => {},

  // temporary
  observeActions() {},

  setSnapshotData: snapshot => Promise.resolve(snapshot)
};
const reservedKeys = Object.keys(defaultComponent);

const mixin = obj => {
  /* eslint no-param-reassign: 0 */
  Object.keys(nodeEventEmitter.prototype).forEach(key => {
    obj[key] = nodeEventEmitter.prototype[key];
  });
  nodeEventEmitter.init(obj);
  return obj;
};

function createWithHooks(generator, opts, galaxy) {
  {
    if (generator.component.run !== run) {
      // eslint-disable-next-line no-console
      console.warn('Detected multiple supernova modules, this might cause problems.');
    }
  }

  const qGlobal = opts.app && opts.app.session ? opts.app.session.getObjectApi({
    handle: -1
  }) : undefined; // use a deep comparison for 'small' objects

  let hasRun = false;
  const current = {};
  const deepCheck = ['appLayout', 'constraints'];
  const forcedConstraints = {}; // select should be a constraint when a real model is not available

  if (!opts.model || !opts.model.session) {
    forcedConstraints.select = true;
  }

  const c = {
    context: {
      // static values that are not expected to
      // change during the component's life
      // --------------------
      model: opts.model,
      app: opts.app,
      global: qGlobal,
      selections: opts.selections,
      nebbie: opts.nebbie,
      element: undefined,
      // set on mount
      // ---- singletons ----
      deviceType: galaxy.deviceType,
      theme: undefined,
      translator: galaxy.translator,
      // --- dynamic values ---
      layout: {},
      appLayout: {},
      keyboardNavigation: opts.keyboardNavigation,
      focusHandler: opts.focusHandler,
      constraints: forcedConstraints,
      options: {},
      plugins: []
    },
    fn: generator.component.fn,

    created() {},

    mounted(element) {
      this.context.element = element;
      generator.component.initiate(c, {
        explicitResize: !!opts.explicitResize
      });
    },

    render(r) {
      let changed = !hasRun || false;

      if (r) {
        if (r.layout && r.layout !== this.context.layout) {
          changed = true;
          this.context.layout = r.layout;
        }

        if (r.context && r.context.theme) {
          // changed is set further down only if the name is different
          this.context.theme = r.context.theme;
        } // false equals undefined, so we to cast to bool here


        if (r.context && !!r.context.keyboardNavigation !== !!this.context.keyboardNavigation) {
          this.context.keyboardNavigation = !!r.context.keyboardNavigation;
          changed = true;
        }

        if (r.context && r.context.focusHandler) {
          // Needs to be added here due to how the client renders
          this.context.focusHandler = r.context.focusHandler;
        }

        if (r.options) {
          // options could contain anything including methods, classes, cyclical references
          // so we can't use JSON parse for comparison.
          // but we can do a shallow reference check on the first level to check if
          // options have changed. if it has changed then create a new reference for
          // the options object to ensure callbacks are triggered
          const op = {};
          let opChanged = false;
          Object.keys(r.options).forEach(key => {
            op[key] = r.options[key];

            if (this.context.options[key] !== r.options[key]) {
              opChanged = true;
            }
          });

          if (opChanged) {
            this.context.options = op;
            changed = true;
          }
        }

        if (r.plugins) {
          let pluginsChanged = this.context.plugins.length !== r.plugins.length;
          r.plugins.forEach((plugin, index) => {
            if (this.context.plugins[index] !== plugin) {
              pluginsChanged = true;
            }
          });

          if (pluginsChanged) {
            this.context.plugins = [...r.plugins];
            changed = true;
          }
        } // do a deep check on 'small' objects


        deepCheck.forEach(key => {
          const ref = r.context;

          if (ref && Object.prototype.hasOwnProperty.call(ref, key)) {
            let s = JSON.stringify(ref[key]);

            if (key === 'constraints') {
              s = JSON.stringify(_objectSpread2(_objectSpread2({}, ref[key]), forcedConstraints));
            }

            if (s !== current[key]) {
              changed = true;
              current[key] = s; // create new object reference to ensure useEffect/useMemo/useCallback
              // is triggered if the object is used a dependency

              this.context[key] = JSON.parse(s);
            }
          }
        });
      } else {
        changed = true;
      } // theme and translator are singletons so their reference won't change, we do
      // however need to observe if their internal content has changed (name, language) and
      // trigger an update if they have


      if (this.context.theme && this.context.theme.name() !== current.themeName) {
        changed = true;
        current.themeName = this.context.theme.name();
      }

      if (this.context.translator.language() !== current.language) {
        changed = true;
        current.language = c.context.translator.language();
      } // TODO - observe what hooks are used, and only trigger run if values associated
      // with those hooks have changed, i.e. if layout has changed but useLayout() isn't called
      // then there is no need to call run


      if (changed) {
        hasRun = true;
        this.currentResult = generator.component.run(this);
        return this.currentResult;
      }

      return this.currentResult || Promise.resolve();
    },

    resize() {
      // resize should never really by necesseary since the ResizeObserver
      // in useRect observes changes on the size of the object, the only time it might
      // be necessary is on IE 11 when the object is resized without the window changing size
      generator.component.updateRectOnNextRun(this);
      return this.render();
    },

    willUnmount() {
      generator.component.teardown(this);
    },

    setSnapshotData(layout) {
      return generator.component.runSnaps(this, layout);
    },

    focus() {
      generator.component.focus(this);
    },

    blur() {
      generator.component.blur(this);
    },

    getImperativeHandle() {
      return generator.component.getImperativeHandle(this);
    },

    destroy() {},

    observeActions(callback) {
      generator.component.observeActions(this, callback);
    },

    isHooked: true
  };
  deepCheck.forEach(key => {
    current[key] = JSON.stringify(c.context[key]);
  });
  current.themeName = c.context.theme ? c.context.theme.name() : undefined;
  current.language = c.context.translator ? c.context.translator.language() : undefined;
  Object.assign(c, {
    selections: opts.selections
  });
  return [c, null];
}

function createClassical(generator, opts) {
  {
    // eslint-disable-next-line no-console
    console.warn('Obsolete API - time to get hooked!');
  }

  const componentInstance = _objectSpread2({}, defaultComponent);

  mixin(componentInstance);
  const userInstance = {
    emit() {
      componentInstance.emit(...arguments);
    }

  };
  Object.keys(generator.component || {}).forEach(key => {
    if (reservedKeys.indexOf(key) !== -1) {
      componentInstance[key] = generator.component[key].bind(userInstance);
    } else {
      userInstance[key] = generator.component[key];
    }
  });
  const hero = actionhero({
    sn: generator,
    component: userInstance
  });
  const qGlobal = opts.app && opts.app.session ? opts.app.session.getObjectApi({
    handle: -1
  }) : null;
  Object.assign(userInstance, {
    model: opts.model,
    app: opts.app,
    global: qGlobal,
    selections: opts.selections,
    actions: hero.actions
  });
  Object.assign(componentInstance, {
    actions: hero.actions,
    model: opts.model,
    app: opts.app,
    selections: opts.selections
  });
  return [componentInstance, hero];
}

function create$2(generator, opts, galaxy) {
  if (typeof generator.component === 'function') {
    generator.component = hook(generator.component);
  }

  const [componentInstance, hero] = generator.component && generator.component.__hooked ? createWithHooks(generator, opts, galaxy) : createClassical(generator, opts);
  const teardowns = [];

  if (opts.model.__snInterceptor) {
    // remove old hook - happens only when proper cleanup hasn't been done
    opts.model.__snInterceptor.teardown();
  }

  if (generator.qae.properties.onChange) {
    // TODO - handle multiple sn
    // TODO - check privileges
    opts.model.__snInterceptor = {
      setProperties: opts.model.setProperties,
      applyPatches: opts.model.applyPatches,
      teardown: undefined
    };

    opts.model.setProperties = function setProperties() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      generator.qae.properties.onChange.call({
        model: opts.model
      }, ...args);
      return opts.model.__snInterceptor.setProperties.call(this, ...args);
    };

    opts.model.applyPatches = function applyPatches(qPatches, qSoftPatch) {
      const method = qSoftPatch ? 'getEffectiveProperties' : 'getProperties';
      return opts.model[method]().then(currentProperties => {
        // apply patches to current props
        const original = JSONPatch.clone(currentProperties);
        const patches = qPatches.map(p => ({
          op: p.qOp,
          value: JSON.parse(p.qValue),
          path: p.qPath
        }));
        JSONPatch.apply(currentProperties, patches);
        generator.qae.properties.onChange.call({
          model: opts.model
        }, currentProperties); // calculate new patches from after change

        const newPatches = JSONPatch.generate(original, currentProperties).map(p => ({
          qOp: p.op,
          qValue: JSON.stringify(p.value),
          qPath: p.path
        }));
        return opts.model.__snInterceptor.applyPatches.call(this, newPatches, qSoftPatch);
      });
    };

    opts.model.__snInterceptor.teardown = () => {
      opts.model.setProperties = opts.model.__snInterceptor.setProperties;
      delete opts.model.__snInterceptor;
    };

    teardowns.push(opts.model.__snInterceptor.teardown);
  }

  return {
    generator,
    component: componentInstance,
    selectionToolbar: {
      items: hero ? hero.selectionToolbarItems : []
    },

    destroy() {
      teardowns.forEach(t => t());
    },

    logicalSize: generator.definition.logicalSize || (() => false)
  };
}

const noop = () => {};
/**
 * @function importProperties
 * @description Imports properties for a chart with a hypercube.
 * @since 1.1.0
 * @param {Object} args
 * @param {ExportFormat} args.exportFormat The export object which is the output of exportProperties.
 * @param {Object=} args.initialProperties Initial properties of the target chart.
 * @param {Object=} args.dataDefinition Data definition of the target chart.
 * @param {Object=} args.defaultPropertyValues Default values for a number of properties of the target chart.
 * @param {string} args.hypercubePath Reference to the qHyperCubeDef.
 * @returns {Object} A properties tree
 */

/**
 * @function exportProperties
 * @description Exports properties for a chart with a hypercube.
 * @since 1.1.0
 * @param {Object} args
 * @param {Object} args.propertyTree
 * @param {string} args.hypercubePath Reference to the qHyperCubeDef.
 * @returns {ExportFormat}
 */

/**
 * @interface QAEDefinition
 * @property {EngineAPI.IGenericObjectProperties=} properties
 * @property {object=} data
 * @property {DataTarget[]} data.targets
 * @property {importProperties=} importProperties
 * @property {exportProperties=} exportProperties
 */

/**
 * @interface DataTarget
 * @property {string} path
 * @property {FieldTarget<EngineAPI.INxDimension>=} dimensions
 * @property {FieldTarget<EngineAPI.INxMeasure>=} measures
 */

/**
 * @callback fieldTargetAddedCallback
 * @template T
 * @param {T} field
 * @param {EngineAPI.IGenericObjectProperties} properties
 */

/**
 * @callback fieldTargetRemovedCallback
 * @template T
 * @param {T} field
 * @param {EngineAPI.IGenericObjectProperties} properties
 * @param {number} index
 */

/**
 * @interface FieldTarget
 * @template T
 * @property {function():number} [min]
 * @property {function():number} [max]
 * @property {fieldTargetAddedCallback<T>} [added]
 * @property {fieldTargetRemovedCallback<T>} [removed]
 */


function fallback(x, value) {
  if (typeof x === 'undefined') {
    return () => value;
  }

  return () => x;
}

function defFn(input) {
  const def = input || {};
  return {
    min: typeof def.min === 'function' ? def.min : fallback(def.min, 0),
    max: typeof def.max === 'function' ? def.max : fallback(def.max, 1000),
    added: def.added || def.add || noop,
    // TODO - deprecate add in favour of added
    description: def.description || noop,
    moved: def.moved || def.move || noop,
    removed: def.removed || def.remove || noop,
    replaced: def.replaced || def.replace || noop,
    isDefined: () => !!input
  };
}

const resolveValue = (data, reference, defaultValue) => {
  const steps = reference.split('/');
  let dataContainer = data;

  if (dataContainer === undefined) {
    return defaultValue;
  }

  for (let i = 0; i < steps.length; ++i) {
    if (steps[i] === '') {
      continue; // eslint-disable-line no-continue
    }

    if (typeof dataContainer[steps[i]] === 'undefined') {
      return defaultValue;
    }

    dataContainer = dataContainer[steps[i]];
  }

  return dataContainer;
};

function target(def) {
  const propertyPath = def.path || '/qHyperCubeDef';
  const layoutPath = propertyPath.slice(0, -3);

  if (/\/(qHyperCube|qListObject)$/.test(layoutPath) === false) {
    const d = layoutPath.includes('/qHyperCube') ? 'qHyperCubeDef' : 'qListObjectDef';
    throw new Error("Incorrect definition for ".concat(d, " at ").concat(propertyPath, ". Valid paths include /qHyperCubeDef or /qListObjectDef, e.g. data/qHyperCubeDef"));
  }

  return {
    propertyPath,
    layoutPath,
    resolveLayout: layout => resolveValue(layout, layoutPath, {}),
    dimensions: defFn(def.dimensions),
    measures: defFn(def.measures)
  };
}

function qae() {
  let def = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  let initial = def.properties || {};
  let onChange;

  if (def.properties && (def.properties.initial || def.properties.onChange)) {
    initial = def.properties.initial;
    onChange = def.properties.onChange;
  }

  const q = {
    properties: {
      initial,
      onChange
    },
    data: {
      targets: ((def.data || {}).targets || []).map(target)
    },
    exportProperties: def.exportProperties,
    importProperties: def.importProperties
  };
  return q;
}

/**
 * The entry point for defining a visualization.
 * @interface Visualization
 * @param {Galaxy} galaxy
 * @returns {VisualizationDefinition}
 * @example
 * import { useElement, useLayout } from '@nebula.js/stardust';
 *
 * export default function() {
 *   return {
 *     qae: {
 *       properties: {
 *         dude: 'Heisenberg',
 *       }
 *     },
 *     component() {
 *       const el = useElement();
 *       const layout = useLayout();
 *       el.innerHTML = `What's my name? ${layout.dude}!!!`;
 *     }
 *   };
 * }
 */

/**
 * @interface VisualizationDefinition
 * @property {QAEDefinition} qae
 * @property {function():void} component
 */

/**
 * @interface snGenerator
 * @param {Visualization} Sn
 * @param {Galaxy} galaxy
 * @returns {generator}
 * @private
 */

function generatorFn(UserSN, galaxy) {
  let sn; // TODO validate galaxy API

  if (typeof UserSN === 'function') {
    sn = UserSN(galaxy);
  } else {
    sn = UserSN;
  }
  /**
   * @alias generator
   * @private
   */


  const generator =
  /** @lends generator */
  {
    /**
     * @type {QAE}
     */
    qae: qae(sn.qae),

    /**
     * @type {SnComponent}
     */
    component: sn.component || {},

    /**
     * @param {object} p
     * @param {EnigmaAppModel} p.app
     * @param {EnigmaObjectModel} p.model
     * @param {ObjectSelections} p.selections
     */
    create(params) {
      const ss = create$2(generator, params, galaxy);
      return ss;
    },

    definition: {}
  };
  Object.keys(sn).forEach(key => {
    if (!generator[key]) {
      generator.definition[key] = sn[key];
    }
  });
  return generator;
}

var semver = {exports: {}};

(function (module, exports) {
	exports = module.exports = SemVer;

	var debug;
	/* istanbul ignore next */
	if (typeof process === 'object' &&
	    process.env &&
	    process.env.NODE_DEBUG &&
	    /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
	  debug = function () {
	    var args = Array.prototype.slice.call(arguments, 0);
	    args.unshift('SEMVER');
	    console.log.apply(console, args);
	  };
	} else {
	  debug = function () {};
	}

	// Note: this is the semver.org version of the spec that it implements
	// Not necessarily the package version of this code.
	exports.SEMVER_SPEC_VERSION = '2.0.0';

	var MAX_LENGTH = 256;
	var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
	  /* istanbul ignore next */ 9007199254740991;

	// Max safe segment length for coercion.
	var MAX_SAFE_COMPONENT_LENGTH = 16;

	// The actual regexps go on exports.re
	var re = exports.re = [];
	var src = exports.src = [];
	var t = exports.tokens = {};
	var R = 0;

	function tok (n) {
	  t[n] = R++;
	}

	// The following Regular Expressions can be used for tokenizing,
	// validating, and parsing SemVer version strings.

	// ## Numeric Identifier
	// A single `0`, or a non-zero digit followed by zero or more digits.

	tok('NUMERICIDENTIFIER');
	src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*';
	tok('NUMERICIDENTIFIERLOOSE');
	src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+';

	// ## Non-numeric Identifier
	// Zero or more digits, followed by a letter or hyphen, and then zero or
	// more letters, digits, or hyphens.

	tok('NONNUMERICIDENTIFIER');
	src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*';

	// ## Main Version
	// Three dot-separated numeric identifiers.

	tok('MAINVERSION');
	src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' +
	                   '(' + src[t.NUMERICIDENTIFIER] + ')\\.' +
	                   '(' + src[t.NUMERICIDENTIFIER] + ')';

	tok('MAINVERSIONLOOSE');
	src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' +
	                        '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' +
	                        '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')';

	// ## Pre-release Version Identifier
	// A numeric identifier, or a non-numeric identifier.

	tok('PRERELEASEIDENTIFIER');
	src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] +
	                            '|' + src[t.NONNUMERICIDENTIFIER] + ')';

	tok('PRERELEASEIDENTIFIERLOOSE');
	src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] +
	                                 '|' + src[t.NONNUMERICIDENTIFIER] + ')';

	// ## Pre-release Version
	// Hyphen, followed by one or more dot-separated pre-release version
	// identifiers.

	tok('PRERELEASE');
	src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] +
	                  '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))';

	tok('PRERELEASELOOSE');
	src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] +
	                       '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))';

	// ## Build Metadata Identifier
	// Any combination of digits, letters, or hyphens.

	tok('BUILDIDENTIFIER');
	src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+';

	// ## Build Metadata
	// Plus sign, followed by one or more period-separated build metadata
	// identifiers.

	tok('BUILD');
	src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] +
	             '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))';

	// ## Full Version String
	// A main version, followed optionally by a pre-release version and
	// build metadata.

	// Note that the only major, minor, patch, and pre-release sections of
	// the version string are capturing groups.  The build metadata is not a
	// capturing group, because it should not ever be used in version
	// comparison.

	tok('FULL');
	tok('FULLPLAIN');
	src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] +
	                  src[t.PRERELEASE] + '?' +
	                  src[t.BUILD] + '?';

	src[t.FULL] = '^' + src[t.FULLPLAIN] + '$';

	// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
	// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
	// common in the npm registry.
	tok('LOOSEPLAIN');
	src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] +
	                  src[t.PRERELEASELOOSE] + '?' +
	                  src[t.BUILD] + '?';

	tok('LOOSE');
	src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$';

	tok('GTLT');
	src[t.GTLT] = '((?:<|>)?=?)';

	// Something like "2.*" or "1.2.x".
	// Note that "x.x" is a valid xRange identifer, meaning "any version"
	// Only the first item is strictly required.
	tok('XRANGEIDENTIFIERLOOSE');
	src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
	tok('XRANGEIDENTIFIER');
	src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*';

	tok('XRANGEPLAIN');
	src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' +
	                   '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
	                   '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
	                   '(?:' + src[t.PRERELEASE] + ')?' +
	                   src[t.BUILD] + '?' +
	                   ')?)?';

	tok('XRANGEPLAINLOOSE');
	src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
	                        '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
	                        '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
	                        '(?:' + src[t.PRERELEASELOOSE] + ')?' +
	                        src[t.BUILD] + '?' +
	                        ')?)?';

	tok('XRANGE');
	src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$';
	tok('XRANGELOOSE');
	src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$';

	// Coercion.
	// Extract anything that could conceivably be a part of a valid semver
	tok('COERCE');
	src[t.COERCE] = '(^|[^\\d])' +
	              '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +
	              '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
	              '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
	              '(?:$|[^\\d])';
	tok('COERCERTL');
	re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g');

	// Tilde ranges.
	// Meaning is "reasonably at or greater than"
	tok('LONETILDE');
	src[t.LONETILDE] = '(?:~>?)';

	tok('TILDETRIM');
	src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+';
	re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g');
	var tildeTrimReplace = '$1~';

	tok('TILDE');
	src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$';
	tok('TILDELOOSE');
	src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$';

	// Caret ranges.
	// Meaning is "at least and backwards compatible with"
	tok('LONECARET');
	src[t.LONECARET] = '(?:\\^)';

	tok('CARETTRIM');
	src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+';
	re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g');
	var caretTrimReplace = '$1^';

	tok('CARET');
	src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$';
	tok('CARETLOOSE');
	src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$';

	// A simple gt/lt/eq thing, or just "" to indicate "any version"
	tok('COMPARATORLOOSE');
	src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$';
	tok('COMPARATOR');
	src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$';

	// An expression to strip any whitespace between the gtlt and the thing
	// it modifies, so that `> 1.2.3` ==> `>1.2.3`
	tok('COMPARATORTRIM');
	src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] +
	                      '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')';

	// this one has to use the /g flag
	re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g');
	var comparatorTrimReplace = '$1$2$3';

	// Something like `1.2.3 - 1.2.4`
	// Note that these all use the loose form, because they'll be
	// checked against either the strict or loose comparator form
	// later.
	tok('HYPHENRANGE');
	src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' +
	                   '\\s+-\\s+' +
	                   '(' + src[t.XRANGEPLAIN] + ')' +
	                   '\\s*$';

	tok('HYPHENRANGELOOSE');
	src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' +
	                        '\\s+-\\s+' +
	                        '(' + src[t.XRANGEPLAINLOOSE] + ')' +
	                        '\\s*$';

	// Star ranges basically just allow anything at all.
	tok('STAR');
	src[t.STAR] = '(<|>)?=?\\s*\\*';

	// Compile to actual regexp objects.
	// All are flag-free, unless they were created above with a flag.
	for (var i = 0; i < R; i++) {
	  debug(i, src[i]);
	  if (!re[i]) {
	    re[i] = new RegExp(src[i]);
	  }
	}

	exports.parse = parse;
	function parse (version, options) {
	  if (!options || typeof options !== 'object') {
	    options = {
	      loose: !!options,
	      includePrerelease: false
	    };
	  }

	  if (version instanceof SemVer) {
	    return version
	  }

	  if (typeof version !== 'string') {
	    return null
	  }

	  if (version.length > MAX_LENGTH) {
	    return null
	  }

	  var r = options.loose ? re[t.LOOSE] : re[t.FULL];
	  if (!r.test(version)) {
	    return null
	  }

	  try {
	    return new SemVer(version, options)
	  } catch (er) {
	    return null
	  }
	}

	exports.valid = valid;
	function valid (version, options) {
	  var v = parse(version, options);
	  return v ? v.version : null
	}

	exports.clean = clean;
	function clean (version, options) {
	  var s = parse(version.trim().replace(/^[=v]+/, ''), options);
	  return s ? s.version : null
	}

	exports.SemVer = SemVer;

	function SemVer (version, options) {
	  if (!options || typeof options !== 'object') {
	    options = {
	      loose: !!options,
	      includePrerelease: false
	    };
	  }
	  if (version instanceof SemVer) {
	    if (version.loose === options.loose) {
	      return version
	    } else {
	      version = version.version;
	    }
	  } else if (typeof version !== 'string') {
	    throw new TypeError('Invalid Version: ' + version)
	  }

	  if (version.length > MAX_LENGTH) {
	    throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')
	  }

	  if (!(this instanceof SemVer)) {
	    return new SemVer(version, options)
	  }

	  debug('SemVer', version, options);
	  this.options = options;
	  this.loose = !!options.loose;

	  var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);

	  if (!m) {
	    throw new TypeError('Invalid Version: ' + version)
	  }

	  this.raw = version;

	  // these are actually numbers
	  this.major = +m[1];
	  this.minor = +m[2];
	  this.patch = +m[3];

	  if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
	    throw new TypeError('Invalid major version')
	  }

	  if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
	    throw new TypeError('Invalid minor version')
	  }

	  if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
	    throw new TypeError('Invalid patch version')
	  }

	  // numberify any prerelease numeric ids
	  if (!m[4]) {
	    this.prerelease = [];
	  } else {
	    this.prerelease = m[4].split('.').map(function (id) {
	      if (/^[0-9]+$/.test(id)) {
	        var num = +id;
	        if (num >= 0 && num < MAX_SAFE_INTEGER) {
	          return num
	        }
	      }
	      return id
	    });
	  }

	  this.build = m[5] ? m[5].split('.') : [];
	  this.format();
	}

	SemVer.prototype.format = function () {
	  this.version = this.major + '.' + this.minor + '.' + this.patch;
	  if (this.prerelease.length) {
	    this.version += '-' + this.prerelease.join('.');
	  }
	  return this.version
	};

	SemVer.prototype.toString = function () {
	  return this.version
	};

	SemVer.prototype.compare = function (other) {
	  debug('SemVer.compare', this.version, this.options, other);
	  if (!(other instanceof SemVer)) {
	    other = new SemVer(other, this.options);
	  }

	  return this.compareMain(other) || this.comparePre(other)
	};

	SemVer.prototype.compareMain = function (other) {
	  if (!(other instanceof SemVer)) {
	    other = new SemVer(other, this.options);
	  }

	  return compareIdentifiers(this.major, other.major) ||
	         compareIdentifiers(this.minor, other.minor) ||
	         compareIdentifiers(this.patch, other.patch)
	};

	SemVer.prototype.comparePre = function (other) {
	  if (!(other instanceof SemVer)) {
	    other = new SemVer(other, this.options);
	  }

	  // NOT having a prerelease is > having one
	  if (this.prerelease.length && !other.prerelease.length) {
	    return -1
	  } else if (!this.prerelease.length && other.prerelease.length) {
	    return 1
	  } else if (!this.prerelease.length && !other.prerelease.length) {
	    return 0
	  }

	  var i = 0;
	  do {
	    var a = this.prerelease[i];
	    var b = other.prerelease[i];
	    debug('prerelease compare', i, a, b);
	    if (a === undefined && b === undefined) {
	      return 0
	    } else if (b === undefined) {
	      return 1
	    } else if (a === undefined) {
	      return -1
	    } else if (a === b) {
	      continue
	    } else {
	      return compareIdentifiers(a, b)
	    }
	  } while (++i)
	};

	SemVer.prototype.compareBuild = function (other) {
	  if (!(other instanceof SemVer)) {
	    other = new SemVer(other, this.options);
	  }

	  var i = 0;
	  do {
	    var a = this.build[i];
	    var b = other.build[i];
	    debug('prerelease compare', i, a, b);
	    if (a === undefined && b === undefined) {
	      return 0
	    } else if (b === undefined) {
	      return 1
	    } else if (a === undefined) {
	      return -1
	    } else if (a === b) {
	      continue
	    } else {
	      return compareIdentifiers(a, b)
	    }
	  } while (++i)
	};

	// preminor will bump the version up to the next minor release, and immediately
	// down to pre-release. premajor and prepatch work the same way.
	SemVer.prototype.inc = function (release, identifier) {
	  switch (release) {
	    case 'premajor':
	      this.prerelease.length = 0;
	      this.patch = 0;
	      this.minor = 0;
	      this.major++;
	      this.inc('pre', identifier);
	      break
	    case 'preminor':
	      this.prerelease.length = 0;
	      this.patch = 0;
	      this.minor++;
	      this.inc('pre', identifier);
	      break
	    case 'prepatch':
	      // If this is already a prerelease, it will bump to the next version
	      // drop any prereleases that might already exist, since they are not
	      // relevant at this point.
	      this.prerelease.length = 0;
	      this.inc('patch', identifier);
	      this.inc('pre', identifier);
	      break
	    // If the input is a non-prerelease version, this acts the same as
	    // prepatch.
	    case 'prerelease':
	      if (this.prerelease.length === 0) {
	        this.inc('patch', identifier);
	      }
	      this.inc('pre', identifier);
	      break

	    case 'major':
	      // If this is a pre-major version, bump up to the same major version.
	      // Otherwise increment major.
	      // 1.0.0-5 bumps to 1.0.0
	      // 1.1.0 bumps to 2.0.0
	      if (this.minor !== 0 ||
	          this.patch !== 0 ||
	          this.prerelease.length === 0) {
	        this.major++;
	      }
	      this.minor = 0;
	      this.patch = 0;
	      this.prerelease = [];
	      break
	    case 'minor':
	      // If this is a pre-minor version, bump up to the same minor version.
	      // Otherwise increment minor.
	      // 1.2.0-5 bumps to 1.2.0
	      // 1.2.1 bumps to 1.3.0
	      if (this.patch !== 0 || this.prerelease.length === 0) {
	        this.minor++;
	      }
	      this.patch = 0;
	      this.prerelease = [];
	      break
	    case 'patch':
	      // If this is not a pre-release version, it will increment the patch.
	      // If it is a pre-release it will bump up to the same patch version.
	      // 1.2.0-5 patches to 1.2.0
	      // 1.2.0 patches to 1.2.1
	      if (this.prerelease.length === 0) {
	        this.patch++;
	      }
	      this.prerelease = [];
	      break
	    // This probably shouldn't be used publicly.
	    // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
	    case 'pre':
	      if (this.prerelease.length === 0) {
	        this.prerelease = [0];
	      } else {
	        var i = this.prerelease.length;
	        while (--i >= 0) {
	          if (typeof this.prerelease[i] === 'number') {
	            this.prerelease[i]++;
	            i = -2;
	          }
	        }
	        if (i === -1) {
	          // didn't increment anything
	          this.prerelease.push(0);
	        }
	      }
	      if (identifier) {
	        // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
	        // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
	        if (this.prerelease[0] === identifier) {
	          if (isNaN(this.prerelease[1])) {
	            this.prerelease = [identifier, 0];
	          }
	        } else {
	          this.prerelease = [identifier, 0];
	        }
	      }
	      break

	    default:
	      throw new Error('invalid increment argument: ' + release)
	  }
	  this.format();
	  this.raw = this.version;
	  return this
	};

	exports.inc = inc;
	function inc (version, release, loose, identifier) {
	  if (typeof (loose) === 'string') {
	    identifier = loose;
	    loose = undefined;
	  }

	  try {
	    return new SemVer(version, loose).inc(release, identifier).version
	  } catch (er) {
	    return null
	  }
	}

	exports.diff = diff;
	function diff (version1, version2) {
	  if (eq(version1, version2)) {
	    return null
	  } else {
	    var v1 = parse(version1);
	    var v2 = parse(version2);
	    var prefix = '';
	    if (v1.prerelease.length || v2.prerelease.length) {
	      prefix = 'pre';
	      var defaultResult = 'prerelease';
	    }
	    for (var key in v1) {
	      if (key === 'major' || key === 'minor' || key === 'patch') {
	        if (v1[key] !== v2[key]) {
	          return prefix + key
	        }
	      }
	    }
	    return defaultResult // may be undefined
	  }
	}

	exports.compareIdentifiers = compareIdentifiers;

	var numeric = /^[0-9]+$/;
	function compareIdentifiers (a, b) {
	  var anum = numeric.test(a);
	  var bnum = numeric.test(b);

	  if (anum && bnum) {
	    a = +a;
	    b = +b;
	  }

	  return a === b ? 0
	    : (anum && !bnum) ? -1
	    : (bnum && !anum) ? 1
	    : a < b ? -1
	    : 1
	}

	exports.rcompareIdentifiers = rcompareIdentifiers;
	function rcompareIdentifiers (a, b) {
	  return compareIdentifiers(b, a)
	}

	exports.major = major;
	function major (a, loose) {
	  return new SemVer(a, loose).major
	}

	exports.minor = minor;
	function minor (a, loose) {
	  return new SemVer(a, loose).minor
	}

	exports.patch = patch;
	function patch (a, loose) {
	  return new SemVer(a, loose).patch
	}

	exports.compare = compare;
	function compare (a, b, loose) {
	  return new SemVer(a, loose).compare(new SemVer(b, loose))
	}

	exports.compareLoose = compareLoose;
	function compareLoose (a, b) {
	  return compare(a, b, true)
	}

	exports.compareBuild = compareBuild;
	function compareBuild (a, b, loose) {
	  var versionA = new SemVer(a, loose);
	  var versionB = new SemVer(b, loose);
	  return versionA.compare(versionB) || versionA.compareBuild(versionB)
	}

	exports.rcompare = rcompare;
	function rcompare (a, b, loose) {
	  return compare(b, a, loose)
	}

	exports.sort = sort;
	function sort (list, loose) {
	  return list.sort(function (a, b) {
	    return exports.compareBuild(a, b, loose)
	  })
	}

	exports.rsort = rsort;
	function rsort (list, loose) {
	  return list.sort(function (a, b) {
	    return exports.compareBuild(b, a, loose)
	  })
	}

	exports.gt = gt;
	function gt (a, b, loose) {
	  return compare(a, b, loose) > 0
	}

	exports.lt = lt;
	function lt (a, b, loose) {
	  return compare(a, b, loose) < 0
	}

	exports.eq = eq;
	function eq (a, b, loose) {
	  return compare(a, b, loose) === 0
	}

	exports.neq = neq;
	function neq (a, b, loose) {
	  return compare(a, b, loose) !== 0
	}

	exports.gte = gte;
	function gte (a, b, loose) {
	  return compare(a, b, loose) >= 0
	}

	exports.lte = lte;
	function lte (a, b, loose) {
	  return compare(a, b, loose) <= 0
	}

	exports.cmp = cmp;
	function cmp (a, op, b, loose) {
	  switch (op) {
	    case '===':
	      if (typeof a === 'object')
	        a = a.version;
	      if (typeof b === 'object')
	        b = b.version;
	      return a === b

	    case '!==':
	      if (typeof a === 'object')
	        a = a.version;
	      if (typeof b === 'object')
	        b = b.version;
	      return a !== b

	    case '':
	    case '=':
	    case '==':
	      return eq(a, b, loose)

	    case '!=':
	      return neq(a, b, loose)

	    case '>':
	      return gt(a, b, loose)

	    case '>=':
	      return gte(a, b, loose)

	    case '<':
	      return lt(a, b, loose)

	    case '<=':
	      return lte(a, b, loose)

	    default:
	      throw new TypeError('Invalid operator: ' + op)
	  }
	}

	exports.Comparator = Comparator;
	function Comparator (comp, options) {
	  if (!options || typeof options !== 'object') {
	    options = {
	      loose: !!options,
	      includePrerelease: false
	    };
	  }

	  if (comp instanceof Comparator) {
	    if (comp.loose === !!options.loose) {
	      return comp
	    } else {
	      comp = comp.value;
	    }
	  }

	  if (!(this instanceof Comparator)) {
	    return new Comparator(comp, options)
	  }

	  debug('comparator', comp, options);
	  this.options = options;
	  this.loose = !!options.loose;
	  this.parse(comp);

	  if (this.semver === ANY) {
	    this.value = '';
	  } else {
	    this.value = this.operator + this.semver.version;
	  }

	  debug('comp', this);
	}

	var ANY = {};
	Comparator.prototype.parse = function (comp) {
	  var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
	  var m = comp.match(r);

	  if (!m) {
	    throw new TypeError('Invalid comparator: ' + comp)
	  }

	  this.operator = m[1] !== undefined ? m[1] : '';
	  if (this.operator === '=') {
	    this.operator = '';
	  }

	  // if it literally is just '>' or '' then allow anything.
	  if (!m[2]) {
	    this.semver = ANY;
	  } else {
	    this.semver = new SemVer(m[2], this.options.loose);
	  }
	};

	Comparator.prototype.toString = function () {
	  return this.value
	};

	Comparator.prototype.test = function (version) {
	  debug('Comparator.test', version, this.options.loose);

	  if (this.semver === ANY || version === ANY) {
	    return true
	  }

	  if (typeof version === 'string') {
	    try {
	      version = new SemVer(version, this.options);
	    } catch (er) {
	      return false
	    }
	  }

	  return cmp(version, this.operator, this.semver, this.options)
	};

	Comparator.prototype.intersects = function (comp, options) {
	  if (!(comp instanceof Comparator)) {
	    throw new TypeError('a Comparator is required')
	  }

	  if (!options || typeof options !== 'object') {
	    options = {
	      loose: !!options,
	      includePrerelease: false
	    };
	  }

	  var rangeTmp;

	  if (this.operator === '') {
	    if (this.value === '') {
	      return true
	    }
	    rangeTmp = new Range(comp.value, options);
	    return satisfies(this.value, rangeTmp, options)
	  } else if (comp.operator === '') {
	    if (comp.value === '') {
	      return true
	    }
	    rangeTmp = new Range(this.value, options);
	    return satisfies(comp.semver, rangeTmp, options)
	  }

	  var sameDirectionIncreasing =
	    (this.operator === '>=' || this.operator === '>') &&
	    (comp.operator === '>=' || comp.operator === '>');
	  var sameDirectionDecreasing =
	    (this.operator === '<=' || this.operator === '<') &&
	    (comp.operator === '<=' || comp.operator === '<');
	  var sameSemVer = this.semver.version === comp.semver.version;
	  var differentDirectionsInclusive =
	    (this.operator === '>=' || this.operator === '<=') &&
	    (comp.operator === '>=' || comp.operator === '<=');
	  var oppositeDirectionsLessThan =
	    cmp(this.semver, '<', comp.semver, options) &&
	    ((this.operator === '>=' || this.operator === '>') &&
	    (comp.operator === '<=' || comp.operator === '<'));
	  var oppositeDirectionsGreaterThan =
	    cmp(this.semver, '>', comp.semver, options) &&
	    ((this.operator === '<=' || this.operator === '<') &&
	    (comp.operator === '>=' || comp.operator === '>'));

	  return sameDirectionIncreasing || sameDirectionDecreasing ||
	    (sameSemVer && differentDirectionsInclusive) ||
	    oppositeDirectionsLessThan || oppositeDirectionsGreaterThan
	};

	exports.Range = Range;
	function Range (range, options) {
	  if (!options || typeof options !== 'object') {
	    options = {
	      loose: !!options,
	      includePrerelease: false
	    };
	  }

	  if (range instanceof Range) {
	    if (range.loose === !!options.loose &&
	        range.includePrerelease === !!options.includePrerelease) {
	      return range
	    } else {
	      return new Range(range.raw, options)
	    }
	  }

	  if (range instanceof Comparator) {
	    return new Range(range.value, options)
	  }

	  if (!(this instanceof Range)) {
	    return new Range(range, options)
	  }

	  this.options = options;
	  this.loose = !!options.loose;
	  this.includePrerelease = !!options.includePrerelease;

	  // First, split based on boolean or ||
	  this.raw = range;
	  this.set = range.split(/\s*\|\|\s*/).map(function (range) {
	    return this.parseRange(range.trim())
	  }, this).filter(function (c) {
	    // throw out any that are not relevant for whatever reason
	    return c.length
	  });

	  if (!this.set.length) {
	    throw new TypeError('Invalid SemVer Range: ' + range)
	  }

	  this.format();
	}

	Range.prototype.format = function () {
	  this.range = this.set.map(function (comps) {
	    return comps.join(' ').trim()
	  }).join('||').trim();
	  return this.range
	};

	Range.prototype.toString = function () {
	  return this.range
	};

	Range.prototype.parseRange = function (range) {
	  var loose = this.options.loose;
	  range = range.trim();
	  // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
	  var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
	  range = range.replace(hr, hyphenReplace);
	  debug('hyphen replace', range);
	  // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
	  range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
	  debug('comparator trim', range, re[t.COMPARATORTRIM]);

	  // `~ 1.2.3` => `~1.2.3`
	  range = range.replace(re[t.TILDETRIM], tildeTrimReplace);

	  // `^ 1.2.3` => `^1.2.3`
	  range = range.replace(re[t.CARETTRIM], caretTrimReplace);

	  // normalize spaces
	  range = range.split(/\s+/).join(' ');

	  // At this point, the range is completely trimmed and
	  // ready to be split into comparators.

	  var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
	  var set = range.split(' ').map(function (comp) {
	    return parseComparator(comp, this.options)
	  }, this).join(' ').split(/\s+/);
	  if (this.options.loose) {
	    // in loose mode, throw out any that are not valid comparators
	    set = set.filter(function (comp) {
	      return !!comp.match(compRe)
	    });
	  }
	  set = set.map(function (comp) {
	    return new Comparator(comp, this.options)
	  }, this);

	  return set
	};

	Range.prototype.intersects = function (range, options) {
	  if (!(range instanceof Range)) {
	    throw new TypeError('a Range is required')
	  }

	  return this.set.some(function (thisComparators) {
	    return (
	      isSatisfiable(thisComparators, options) &&
	      range.set.some(function (rangeComparators) {
	        return (
	          isSatisfiable(rangeComparators, options) &&
	          thisComparators.every(function (thisComparator) {
	            return rangeComparators.every(function (rangeComparator) {
	              return thisComparator.intersects(rangeComparator, options)
	            })
	          })
	        )
	      })
	    )
	  })
	};

	// take a set of comparators and determine whether there
	// exists a version which can satisfy it
	function isSatisfiable (comparators, options) {
	  var result = true;
	  var remainingComparators = comparators.slice();
	  var testComparator = remainingComparators.pop();

	  while (result && remainingComparators.length) {
	    result = remainingComparators.every(function (otherComparator) {
	      return testComparator.intersects(otherComparator, options)
	    });

	    testComparator = remainingComparators.pop();
	  }

	  return result
	}

	// Mostly just for testing and legacy API reasons
	exports.toComparators = toComparators;
	function toComparators (range, options) {
	  return new Range(range, options).set.map(function (comp) {
	    return comp.map(function (c) {
	      return c.value
	    }).join(' ').trim().split(' ')
	  })
	}

	// comprised of xranges, tildes, stars, and gtlt's at this point.
	// already replaced the hyphen ranges
	// turn into a set of JUST comparators.
	function parseComparator (comp, options) {
	  debug('comp', comp, options);
	  comp = replaceCarets(comp, options);
	  debug('caret', comp);
	  comp = replaceTildes(comp, options);
	  debug('tildes', comp);
	  comp = replaceXRanges(comp, options);
	  debug('xrange', comp);
	  comp = replaceStars(comp, options);
	  debug('stars', comp);
	  return comp
	}

	function isX (id) {
	  return !id || id.toLowerCase() === 'x' || id === '*'
	}

	// ~, ~> --> * (any, kinda silly)
	// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
	// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
	// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
	// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
	// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
	function replaceTildes (comp, options) {
	  return comp.trim().split(/\s+/).map(function (comp) {
	    return replaceTilde(comp, options)
	  }).join(' ')
	}

	function replaceTilde (comp, options) {
	  var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
	  return comp.replace(r, function (_, M, m, p, pr) {
	    debug('tilde', comp, _, M, m, p, pr);
	    var ret;

	    if (isX(M)) {
	      ret = '';
	    } else if (isX(m)) {
	      ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
	    } else if (isX(p)) {
	      // ~1.2 == >=1.2.0 <1.3.0
	      ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
	    } else if (pr) {
	      debug('replaceTilde pr', pr);
	      ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
	            ' <' + M + '.' + (+m + 1) + '.0';
	    } else {
	      // ~1.2.3 == >=1.2.3 <1.3.0
	      ret = '>=' + M + '.' + m + '.' + p +
	            ' <' + M + '.' + (+m + 1) + '.0';
	    }

	    debug('tilde return', ret);
	    return ret
	  })
	}

	// ^ --> * (any, kinda silly)
	// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
	// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
	// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
	// ^1.2.3 --> >=1.2.3 <2.0.0
	// ^1.2.0 --> >=1.2.0 <2.0.0
	function replaceCarets (comp, options) {
	  return comp.trim().split(/\s+/).map(function (comp) {
	    return replaceCaret(comp, options)
	  }).join(' ')
	}

	function replaceCaret (comp, options) {
	  debug('caret', comp, options);
	  var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
	  return comp.replace(r, function (_, M, m, p, pr) {
	    debug('caret', comp, _, M, m, p, pr);
	    var ret;

	    if (isX(M)) {
	      ret = '';
	    } else if (isX(m)) {
	      ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
	    } else if (isX(p)) {
	      if (M === '0') {
	        ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
	      } else {
	        ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
	      }
	    } else if (pr) {
	      debug('replaceCaret pr', pr);
	      if (M === '0') {
	        if (m === '0') {
	          ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
	                ' <' + M + '.' + m + '.' + (+p + 1);
	        } else {
	          ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
	                ' <' + M + '.' + (+m + 1) + '.0';
	        }
	      } else {
	        ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
	              ' <' + (+M + 1) + '.0.0';
	      }
	    } else {
	      debug('no pr');
	      if (M === '0') {
	        if (m === '0') {
	          ret = '>=' + M + '.' + m + '.' + p +
	                ' <' + M + '.' + m + '.' + (+p + 1);
	        } else {
	          ret = '>=' + M + '.' + m + '.' + p +
	                ' <' + M + '.' + (+m + 1) + '.0';
	        }
	      } else {
	        ret = '>=' + M + '.' + m + '.' + p +
	              ' <' + (+M + 1) + '.0.0';
	      }
	    }

	    debug('caret return', ret);
	    return ret
	  })
	}

	function replaceXRanges (comp, options) {
	  debug('replaceXRanges', comp, options);
	  return comp.split(/\s+/).map(function (comp) {
	    return replaceXRange(comp, options)
	  }).join(' ')
	}

	function replaceXRange (comp, options) {
	  comp = comp.trim();
	  var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
	  return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
	    debug('xRange', comp, ret, gtlt, M, m, p, pr);
	    var xM = isX(M);
	    var xm = xM || isX(m);
	    var xp = xm || isX(p);
	    var anyX = xp;

	    if (gtlt === '=' && anyX) {
	      gtlt = '';
	    }

	    // if we're including prereleases in the match, then we need
	    // to fix this to -0, the lowest possible prerelease value
	    pr = options.includePrerelease ? '-0' : '';

	    if (xM) {
	      if (gtlt === '>' || gtlt === '<') {
	        // nothing is allowed
	        ret = '<0.0.0-0';
	      } else {
	        // nothing is forbidden
	        ret = '*';
	      }
	    } else if (gtlt && anyX) {
	      // we know patch is an x, because we have any x at all.
	      // replace X with 0
	      if (xm) {
	        m = 0;
	      }
	      p = 0;

	      if (gtlt === '>') {
	        // >1 => >=2.0.0
	        // >1.2 => >=1.3.0
	        // >1.2.3 => >= 1.2.4
	        gtlt = '>=';
	        if (xm) {
	          M = +M + 1;
	          m = 0;
	          p = 0;
	        } else {
	          m = +m + 1;
	          p = 0;
	        }
	      } else if (gtlt === '<=') {
	        // <=0.7.x is actually <0.8.0, since any 0.7.x should
	        // pass.  Similarly, <=7.x is actually <8.0.0, etc.
	        gtlt = '<';
	        if (xm) {
	          M = +M + 1;
	        } else {
	          m = +m + 1;
	        }
	      }

	      ret = gtlt + M + '.' + m + '.' + p + pr;
	    } else if (xm) {
	      ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr;
	    } else if (xp) {
	      ret = '>=' + M + '.' + m + '.0' + pr +
	        ' <' + M + '.' + (+m + 1) + '.0' + pr;
	    }

	    debug('xRange return', ret);

	    return ret
	  })
	}

	// Because * is AND-ed with everything else in the comparator,
	// and '' means "any version", just remove the *s entirely.
	function replaceStars (comp, options) {
	  debug('replaceStars', comp, options);
	  // Looseness is ignored here.  star is always as loose as it gets!
	  return comp.trim().replace(re[t.STAR], '')
	}

	// This function is passed to string.replace(re[t.HYPHENRANGE])
	// M, m, patch, prerelease, build
	// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
	// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
	// 1.2 - 3.4 => >=1.2.0 <3.5.0
	function hyphenReplace ($0,
	  from, fM, fm, fp, fpr, fb,
	  to, tM, tm, tp, tpr, tb) {
	  if (isX(fM)) {
	    from = '';
	  } else if (isX(fm)) {
	    from = '>=' + fM + '.0.0';
	  } else if (isX(fp)) {
	    from = '>=' + fM + '.' + fm + '.0';
	  } else {
	    from = '>=' + from;
	  }

	  if (isX(tM)) {
	    to = '';
	  } else if (isX(tm)) {
	    to = '<' + (+tM + 1) + '.0.0';
	  } else if (isX(tp)) {
	    to = '<' + tM + '.' + (+tm + 1) + '.0';
	  } else if (tpr) {
	    to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;
	  } else {
	    to = '<=' + to;
	  }

	  return (from + ' ' + to).trim()
	}

	// if ANY of the sets match ALL of its comparators, then pass
	Range.prototype.test = function (version) {
	  if (!version) {
	    return false
	  }

	  if (typeof version === 'string') {
	    try {
	      version = new SemVer(version, this.options);
	    } catch (er) {
	      return false
	    }
	  }

	  for (var i = 0; i < this.set.length; i++) {
	    if (testSet(this.set[i], version, this.options)) {
	      return true
	    }
	  }
	  return false
	};

	function testSet (set, version, options) {
	  for (var i = 0; i < set.length; i++) {
	    if (!set[i].test(version)) {
	      return false
	    }
	  }

	  if (version.prerelease.length && !options.includePrerelease) {
	    // Find the set of versions that are allowed to have prereleases
	    // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
	    // That should allow `1.2.3-pr.2` to pass.
	    // However, `1.2.4-alpha.notready` should NOT be allowed,
	    // even though it's within the range set by the comparators.
	    for (i = 0; i < set.length; i++) {
	      debug(set[i].semver);
	      if (set[i].semver === ANY) {
	        continue
	      }

	      if (set[i].semver.prerelease.length > 0) {
	        var allowed = set[i].semver;
	        if (allowed.major === version.major &&
	            allowed.minor === version.minor &&
	            allowed.patch === version.patch) {
	          return true
	        }
	      }
	    }

	    // Version has a -pre, but it's not one of the ones we like.
	    return false
	  }

	  return true
	}

	exports.satisfies = satisfies;
	function satisfies (version, range, options) {
	  try {
	    range = new Range(range, options);
	  } catch (er) {
	    return false
	  }
	  return range.test(version)
	}

	exports.maxSatisfying = maxSatisfying;
	function maxSatisfying (versions, range, options) {
	  var max = null;
	  var maxSV = null;
	  try {
	    var rangeObj = new Range(range, options);
	  } catch (er) {
	    return null
	  }
	  versions.forEach(function (v) {
	    if (rangeObj.test(v)) {
	      // satisfies(v, range, options)
	      if (!max || maxSV.compare(v) === -1) {
	        // compare(max, v, true)
	        max = v;
	        maxSV = new SemVer(max, options);
	      }
	    }
	  });
	  return max
	}

	exports.minSatisfying = minSatisfying;
	function minSatisfying (versions, range, options) {
	  var min = null;
	  var minSV = null;
	  try {
	    var rangeObj = new Range(range, options);
	  } catch (er) {
	    return null
	  }
	  versions.forEach(function (v) {
	    if (rangeObj.test(v)) {
	      // satisfies(v, range, options)
	      if (!min || minSV.compare(v) === 1) {
	        // compare(min, v, true)
	        min = v;
	        minSV = new SemVer(min, options);
	      }
	    }
	  });
	  return min
	}

	exports.minVersion = minVersion;
	function minVersion (range, loose) {
	  range = new Range(range, loose);

	  var minver = new SemVer('0.0.0');
	  if (range.test(minver)) {
	    return minver
	  }

	  minver = new SemVer('0.0.0-0');
	  if (range.test(minver)) {
	    return minver
	  }

	  minver = null;
	  for (var i = 0; i < range.set.length; ++i) {
	    var comparators = range.set[i];

	    comparators.forEach(function (comparator) {
	      // Clone to avoid manipulating the comparator's semver object.
	      var compver = new SemVer(comparator.semver.version);
	      switch (comparator.operator) {
	        case '>':
	          if (compver.prerelease.length === 0) {
	            compver.patch++;
	          } else {
	            compver.prerelease.push(0);
	          }
	          compver.raw = compver.format();
	          /* fallthrough */
	        case '':
	        case '>=':
	          if (!minver || gt(minver, compver)) {
	            minver = compver;
	          }
	          break
	        case '<':
	        case '<=':
	          /* Ignore maximum versions */
	          break
	        /* istanbul ignore next */
	        default:
	          throw new Error('Unexpected operation: ' + comparator.operator)
	      }
	    });
	  }

	  if (minver && range.test(minver)) {
	    return minver
	  }

	  return null
	}

	exports.validRange = validRange;
	function validRange (range, options) {
	  try {
	    // Return '*' instead of '' so that truthiness works.
	    // This will throw if it's invalid anyway
	    return new Range(range, options).range || '*'
	  } catch (er) {
	    return null
	  }
	}

	// Determine if version is less than all the versions possible in the range
	exports.ltr = ltr;
	function ltr (version, range, options) {
	  return outside(version, range, '<', options)
	}

	// Determine if version is greater than all the versions possible in the range.
	exports.gtr = gtr;
	function gtr (version, range, options) {
	  return outside(version, range, '>', options)
	}

	exports.outside = outside;
	function outside (version, range, hilo, options) {
	  version = new SemVer(version, options);
	  range = new Range(range, options);

	  var gtfn, ltefn, ltfn, comp, ecomp;
	  switch (hilo) {
	    case '>':
	      gtfn = gt;
	      ltefn = lte;
	      ltfn = lt;
	      comp = '>';
	      ecomp = '>=';
	      break
	    case '<':
	      gtfn = lt;
	      ltefn = gte;
	      ltfn = gt;
	      comp = '<';
	      ecomp = '<=';
	      break
	    default:
	      throw new TypeError('Must provide a hilo val of "<" or ">"')
	  }

	  // If it satisifes the range it is not outside
	  if (satisfies(version, range, options)) {
	    return false
	  }

	  // From now on, variable terms are as if we're in "gtr" mode.
	  // but note that everything is flipped for the "ltr" function.

	  for (var i = 0; i < range.set.length; ++i) {
	    var comparators = range.set[i];

	    var high = null;
	    var low = null;

	    comparators.forEach(function (comparator) {
	      if (comparator.semver === ANY) {
	        comparator = new Comparator('>=0.0.0');
	      }
	      high = high || comparator;
	      low = low || comparator;
	      if (gtfn(comparator.semver, high.semver, options)) {
	        high = comparator;
	      } else if (ltfn(comparator.semver, low.semver, options)) {
	        low = comparator;
	      }
	    });

	    // If the edge version comparator has a operator then our version
	    // isn't outside it
	    if (high.operator === comp || high.operator === ecomp) {
	      return false
	    }

	    // If the lowest version comparator has an operator and our version
	    // is less than it then it isn't higher than the range
	    if ((!low.operator || low.operator === comp) &&
	        ltefn(version, low.semver)) {
	      return false
	    } else if (low.operator === ecomp && ltfn(version, low.semver)) {
	      return false
	    }
	  }
	  return true
	}

	exports.prerelease = prerelease;
	function prerelease (version, options) {
	  var parsed = parse(version, options);
	  return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
	}

	exports.intersects = intersects;
	function intersects (r1, r2, options) {
	  r1 = new Range(r1, options);
	  r2 = new Range(r2, options);
	  return r1.intersects(r2)
	}

	exports.coerce = coerce;
	function coerce (version, options) {
	  if (version instanceof SemVer) {
	    return version
	  }

	  if (typeof version === 'number') {
	    version = String(version);
	  }

	  if (typeof version !== 'string') {
	    return null
	  }

	  options = options || {};

	  var match = null;
	  if (!options.rtl) {
	    match = version.match(re[t.COERCE]);
	  } else {
	    // Find the right-most coercible string that does not share
	    // a terminus with a more left-ward coercible string.
	    // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
	    //
	    // Walk through the string checking with a /g regexp
	    // Manually set the index so as to pick up overlapping matches.
	    // Stop when we get a match that ends at the string end, since no
	    // coercible string can be more right-ward without the same terminus.
	    var next;
	    while ((next = re[t.COERCERTL].exec(version)) &&
	      (!match || match.index + match[0].length !== version.length)
	    ) {
	      if (!match ||
	          next.index + next[0].length !== match.index + match[0].length) {
	        match = next;
	      }
	      re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
	    }
	    // leave it in a clean state
	    re[t.COERCERTL].lastIndex = -1;
	  }

	  if (match === null) {
	    return null
	  }

	  return parse(match[2] +
	    '.' + (match[3] || '0') +
	    '.' + (match[4] || '0'), options)
	}
} (semver, semver.exports));

const LOADED = {};
/**
 * @interface LoadType
 * @param {object} type
 * @param {string} type.name
 * @param {string} type.version
 * @returns {Promise<Visualization>}
 */

async function load(name, version, _ref, loader) {
  let {
    config
  } = _ref;
  const key = "".concat(name, "__").concat(version);

  if (!LOADED[key]) {
    const sKey = "".concat(name).concat(version && " v".concat(version) || '');

    if (loader && typeof loader !== 'function') {
      throw new Error("load of visualization '".concat(sKey, "' is not a fuction, wrap load promise in function"));
    }

    const p = (loader || config.load)({
      name,
      version
    });
    const prom = Promise.resolve(p);
    LOADED[key] = prom.then(sn => {
      if (!sn) {
        // TODO - improve validation
        throw new Error("load() of visualization '".concat(sKey, "' resolved to an invalid object"));
      }

      return sn;
    }).catch(e => {
      {
        console.warn(e); // eslint-disable-line no-console
      }

      throw new Error("Failed to load visualization: '".concat(sKey, "'"));
    });
  }

  return LOADED[key];
}
function clearFromCache(name) {
  Object.keys(LOADED).forEach(key => {
    if (key.split('__')[0] === name) {
      LOADED[key] = undefined;
    }
  });
}

/**
 * @interface TypeInfo
 * @property {string} name
 * @property {string=} version
 * @property {LoadType} load
 * @property {object=} meta
 */

function create$1(info, halo) {
  let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  let sn;
  let stringified;
  const {
    meta
  } = opts;
  const type = {
    name: info.name,
    version: info.version,

    supportsPropertiesVersion(v) {
      if (v && meta && meta.deps && meta.deps.properties) {
        return semver.exports.satisfies(v, meta.deps.properties);
      }

      return true;
    },

    supernova: () => load(type.name, type.version, halo, opts.load).then(SNDefinition => {
      sn = sn || generatorFn(SNDefinition, halo.public.galaxy);
      stringified = JSON.stringify(sn.qae.properties.initial);
      return sn;
    }),

    initialProperties(initial) {
      return this.supernova().then(() => {
        const props = _objectSpread2(_objectSpread2({
          qInfo: {
            qType: type.name
          },
          visualization: type.name,
          version: type.version,
          showTitles: true
        }, JSON.parse(stringified)), initial);

        return props;
      });
    }

  };
  return type;
}

function semverSort(arr) {
  const unversioned = arr.filter(v => v === 'undefined');
  return [...unversioned, ...arr.filter(v => v !== 'undefined').map(v => v.split('.').map(n => parseInt(n, 10))).sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]).map(n => n.join('.'))];
}
function typeCollection(name, halo) {
  const versions = {};
  let sortedVersions = null;
  return {
    get: version => versions[version],
    register: (version, opts) => {
      if (versions[version]) {
        throw new Error("Supernova '".concat(name, "@").concat(version, "' already registered."));
      }

      versions[version] = create$1({
        name,
        version
      }, halo, opts);
      sortedVersions = null;
    },
    getMatchingVersionFromProperties: propertyVersion => {
      if (!sortedVersions) {
        sortedVersions = semverSort(Object.keys(versions));
      }

      for (let i = sortedVersions.length - 1; i >= 0; i--) {
        const t = versions[sortedVersions[i]];

        if (t.supportsPropertiesVersion(propertyVersion)) {
          return sortedVersions[i];
        }
      }

      return null;
    },
    versions
  };
}
function create(_ref) {
  let {
    halo,
    parent
  } = _ref;
  const tc = {};
  const p = parent || {
    get: () => undefined
  };
  return {
    register: (typeInfo, opts) => {
      if (!tc[typeInfo.name]) {
        tc[typeInfo.name] = typeCollection(typeInfo.name, halo);
      }

      tc[typeInfo.name].register(typeInfo.version, opts);
    },
    getSupportedVersion: (name, propertyVersion) => {
      if (!tc[name]) {
        return null;
      }

      return tc[name].getMatchingVersionFromProperties(propertyVersion);
    },

    get(typeInfo) {
      const {
        name
      } = typeInfo;
      let {
        version
      } = typeInfo;

      if (!tc[name]) {
        // Fall back to existing version
        {
          console.warn("Visualization ".concat(name, " is not registered.")); // eslint-disable-line no-console
        }

        this.register({
          name,
          version
        });
      } else if (!tc[name].versions[version]) {
        // Fall back to existing version
        const versionToUse = Object.keys(tc[name].versions)[0];

        {
          console.warn("Version ".concat(version, " of ").concat(name, " is not registered. Falling back to version ").concat(versionToUse)); // eslint-disable-line no-console
        }

        version = versionToUse;
      }

      return tc[name].get(version) || p.get(typeInfo);
    },

    getList: () => Object.keys(tc).map(key => ({
      name: key,
      versions: Object.keys(tc[key].versions).map(v => v === 'undefined' ? undefined : v)
    })),
    clearFromCache: name => {
      if (tc[name]) {
        tc[name] = undefined;
      }

      clearFromCache(name);
    }
  };
}

const _excluded = ["__DO_NOT_USE__"];
/**
 * @interface Context
 * @property {boolean=} keyboardNavigation
 * @property {object=} constraints
 * @property {boolean=} constraints.active
 * @property {boolean=} constraints.passive
 * @property {boolean=} constraints.select
 */

const DEFAULT_CONTEXT =
/** @lends Context */
{
  /** @type {string=} */
  theme: 'light',

  /** @type {string=} */
  language: 'en-US',

  /** @type {string=} */
  deviceType: 'auto',
  constraints: {},
  keyboardNavigation: false,
  disableCellPadding: false
};
/**
 * @interface SnapshotConfiguration
 * @private
 */

const DEFAULT_SNAPSHOT_CONFIG =
/** @lends SnapshotConfiguration */
{
  /**
   * @param {string} id
   * @returns {Promise<SnapshotLayout>}
   */
  get: async id => {
    const res = await fetch("/njs/snapshot/".concat(id));

    if (!res.ok) {
      throw new Error(res.statusText);
    }

    return res.json();
  },

  capture(payload) {
    return fetch("/njs/capture", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(payload)
    }).then(res => res.json());
  }

};
/**
 * @interface Configuration
 */

const DEFAULT_CONFIG =
/** @lends Configuration */
{
  /**
   * @type {Context=}
   */
  context: DEFAULT_CONTEXT,
  load: () => undefined,

  /**
   * @type {(TypeInfo[])=}
   */
  types: [],

  /**
   * @type {(ThemeInfo[])=}
   */
  themes: [],

  /** @type {object=} */
  anything: {},

  /**
   * @type {SnapshotConfiguration=}
   * @private
   */
  snapshot: DEFAULT_SNAPSHOT_CONFIG
};
/**
 * @interface Galaxy
 */

const mergeObj = function () {
  let o1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  let o2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  return _objectSpread2(_objectSpread2({}, o1), o2);
};

const mergeArray = function () {
  let a1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  let a2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  return (// Simple merge and deduplication
    [...a1, ...a2].filter((v, i, a) => a.indexOf(v) === i)
  );
};

const mergeConfigs = (base, c) => ({
  context: mergeObj(base.context, c.context),
  load: c.load || base.load,
  snapshot: _objectSpread2({}, c.snapshot || base.snapshot),
  types: mergeArray(base.types, c.types),
  themes: mergeArray(base.themes, c.themes),
  flags: mergeObj(base.flags, c.flags),
  anything: mergeObj(base.anything, c.anything)
});
/**
 * @ignore
 * @typedef {function(promise)} PromiseFunction A callback function which receives a request promise as the first argument.
 */

/**
 * @ignore
 * @typedef {function(function)} ReceiverFunction A callback function which receives another function as input.
 */

/**
 * @ignore
 * @typedef {object} DoNotUseOptions Options strictly recommended not to use as they might change anytime. Documenting them to keep track of them, but not exposing them to API docs.
 * @property {boolean=} [focusSearch=false] Initialize the Listbox with the search input focused. Only applicable when
 *    search is true, since toggling will always focus the search input on show.
 * @property {boolean=} [options.showGray=true] Render fields or checkboxes in shades of gray instead of white when their state is excluded or alternative.
 * @property {object} [options.sessionModel] Use a custom sessionModel.
 * @property {object} [options.selectionsApi] Use a custom selectionsApi to customize how values are selected.
 * @property {function():boolean} [options.selectDisabled=] Define a function which tells when selections are disabled (true) or enabled (false). By default, always returns false.
 * @property {PromiseFunction} [options.fetchStart] A function called when the Listbox starts fetching data. Receives the fetch request promise as an argument.
 * @property {ReceiverFunction} [options.update] A function which receives an update function which upon call will trigger a data fetch.
 * @property {{setScrollPos:function(number):void, initScrollPos:number}} [options.scrollState=] Object including a setScrollPos function that sets current scroll position index. A initial scroll position index.
 * @property {number=} [options.sortByState=1] Sort by state, detault 1 = sort descending, 0 = no sorting, -1 sort ascending.
 * @property {function(number):void} [options.setCount=] A function that gets called with the length of the data in the Listbox.
 */

/**
 * @ignore
 * @param {object} usersOptions Options sent in to fieldInstance.mount.
 * @param {DoNotUseOptions} __DO_NOT_USE__
 * @returns {object} Squashed options with defaults given for non-exposed options.
 */


const getOptions = function () {
  let usersOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  const {
    __DO_NOT_USE__ = {}
  } = usersOptions,
        exposedOptions = _objectWithoutProperties$1(usersOptions, _excluded);

  const DO_NOT_USE_DEFAULTS = {
    update: undefined,
    fetchStart: undefined,
    showGray: true,
    focusSearch: false,
    sessionModel: undefined,
    selectionsApi: undefined,
    selectDisabled: undefined
  };

  const squashedOptions = _objectSpread2(_objectSpread2(_objectSpread2({}, exposedOptions), DO_NOT_USE_DEFAULTS), __DO_NOT_USE__);

  return squashedOptions;
};

function nuked() {
  let configuration = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  const locale = appLocaleFn(configuration.context.language);
  /**
   * Initiates a new `Embed` instance using the specified enigma `app`.
   * @entry
   * @function embed
   * @param {EngineAPI.IApp} app
   * @param {Configuration=} instanceConfig
   * @returns {Embed}
   * @example
   * import { embed } from '@nebula.js/stardust'
   * const n = embed(app);
   * n.render({ id: 'abc' });
   */

  function embed(app, instanceConfig) {
    if (instanceConfig) {
      return embed.createConfiguration(instanceConfig)(app);
    }

    let currentContext = _objectSpread2(_objectSpread2({}, configuration.context), {}, {
      translator: locale.translator
    });

    const [root] = boot({
      app,
      context: currentContext
    });
    const appTheme$1 = appTheme({
      themes: configuration.themes,
      root
    });
    const publicAPIs = {
      galaxy:
      /** @lends Galaxy */
      {
        /** @type {Translator} */
        translator: locale.translator,
        // TODO - validate flags input

        /** @type {Flags} */
        flags: flagsFn(configuration.flags),

        /** @type {string} */
        deviceType: deviceTypeFn(configuration.context.deviceType),

        /** @type {object} */
        anything: configuration.anything
      },
      theme: appTheme$1.externalAPI,
      translator: locale.translator,
      nebbie: null // actual value is set further down

    };
    const halo = {
      app,
      root,
      config: configuration,
      public: publicAPIs,
      context: currentContext,
      types: null
    };
    const types = create({
      halo
    });
    configuration.types.forEach(t => types.register({
      name: t.name,
      version: t.version
    }, {
      meta: t.meta,
      load: t.load
    }));
    let currentThemePromise = appTheme$1.setTheme(configuration.context.theme);
    let selectionsApi = null;
    let selectionsComponentReference = null;
    /**
     * @class
     * @alias Embed
     */

    const api =
    /** @lends Embed# */
    {
      /**
       * Renders a visualization into an HTMLElement.
       * @param {CreateConfig | GetConfig} cfg - The render configuration.
       * @returns {Promise<Viz>} A controller to the rendered visualization.
       * @example
       * // render from existing object
       * n.render({
       *   element: el,
       *   id: 'abcdef'
       * });
       * @example
       * // render on the fly
       * n.render({
       *   element: el,
       *   type: 'barchart',
       *   fields: ['Product', { qLibraryId: 'u378hn', type: 'measure' }]
       * });
       */
      render: async cfg => {
        await currentThemePromise;

        if (cfg.id) {
          return getObject(cfg, halo);
        }

        return createSessionObject(cfg, halo);
      },

      /**
       * Updates the current context of this embed instance.
       * Use this when you want to change some part of the current context, like theme.
       * @param {Context} ctx - The context to update.
       * @returns {Promise<undefined>}
       * @example
       * // change theme
       * n.context({ theme: 'dark'});
       * @example
       * // limit constraints
       * n.context({ constraints: { active: true } });
       */
      context: async ctx => {
        // filter valid values to avoid triggering unnecessary rerender
        let changes;
        ['theme', 'language', 'constraints', 'keyboardNavigation'].forEach(key => {
          if (Object.prototype.hasOwnProperty.call(ctx, key) && ctx[key] !== currentContext[key]) {
            if (!changes) {
              changes = {};
            }

            changes[key] = ctx[key];
          }
        });

        if (!changes) {
          return;
        }

        currentContext = _objectSpread2(_objectSpread2(_objectSpread2({}, currentContext), changes), {}, {
          translator: locale.translator
        });
        halo.context = currentContext;

        if (changes.theme) {
          currentThemePromise = appTheme$1.setTheme(changes.theme);
          await currentThemePromise;
        }

        if (changes.language) {
          halo.public.translator.language(changes.language);
        }

        root.context(currentContext);
      },

      /**
       * Gets the app selections of this instance.
       * @returns {Promise<AppSelections>}
       * @example
       * const selections = await n.selections();
       * selections.mount(element);
       */
      selections: async () => {
        if (!selectionsApi) {
          // const appSelections = await root.getAppSelections(); // Don't expose this for now
          selectionsApi =
          /** @lends AppSelections# */
          {
            /**
             * Mounts the app selection UI into the provided HTMLElement.
             * @param {HTMLElement} element
             * @example
             * selections.mount(element);
             */
            mount(element) {
              if (selectionsComponentReference) {
                {
                  console.error('Already mounted'); // eslint-disable-line no-console
                }

                return;
              }

              selectionsComponentReference = mount({
                element,
                app
              });
              root.add(selectionsComponentReference);
            },

            /**
             * Unmounts the app selection UI from the DOM.
             * @example
             * selections.unmount();
             */
            unmount() {
              if (selectionsComponentReference) {
                root.remove(selectionsComponentReference);
                selectionsComponentReference = null;
              }
            }

          };
        }

        return selectionsApi;
      },

      /**
       * Gets the listbox instance of the specified field
       * @param {string|LibraryField} fieldIdentifier Fieldname as a string or a Library dimension
       * @returns {Promise<FieldInstance>}
       * @since 1.1.0
       * @example
       * const fieldInstance = await n.field("MyField");
       * fieldInstance.mount(element, { title: "Hello Field"});
       */
      field: async fieldIdentifier => {
        const fieldName = typeof fieldIdentifier === 'string' ? fieldIdentifier : fieldIdentifier.qLibraryId;

        if (!fieldName) {
          throw new Error("Field identifier must be provided");
        }
        /**
         * @typedef { 'ltr' | 'rtl' } Direction
         */

        /**
         * @typedef { 'vertical' | 'horizontal' } ListLayout
         */

        /**
         * @typedef { 'none' | 'value' | 'percent' | 'relative' } FrequencyMode
         */

        /**
         * @typedef { boolean | 'toggle' } SearchMode
         */

        /**
         * @class
         * @alias FieldInstance
         * @since 1.1.0
         */


        const fieldSels = {
          fieldName,

          /**
           * Mounts the field as a listbox into the provided HTMLElement.
           * @param {HTMLElement} element
           * @param {object=} options Settings for the embedded listbox
           * @param {string=} options.title Custom title, defaults to fieldname
           * @param {Direction=} [options.direction=ltr] Direction setting ltr|rtl.
           * @param {ListLayout=} [options.listLayout=vertical] Layout direction vertical|horizontal
           * @param {FrequencyMode=} [options.frequencyMode=none] Show frequency none|value|percent|relative
           * @param {boolean=} [options.histogram=false] Show histogram bar
           * @param {SearchMode=} [options.search=true] Show the search bar permanently or using the toggle button: false|true|toggle|toggleShow
           * @param {boolean=} [options.toolbar=true] Show the toolbar
           * @param {boolean=} [options.checkboxes=false] Show values as checkboxes instead of as fields
           * @param {boolean=} [options.dense=false] Reduces padding and text size
           * @param {boolean=} [options.stateName="$"] Sets the state to make selections in
           * @param {object=} [options.properties={}] Properties object to extend default properties with
           *
           * @since 1.1.0
           * @instance
           * @example
           * fieldInstance.mount(element);
           */
          mount(element) {
            let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

            if (!element) {
              throw new Error("Element for ".concat(fieldName, " not provided"));
            }

            if (this._instance) {
              throw new Error("Field ".concat(fieldName, " already mounted"));
            }

            this._instance = ListBoxPortal({
              element,
              app,
              fieldIdentifier,
              options: getOptions(options),
              stateName: options.stateName || '$'
            });
            root.add(this._instance);
          },

          /**
           * Unmounts the field listbox from the DOM.
           * @since 1.1.0
           * @instance
           * @example
           * listbox.unmount();
           */
          unmount() {
            if (this._instance) {
              root.remove(this._instance);
              this._instance = null;
            }
          }

        };
        return fieldSels;
      },

      /**
       * Gets a list of registered visualization types and versions
       * @function
       * @returns {Array<Object>} types
       * @example
       * const types = n.getRegisteredTypes();
       * // Contains
       * //[
       * // {
       * //   name: "barchart"
       * //   versions:[undefined, "1.2.0"]
       * // }
       * //]
       */
      getRegisteredTypes: types.getList,
      __DO_NOT_USE__: {
        types
      }
    };
    halo.public.nebbie = api;
    halo.types = types;
    return api;
  }
  /**
   * Creates a new `embed` scope bound to the specified `configuration`.
   *
   * The configuration is merged with all previous scopes.
   * @memberof embed
   * @param {Configuration} configuration - The configuration object
   * @returns {embed}
   * @example
   * import { embed } from '@nebula.js/stardust';
   * // create a 'master' config which registers all types
   * const m = embed.createConfiguration({
   *   types: [{
   *     name: 'mekko',
   *     version: '1.0.0',
   *     load: () => Promise.resolve(mekko)
   *   }],
   * });
   *
   * // create an alternate config with dark theme
   * // and inherit the config from the previous
   * const d = m.createConfiguration({
   *  context: {
   *    theme: 'dark'
   *  }
   * });
   *
   * m(app).render({ type: 'mekko' }); // will render the object with default theme
   * d(app).render({ type: 'mekko' }); // will render the object with 'dark' theme
   * embed(app).render({ type: 'mekko' }); // will throw error since 'mekko' is not a register type on the default instance
   */


  embed.createConfiguration = c => nuked(mergeConfigs(configuration, c));

  embed.config = configuration;
  return embed;
}
/**
 * @typedef {any} ThemeJSON
 */

/**
 * @interface ThemeInfo
 * @property {string} id Theme identifier
 * @property {function(): Promise<ThemeJSON>} load A function that should return a Promise that resolves to a raw JSON theme.
 */


var index = nuked(DEFAULT_CONFIG);

var enigmaMocker = {exports: {}};

var enigmaMocker_dev = {exports: {}};

/*
* @nebula.js/enigma-mocker v2.11.0
* Copyright (c) 2022 QlikTech International AB
* Released under the MIT license.
*/

(function (module, exports) {
  (function (global, factory) {
    module.exports = factory() ;
  })(commonjsGlobal, function () {

    function SessionMock() {
      return {
        getObjectApi() {
          return Promise.resolve({
            id: "sessapi - ".concat(+Date.now())
          });
        }

      };
    }

    function ownKeys(object, enumerableOnly) {
      var keys = Object.keys(object);

      if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        enumerableOnly && (symbols = symbols.filter(function (sym) {
          return Object.getOwnPropertyDescriptor(object, sym).enumerable;
        })), keys.push.apply(keys, symbols);
      }

      return keys;
    }

    function _objectSpread2(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = null != arguments[i] ? arguments[i] : {};
        i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
          _defineProperty(target, key, source[key]);
        }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
          Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
      }

      return target;
    }

    function _defineProperty(obj, key, value) {
      if (key in obj) {
        Object.defineProperty(obj, key, {
          value: value,
          enumerable: true,
          configurable: true,
          writable: true
        });
      } else {
        obj[key] = value;
      }

      return obj;
    }

    function _objectWithoutPropertiesLoose(source, excluded) {
      if (source == null) return {};
      var target = {};
      var sourceKeys = Object.keys(source);
      var key, i;

      for (i = 0; i < sourceKeys.length; i++) {
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        target[key] = source[key];
      }

      return target;
    }

    function _objectWithoutProperties(source, excluded) {
      if (source == null) return {};

      var target = _objectWithoutPropertiesLoose(source, excluded);

      var key, i;

      if (Object.getOwnPropertySymbols) {
        var sourceSymbolKeys = Object.getOwnPropertySymbols(source);

        for (i = 0; i < sourceSymbolKeys.length; i++) {
          key = sourceSymbolKeys[i];
          if (excluded.indexOf(key) >= 0) continue;
          if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
          target[key] = source[key];
        }
      }

      return target;
    }

    var hasOwn = Object.prototype.hasOwnProperty;
    var toStr = Object.prototype.toString;
    var defineProperty = Object.defineProperty;
    var gOPD = Object.getOwnPropertyDescriptor;

    var isArray = function isArray(arr) {
      if (typeof Array.isArray === 'function') {
        return Array.isArray(arr);
      }

      return toStr.call(arr) === '[object Array]';
    };

    var isPlainObject = function isPlainObject(obj) {
      if (!obj || toStr.call(obj) !== '[object Object]') {
        return false;
      }

      var hasOwnConstructor = hasOwn.call(obj, 'constructor');
      var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); // Not own constructor property must be Object

      if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
        return false;
      } // Own properties are enumerated firstly, so to speed up,
      // if last one is own, then all properties are own.


      var key;

      for (key in obj) {
        /**/
      }

      return typeof key === 'undefined' || hasOwn.call(obj, key);
    }; // If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target


    var setProperty = function setProperty(target, options) {
      if (defineProperty && options.name === '__proto__') {
        defineProperty(target, options.name, {
          enumerable: true,
          configurable: true,
          value: options.newValue,
          writable: true
        });
      } else {
        target[options.name] = options.newValue;
      }
    }; // Return undefined instead of __proto__ if '__proto__' is not an own property


    var getProperty = function getProperty(obj, name) {
      if (name === '__proto__') {
        if (!hasOwn.call(obj, name)) {
          return void 0;
        } else if (gOPD) {
          // In early versions of node, obj['__proto__'] is buggy when obj has
          // __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
          return gOPD(obj, name).value;
        }
      }

      return obj[name];
    };

    var extend = function extend() {
      var options, name, src, copy, copyIsArray, clone;
      var target = arguments[0];
      var i = 1;
      var length = arguments.length;
      var deep = false; // Handle a deep copy situation

      if (typeof target === 'boolean') {
        deep = target;
        target = arguments[1] || {}; // skip the boolean and the target

        i = 2;
      }

      if (target == null || typeof target !== 'object' && typeof target !== 'function') {
        target = {};
      }

      for (; i < length; ++i) {
        options = arguments[i]; // Only deal with non-null/undefined values

        if (options != null) {
          // Extend the base object
          for (name in options) {
            src = getProperty(target, name);
            copy = getProperty(options, name); // Prevent never-ending loop

            if (target !== copy) {
              // Recurse if we're merging plain objects or arrays
              if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
                if (copyIsArray) {
                  copyIsArray = false;
                  clone = src && isArray(src) ? src : [];
                } else {
                  clone = src && isPlainObject(src) ? src : {};
                } // Never move original objects, clone them


                setProperty(target, {
                  name: name,
                  newValue: extend(deep, clone, copy)
                }); // Don't bring in undefined values
              } else if (typeof copy !== 'undefined') {
                setProperty(target, {
                  name: name,
                  newValue: copy
                });
              }
            }
          }
        }
      } // Return the modified object


      return target;
    }; // eslint-disable-next-line no-undef


    const crt = globalThis.crypto || {
      getRandomValues: () => 123456
    }; // https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid
    // Not using crypto.randomUUID due to missing safari support < 15

    function uuidv4() {
      return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ crt.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16));
    }

    function CreateSessionObjectMock() {
      return props => {
        const properties = extend({}, props);
        properties.qInfo = properties.qInfo || {};
        properties.qInfo.qId = properties.qInfo.qId || "mock-".concat(uuidv4());
        const mockedInclusions = properties._mock;
        let layout = properties;

        if (mockedInclusions) {
          delete properties._mock;
          layout = extend({}, properties, mockedInclusions);
        }

        return Promise.resolve(_objectSpread2({
          on: () => {},
          once: () => {},
          getLayout: () => Promise.resolve(layout),
          getProperties: () => Promise.resolve(properties),
          getEffectiveProperties: () => Promise.resolve(properties),
          id: properties.qInfo.qId
        }, properties));
      };
    }
    /**
     * Get value for a fixture property.
     *
     * The value is either static (e.g. pass a string / object / similar) or dynamic when passing a function.
     *
     * It falls back to the default value in case the fixture has no value specified.
     *
     * Example
     * ```js
     * const fixture = {
     *  id: 'grid-chart-1',
     * };
     * const app = {
     *   id: getValue(fixture.id, { defaultValue: 'object-id-${+Date.now()}'}),
     * }
     * ```
     *
     * @param {any} prop Fixture property. Either a fixed value (string / object / boolean / ...) or a function invoked when the value is needed.
     * @param {object} options Options.
     * @param {Array<any>} options.args Arguments used to evaluate the property value.
     * @param {any} options.defaultValue Default value in case not value is defined in fixture.
     * @returns The property value.
     */


    const getPropValue = function (prop) {
      let {
        args = [],
        defaultValue
      } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      if (typeof prop === 'function') {
        return prop(...args);
      }

      if (prop !== undefined) {
        return prop;
      }

      return defaultValue;
    };
    /**
     * Get function for a fixture property.
     *
     * When the returned function is invoked it resolves the value - using `defaultValue` as fallback - and returns it. The value is returned as a promise if `option.usePromise` is `true`.
     *
     * Example:
     * ```js
     * const fixture = {
     *   getHyperCubeData(path, page) {
     *     return [ ... ];
     *   }
     * }
     * const app = {
     *   getHyperCubeData: getPropFn(fixture.getHyperCubeData, { defaultValue: [], usePromise: true })
     * };
     * ```
     *
     * @param {any} prop Fixture property. Either a fixed value (string / object / boolean / ...) or a function invoked when the value is needed.
     * @param {object} options Options.
     * @param {any} options.defaultValue Default value in case not value is defined in fixture.
     * @param {boolean} options.async When `true` the returns value is wrapped in a promise, otherwise the value is directly returned.
     * @param {number} options.number Delay before value is returned.
     * @returns A fixture property function
     */


    const getPropFn = function (prop) {
      let {
        defaultValue,
        async = true,
        delay = 0
      } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      return function () {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }

        const value = getPropValue(prop, {
          defaultValue,
          args
        });
        return async ? new Promise(resolve => {
          setTimeout(() => resolve(value), delay);
        }) : value;
      };
    };

    const _excluded = ["id", "session"];
    /**
     * Properties on `getObject()` operating synchronously.
     */

    const PROPS_SYNC = ['addListener', 'emit', 'listeners', 'on', 'once', 'removeAllListeners', 'removeListener', 'setMaxListerners'];
    /**
     * Is property operating asynchrously.
     * @param {string} name Property name.
     * @returns `true` if property is operating asynchrously, otherwise `false`.
     */

    function isPropAsync(name) {
      return !PROPS_SYNC.includes(name);
    }
    /**
     * Get `qId` for visualization.
     * @param {object} genericObject Generic object describing behaviour of mock
     * @returns The `qId`, undefined if not present
     */


    function getQId(genericObject) {
      const layout = getPropValue(genericObject.getLayout);
      return layout.qInfo && layout.qInfo.qId;
    }
    /**
     * Create a mock of a generic object. Mandatory properties are added, functions returns async values where applicable etc.
     * @param {object} genericObject Generic object describing behaviour of mock
     * @param {EnigmaMockerOptions} options Options.
     * @returns The mocked object
     */


    function createMock(genericObject, options) {
      const qId = getQId(genericObject);
      const {
        delay
      } = options;

      const {
        id,
        session
      } = genericObject,
            props = _objectWithoutProperties(genericObject, _excluded);

      const mock = _objectSpread2({
        id: getPropValue(id, {
          defaultValue: "object - ".concat(+Date.now())
        }),
        session: getPropValue(session, {
          defaultValue: true
        }),
        on: () => {},
        once: () => {}
      }, Object.entries(props).reduce((fns, _ref) => {
        let [name, value] = _ref;
        return _objectSpread2(_objectSpread2({}, fns), {}, {
          [name]: getPropFn(value, {
            async: isPropAsync(name),
            delay
          })
        });
      }, {}));

      return {
        [qId]: mock
      };
    }
    /**
     * Create mocked objects from list of generic objects.
     * @param {Array<object>} genericObjects Generic objects describing behaviour of mock
     * @param {EnigmaMockerOptions} options options
     * @returns Object with mocks where key is `qId` and value is the mocked object.
     */


    function createMocks(genericObjects, options) {
      return genericObjects.reduce((mocks, genericObject) => _objectSpread2(_objectSpread2({}, mocks), createMock(genericObject, options)), {});
    }
    /**
     * Validates if mandatory information is available.
     * @param {object} genericObject Generic object to validate
     * @throws {}
     * <ul>
     *   <li>{Error} If getLayout is missing</li>
     *   <li>{Error} If getLayout.qInfo.qId is missing</li>
     * </ul>
     */


    function validate(genericObject) {
      if (!genericObject.getLayout) {
        throw new Error('Generic object is missing "getLayout"');
      }

      const qId = getQId(genericObject);

      if (!qId) {
        throw new Error('Generic object is missing "qId" for path "getLayout().qInfo.qId"');
      }
    }
    /**
     * Creates mock of `getObject(id)` based on an array of generic objects.
     * @param {Array<object>} genericObjects Generic objects.
     * @param {EnigmaMockerOptions} options Options.
     * @returns Function to retrieve the mocked generic object with the corresponding id.
     */


    function GetObjectMock() {
      let genericObjects = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      if (!Array.isArray(genericObjects) || genericObjects.length === 0) {
        return () => {
          throw new Error('No "genericObjects" specified');
        };
      }

      genericObjects.forEach(validate);
      const mocks = createMocks(genericObjects, options);
      return async id => Promise.resolve(mocks[id]);
    }

    function GetAppLayoutMock() {
      return () => Promise.resolve({
        id: 'app-layout'
      });
    }
    /**
     * @interface EnigmaMockerOptions
     * @property {number} delay Simulate delay (in ms) for calls in enigma-mocker.
     */

    /**
     * Mocks Engima app functionality. It accepts one / many generic objects as input argument and returns the mocked Enigma app. Each generic object represents one visulization and specifies how it behaves. For example, what layout to use the data to present.
     *
     * The generic object is represented with a Javascript object with a number of properties. The name of the property correlates to the name in the Enigma model for `app.getObject(id)`. For example, the property `getLayout` in the generic object is used to define `app.getObject(id).getLayout()`. Any property can be added to the fixture (just make sure it exists and behaves as in the Enigma model!).
     *
     * The value for each property is either fixed (string / boolean / number / object) or a function. Arguments are forwarded to the function to allow for greater flexibility. For example, this can be used to return different hypercube data when scrolling in the chart.
     *
     * @param {Array<object>} genericObjects Generic objects controling behaviour of visualizations.
     * @param {EnigmaMockerOptions} options Options
     * @returns {Promise<enigma.Doc>}
     * @example
     * const genericObject = {
     *   getLayout() {
     *     return {
     *       qInfo: {
     *         qId: 'qqj4zx',
     *         qType: 'sn-grid-chart'
     *       },
     *       ...
     *     }
     *   },
     *   getHyperCubeData(path, page) {
     *     return [ ... ];
     *   }
     * };
     * const app = await EnigmaMocker.fromGenericObjects([genericObject]);
     */


    var fromGenericObjects = function (genericObjects) {
      let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      const session = new SessionMock();
      const createSessionObject = new CreateSessionObjectMock();
      const getObject = new GetObjectMock(genericObjects, options);
      const getAppLayout = new GetAppLayoutMock();
      const app = {
        id: "app - ".concat(+Date.now()),
        session,
        createSessionObject,
        getObject,
        getAppLayout
      };
      return Promise.resolve(app);
    };

    var index = {
      fromGenericObjects
    };
    return index;
  });
})(enigmaMocker_dev);

(function (module) {
  module.exports = enigmaMocker_dev.exports;
})(enigmaMocker);

var EnigmaMocker = /*@__PURE__*/getDefaultExportFromCjs(enigmaMocker.exports);

/* eslint no-underscore-dangle: 0 */

const __DO_NOT_USE__ = {
  generator: generatorFn,
  hook,
  theme,
  locale,
  EnigmaMocker
};

export { __DO_NOT_USE__, conversion, index as embed, onTakeSnapshot, useAction, useApp, useAppLayout, useConstraints, useDeviceType, useEffect, useElement, useEmbed, useGlobal, useImperativeHandle, useKeyboard, useLayout, useMemo, useModel, useOptions, usePlugins, usePromise, useRect, useRenderState, useSelections, useStaleLayout, useState, useTheme, useTranslator };
//# sourceMappingURL=dev.js.map