@nebula.js/stardust
Version:
Product and framework agnostic integration API for Qlik's Associative Engine
49,243 lines • 1.85 MB
JavaScript
/*
* @nebula.js/stardust v6.3.0
* Copyright (c) 2025 QlikTech International AB
* Released under the MIT license.
*/
System.register([], (function (exports, module) {
'use strict';
return {
execute: (function () {
function _mergeNamespaces(n, m) {
m.forEach(function (e) {
e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
if (k !== 'default' && !(k in n)) {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
});
return Object.freeze(n);
}
exports({
A: useDeviceType,
B: useNavigation,
C: usePlugins,
D: useConstraints,
E: useInteractionState,
F: useOptions,
G: useEmbed,
H: useRenderState,
I: useEmitter,
J: onTakeSnapshot,
K: onContextMenu,
a: isNode,
c: cleanFalsyValues,
e: useEffect,
f: useMemo,
g: useImperativeHandle,
h: useKeyboard,
i: isBrowser$1,
j: usePromise,
k: useAction,
l: useRect,
n: useModel,
o: useApp,
p: useGlobal,
q: useElement,
r: useSelections,
s: sortKeys,
t: useTheme,
u: useState,
v: useLayout,
w: useRef,
x: useStaleLayout,
y: useAppLayout,
z: useTranslator
});
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.
*/
var hasRequiredRuntime;
function requireRuntime () {
if (hasRequiredRuntime) return runtime.exports;
hasRequiredRuntime = 1;
(function (module) {
var runtime = (function (exports$1) {
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; };
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.
defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) });
return generator;
}
exports$1.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;
defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: true });
defineProperty(
GeneratorFunctionPrototype,
"constructor",
{ value: GeneratorFunction, configurable: true }
);
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$1.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$1.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$1.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).
defineProperty(this, "_invoke", { value: enqueue });
}
defineIteratorMethods(AsyncIterator.prototype);
define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
return this;
});
exports$1.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$1.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$1.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 GeneratorResume behavior specified since ES2015:
// ES2015 spec, step 3: https://262.ecma-international.org/6.0/#sec-generatorresume
// Latest spec, step 2: https://tc39.es/ecma262/#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 methodName = context.method;
var method = delegate.iterator[methodName];
if (method === undefined$1) {
// A .throw or .return when the delegate iterator has no .throw
// method, or a missing .next method, always terminate the
// yield* loop.
context.delegate = null;
// Note: ["return"] must be used for ES3 parsing compatibility.
if (methodName === "throw" && 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;
}
}
if (methodName !== "return") {
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a '" + methodName + "' 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$1.keys = function(val) {
var object = Object(val);
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 != null) {
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;
}
}
throw new TypeError(typeof iterable + " is not iterable");
}
exports$1.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$1;
}(
// 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));
return runtime.exports;
}
requireRuntime();
function _asyncIterator(r) {
var n,
t,
o,
e = 2;
for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {
if (t && null != (n = r[t])) return n.call(r);
if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
t = "@@asyncIterator", o = "@@iterator";
}
throw new TypeError("Object is not async iterable");
}
function AsyncFromSyncIterator(r) {
function AsyncFromSyncIteratorContinuation(r) {
if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object."));
var n = r.done;
return Promise.resolve(r.value).then(function (r) {
return {
value: r,
done: n
};
});
}
return AsyncFromSyncIterator = function (r) {
this.s = r, this.n = r.next;
}, AsyncFromSyncIterator.prototype = {
s: null,
n: null,
next: function () {
return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
},
return: function (r) {
var n = this.s.return;
return void 0 === n ? Promise.resolve({
value: r,
done: true
}) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
},
throw: function (r) {
var n = this.s.return;
return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
}
}, new AsyncFromSyncIterator(r);
}
function _defineProperty(e, r, t) {
return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: true,
configurable: true,
writable: true
}) : e[r] = t, e;
}
function _extends$1() {
return _extends$1 = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, _extends$1.apply(null, arguments);
}
function ownKeys(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function (r) {
return Object.getOwnPropertyDescriptor(e, r).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function _objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
_defineProperty(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
function _objectWithoutProperties(e, t) {
if (null == e) return {};
var o,
r,
i = _objectWithoutPropertiesLoose$1(e, t);
if (Object.getOwnPropertySymbols) {
var n = Object.getOwnPropertySymbols(e);
for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
}
return i;
}
function _objectWithoutPropertiesLoose$1(r, e) {
if (null == r) return {};
var t = {};
for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
if (-1 !== e.indexOf(n)) continue;
t[n] = r[n];
}
return t;
}
function _toPrimitive(t, r) {
if ("object" != typeof t || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r);
if ("object" != typeof i) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
function _toPropertyKey(t) {
var i = _toPrimitive(t, "string");
return "symbol" == typeof i ? i : i + "";
}
//#region src/utils/utils.ts
/**
* Returns true if the running environment is a browser-like environment
*/
function isBrowser$1() {
if (typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.self !== "undefined") return true;
return false;
}
/**
* Returns true if the running environment is a node-like environment
*/
function isNode() {
if (typeof process !== "undefined" && process.version && process.versions.node) return true;
return false;
}
/**
* Checks if a value is a plain object (not an array, null, or any other type).
* @param value The value to check
* @returns true if the value is a plain object, false otherwise
*/
function isPlainObject$1(value) {
return typeof value === "object" && value !== null && value.constructor === Object;
}
/**
* Recursively sorts the keys of an object or array of objects.
* If the input is an array, it sorts each object in the array.
* If the input is an object, it sorts the keys of the object.
* If the input is neither an object nor an array, it returns the input as is.
* @param obj Object to sort keys of
* @template T Type of the object
* @returns sorted object or array of objects
* @example
* const obj = { b: 2, a: 1, c: { d: 4, b: 3 } };
* const sortedObj = sortKeys(obj);
* // sortedObj will be { a: 1, b: 2, c: { b: 3, d: 4 } }
*/
function sortKeys(obj) {
if (Array.isArray(obj)) return obj.map(sortKeys);
else if (isPlainObject$1(obj)) {
const sortedObj = {};
for (const key of Object.keys(obj).sort()) sortedObj[key] = sortKeys(obj[key]);
return sortedObj;
}
return obj;
}
/**
* Cleans an object by removing all properties that are falsy (null, undefined, false, 0, "", NaN).
* strings that are empty after trimming will also be removed.
* @param obj The object to clean
* @returns A new object with all falsy values removed
*/
function cleanFalsyValues(obj) {
if (Array.isArray(obj)) return obj.map((item) => typeof item === "object" && item !== null ? cleanFalsyValues(item) : item).filter((item) => {
if (typeof item === "object" && item !== null) return Object.keys(item).length > 0;
return item !== null && item !== void 0 && item !== "";
});
else if (typeof obj === "object" && obj !== null) {
const cleaned = {};
for (const key of Object.keys(obj)) {
const value = obj[key];
switch (typeof value) {
case "undefined": break;
case "boolean":
if (value) cleaned[key] = value;
break;
case "string": {
const trimmed = value.trim();
if (trimmed !== "") cleaned[key] = trimmed;
break;
}
case "object": {
if (value === null) break;
const cleanedValue = cleanFalsyValues(value);
if (cleanedValue) {
if (Array.isArray(cleanedValue) && cleanedValue.length > 0 || typeof cleanedValue === "object" && Object.keys(cleanedValue).length > 0) cleaned[key] = cleanedValue;
}
break;
}
case "function":
case "number":
cleaned[key] = value;
break;
default:
console.warn(`Unexpected type for key "${key}": ${typeof value}`);
cleaned[key] = value;
break;
}
}
if (Object.keys(cleaned).length === 0) return;
return cleaned;
}
return obj;
}
//#region src/public/public-runtime-modules.ts
const isNode$1 = isNode();
const importRuntimeModulePromise = (async () => {
if (isNode$1) return () => {
throw new Error("importRuntimeModule cannot be used in a Node.js context");
};
return (await module.import('./dist-CdktrY2F-CQdIunMv.js')).importRuntimeModule;
})();
/**
* @param hostConfig
* @returns
*/
async function getAuthRuntimeModule(hostConfig) {
if (isNode$1) return module.import('./auth-sNi1A67--Belh4pQc.js');
return (await importRuntimeModulePromise)("auth@v1", hostConfig);
}
//#region src/public/auth.ts
/**
* Registers an auth module that can handle authentication. An auth module is used by specifying its name as authType in the HostConfig passed in to api calls.
* @param name the name of the module
* @param authModule the implementation of the AuthModule interface
*/
function registerAuthModule(name, authModule) {
getAuthRuntimeModule().then((impl) => impl.registerAuthModule(name, authModule));
}
/**
* Sets the default host config that will be used for all api calls that do not include a HostConfig
* @param hostConfig the default HostConfig to use
*/
function setDefaultHostConfig(hostConfig) {
getAuthRuntimeModule(hostConfig).then((impl) => impl.setDefaultHostConfig(hostConfig));
}
/**
* Registers a host config with the given name.
* @param name The name of the host config to be used to reference the host config later.
* @param hostConfig The host config to register.
*/
function registerHostConfig(name, hostConfig) {
getAuthRuntimeModule(hostConfig).then((impl) => impl.registerHostConfig(name, hostConfig));
}
/**
* Unregisters a host config with the given name.
* @param name The name of the host config to unregister.
*/
function unregisterHostConfig(name) {
getAuthRuntimeModule().then((impl) => impl.unregisterHostConfig(name));
}
/**
* Returns an access token using the supplied host config. Typically used on the backend to supply the access token to the frontend
*/
async function getAccessToken({ hostConfig }) {
return getAuthRuntimeModule(hostConfig).then((impl) => impl.getAccessToken({ hostConfig }));
}
/**
* Returns a record of query parameters that needs to be added to resources requests, e.g.
* image tags, etc.
*/
async function getWebResourceAuthParams({ hostConfig }) {
return getAuthRuntimeModule(hostConfig).then((impl) => impl.getWebResourceAuthParams({ hostConfig }));
}
var auth_default = {
registerAuthModule,
setDefaultHostConfig,
registerHostConfig,
unregisterHostConfig,
getAccessToken,
getWebResourceAuthParams
};
var react = {exports: {}};
var react_production_min = {};
/**
* @license React
* react.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 hasRequiredReact_production_min;
function requireReact_production_min () {
if (hasRequiredReact_production_min) return react_production_min;
hasRequiredReact_production_min = 1;
var l=Symbol.for("react.element"),n=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),q=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),t=Symbol.for("react.provider"),u=Symbol.for("react.context"),v=Symbol.for("react.forward_ref"),w=Symbol.for("react.suspense"),x=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),z=Symbol.iterator;function A(a){if(null===a||"object"!==typeof a)return null;a=z&&a[z]||a["@@iterator"];return "function"===typeof a?a:null}
var B={isMounted:function(){return false},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B;}E.prototype.isReactComponent={};
E.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState");};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate");};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B;}var H=G.prototype=new F;
H.constructor=G;C(H,E.prototype);H.isPureReactComponent=true;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:true,ref:true,__self:true,__source:true};
function M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=""+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1<g){for(var f=Array(g),m=0;m<g;m++)f[m]=arguments[m+2];c.children=f;}if(a&&a.defaultProps)for(d in g=a.defaultProps,g) void 0===c[d]&&(c[d]=g[d]);return {$$typeof:l,type:a,key:k,ref:h,props:c,_owner:K.current}}
function N(a,b){return {$$typeof:l,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function O(a){return "object"===typeof a&&null!==a&&a.$$typeof===l}function escape(a){var b={"=":"=0",":":"=2"};return "$"+a.replace(/[=:]/g,function(a){return b[a]})}var P=/\/+/g;function Q(a,b){return "object"===typeof a&&null!==a&&null!=a.key?escape(""+a.key):b.toString(36)}
function R(a,b,e,d,c){var k=typeof a;if("undefined"===k||"boolean"===k)a=null;var h=false;if(null===a)h=true;else switch(k){case "string":case "number":h=true;break;case "object":switch(a.$$typeof){case l:case n:h=true;}}if(h)return h=a,c=c(h),a=""===d?"."+Q(h,0):d,I(c)?(e="",null!=a&&(e=a.replace(P,"$&/")+"/"),R(c,b,e,"",function(a){return a})):null!=c&&(O(c)&&(c=N(c,e+(!c.key||h&&h.key===c.key?"":(""+c.key).replace(P,"$&/")+"/")+a)),b.push(c)),1;h=0;d=""===d?".":d+":";if(I(a))for(var g=0;g<a.length;g++){k=
a[g];var f=d+Q(k,g);h+=R(k,b,e,f,c);}else if(f=A(a),"function"===typeof f)for(a=f.call(a),g=0;!(k=a.next()).done;)k=k.value,f=d+Q(k,g++),h+=R(k,b,e,f,c);else if("object"===k)throw b=String(a),Error("Objects are not valid as a React child (found: "+("[object Object]"===b?"object with keys {"+Object.keys(a).join(", ")+"}":b)+"). If you meant to render a collection of children, use an array instead.");return h}
function S(a,b,e){if(null==a)return a;var d=[],c=0;R(a,d,"","",function(a){return b.call(e,a,c++)});return d}function T(a){if(-1===a._status){var b=a._result;b=b();b.then(function(b){if(0===a._status||-1===a._status)a._status=1,a._result=b;},function(b){if(0===a._status||-1===a._status)a._status=2,a._result=b;});-1===a._status&&(a._status=0,a._result=b);}if(1===a._status)return a._result.default;throw a._result;}
var U={current:null},V={transition:null},W={ReactCurrentDispatcher:U,ReactCurrentBatchConfig:V,ReactCurrentOwner:K};function X(){throw Error("act(...) is not supported in production builds of React.");}
react_production_min.Children={map:S,forEach:function(a,b,e){S(a,function(){b.apply(this,arguments);},e);},count:function(a){var b=0;S(a,function(){b++;});return b},toArray:function(a){return S(a,function(a){return a})||[]},only:function(a){if(!O(a))throw Error("React.Children.only expected to receive a single React element child.");return a}};react_production_min.Component=E;react_production_min.Fragment=p;react_production_min.Profiler=r;react_production_min.PureComponent=G;react_production_min.StrictMode=q;react_production_min.Suspense=w;
react_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=W;react_production_min.act=X;
react_production_min.cloneElement=function(a,b,e){if(null===a||void 0===a)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+a+".");var d=C({},a.props),c=a.key,k=a.ref,h=a._owner;if(null!=b){ void 0!==b.ref&&(k=b.ref,h=K.current);void 0!==b.key&&(c=""+b.key);if(a.type&&a.type.defaultProps)var g=a.type.defaultProps;for(f in b)J.call(b,f)&&!L.hasOwnProperty(f)&&(d[f]=void 0===b[f]&&void 0!==g?g[f]:b[f]);}var f=arguments.length-2;if(1===f)d.children=e;else if(1<f){g=Array(f);
for(var m=0;m<f;m++)g[m]=arguments[m+2];d.children=g;}return {$$typeof:l,type:a.type,key:c,ref:k,props:d,_owner:h}};react_production_min.createContext=function(a){a={$$typeof:u,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};a.Provider={$$typeof:t,_context:a};return a.Consumer=a};react_production_min.createElement=M;react_production_min.createFactory=function(a){var b=M.bind(null,a);b.type=a;return b};react_production_min.createRef=function(){return {current:null}};
react_production_min.forwardRef=function(a){return {$$typeof:v,render:a}};react_production_min.isValidElement=O;react_production_min.lazy=function(a){return {$$typeof:y,_payload:{_status:-1,_result:a},_init:T}};react_production_min.memo=function(a,b){return {$$typeof:x,type:a,compare:void 0===b?null:b}};react_production_min.startTransition=function(a){var b=V.transition;V.transition={};try{a();}finally{V.transition=b;}};react_production_min.unstable_act=X;react_production_min.useCallback=function(a,b){return U.current.useCallback(a,b)};react_production_min.useContext=function(a){return U.current.useContext(a)};
react_production_min.useDebugValue=function(){};react_production_min.useDeferredValue=function(a){return U.current.useDeferredValue(a)};react_production_min.useEffect=function(a,b){return U.current.useEffect(a,b)};react_production_min.useId=function(){return U.current.useId()};react_production_min.useImperativeHandle=function(a,b,e){return U.current.useImperativeHandle(a,b,e)};react_production_min.useInsertionEffect=function(a,b){return U.current.useInsertionEffect(a,b)};react_production_min.useLayoutEffect=function(a,b){return U.current.useLayoutEffect(a,b)};
react_production_min.useMemo=function(a,b){return U.current.useMemo(a,b)};react_production_min.useReducer=function(a,b,e){return U.current.useReducer(a,b,e)};react_production_min.useRef=function(a){return U.current.useRef(a)};react_production_min.useState=function(a){return U.current.useState(a)};react_production_min.useSyncExternalStore=function(a,b,e){return U.current.useSyncExternalStore(a,b,e)};react_production_min.useTransition=function(){return U.current.useTransition()};react_production_min.version="18.3.1";
return react_production_min;
}
var hasRequiredReact;
function requireReact () {
if (hasRequiredReact) return react.exports;
hasRequiredReact = 1;
{
react.exports = requireReact_production_min();
}
return react.exports;
}
var reactExports = requireReact();
var React = /*@__PURE__*/getDefaultExportFromCjs(reactExports);
var React$1 = /*#__PURE__*/_mergeNamespaces({
__proto__: null,
default: React
}, [reactExports]);
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# */{
/**
* Returns current locale.
* @param {string=} lang - language Locale to updated the currentLocale value
* @returns {string} current locale.
*/
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 Accessibility_Object_NoTitle = {
id: "Accessibility.Object.NoTitle",
locale: {
"de-DE": "Kein Titel",
"en-US": "No title",
"es-ES": "Sin título",
"fr-FR": "Pas de titre",
"it-IT": "Nessun titolo",
"ja-JP": "タイトルなし",
"ko-KR": "제목 없음",
"nl-NL": "Geen titel",
"pl-PL": "Brak tytułu",
"pt-BR": "Sem título",
"ru-RU": "Без заголовка",
"sv-SE": "Ingen rubrik",
"tr-TR": "Başlık yok",
"zh-CN": "无标题",
"zh-TW": "無標題"
}
};
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_Clear_Search = {
id: "Listbox.Clear.Search",
locale: {
"de-DE": "Suche löschen",
"en-US": "Clear search",
"es-ES": "Borrar búsqueda",
"fr-FR": "Effacer la recherche",
"it-IT": "Cancella ricerca",
"ja-JP": "検索をクリア",
"ko-KR": "검색 지우기",
"nl-NL": "Zoekopdracht wissen",
"pl-PL": "Wyczyść wyszukiwanie",
"pt-BR": "Limpar pesquisa",
"ru-RU": "Очистить поиск",
"sv-SE": "Radera sökning",
"tr-TR": "Aramayı temizle",
"zh-CN": "清除搜索",
"zh-TW": "清除搜尋"
}
};
var Listbox_Cyclic = {
id: "Listbox.Cyclic",
locale: {
"de-DE": "Zyklische Dimension",
"en-US": "Cyclic dimension",
"es-ES": "Dimensión cíclica",
"fr-FR": "Dimension cyclique",
"it-IT": "Dimensione ciclica",
"ja-JP": "サイクリック軸",
"ko-KR": "순환 차원",
"nl-NL": "Cyclische dimensie",
"pl-PL": "Wymiar cykliczny",
"pt-BR": "Dimensão cíclica",
"ru-RU": "Циклическое измерение",
"sv-SE": "Cyklisk dimension",
"tr-TR": "Döngüsel boyut",
"zh-CN": "循环维度",
"zh-TW": "循環維度"
}
};
var Listbox_Dismiss = {
id: "Listbox.Dismiss",
locale: {
"de-DE": "Schließen",
"en-US": "Dismiss",
"es-ES": "Descartar",
"fr-FR": "Ignorer",
"it-IT": "Ignora",
"ja-JP": "却下",
"ko-KR": "해제",
"nl-NL": "Overslaan",
"pl-PL": "Zamknij",
"pt-BR": "Ignorar",
"ru-RU": "Пропустить",
"sv-SE": "Hoppa över",
"tr-TR": "Kapat",
"zh-CN": "离开",
"zh-TW": "解除"
}
};
var Listbox_DrillDown = {
id: "Listbox.DrillDown",
locale: {
"de-DE": "Drilldown-Dimension",
"en-US": "Drill-down dimension",
"es-ES": "Dimensión jerárquica",
"fr-FR": "Dimension hiérarchique",
"it-IT": "Dimensione drill-down",
"ja-JP": "軸のドリルダウン",
"ko-KR": "드릴다운 차원",
"nl-NL": "Drill-downdimensie",
"pl-PL": "Wymiar hierarchiczny",
"pt-BR": "Dimensão de detalhamento",
"ru-RU": "Детализированное измерение",
"sv-SE": "Hierarkisk dimension",
"tr-TR": "Detaya inme boyutu",
"zh-CN": "钻取维度",
"zh-TW": "向下探查維度"
}
};
var Listbox_ItemsOverflow = {
id: "Listbox.ItemsOverflow",
locale: {
"de-DE": "Derzeit wird ein eingeschränkter Datensatz angezeigt, verwenden Sie die Suche, um die Größe zu reduzieren",
"en-US": "Currently showing a limited data set, use search to reduce the size",
"es-ES": "Actualmente se muestra un conjunto de datos limitado, utilice la búsqueda para reducir el tamaño",
"fr-FR": "Ensemble de données limité actuellement affiché. Utilisez la rechercher pour réduire la taille.",
"it-IT": "Attualmente visualizzato un set di dati limitato; utilizzare la ricerca per ridurre le dimensioni",
"ja-JP": "現在表示されているデータ セットは制限されているため、検索を使ってサイズを縮小してください",
"ko-KR": "현재 제한된 데이터 집합이 표시되고 있습니다. 검색을 사용하여 크기를 줄이십시오.",
"nl-NL": "Er wordt momenteel een beperkte gegevensverzameling getoond, gebruik Zoeken om de omvang te verkleinen",
"pl-PL": "Wyświetlany jest ograniczony zestaw danych. Użyj wyszukiwania, aby zmniejszyć rozmiar.",
"pt-BR": "Atualmente mostrando um conjunto de dados limitado, use a pesquisa para reduzir o tamanho",
"ru-RU": "Сейчас отображается ограниченный набор данных. Используйте поиск, чтобы уменьшить размер.",
"sv-SE": "En begränsad datauppsättning visas. Använd sök för att minska storleken",
"tr-TR": "Şu anda sınırlı bir veri kümesi gösteriliyor. Boyutu azaltmak için arama işlevini kullanın",
"zh-CN": "目前显示有限的数据集,使用搜索来减少大小",
"zh-TW": "目前顯示有限資料集,請使用搜尋減少大小"
}
};
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_NoMatchesForYourTerms = {
id: "Listbox.NoMatchesForYourTerms",
locale: {
"de-DE": "Für Ihre Suche wurden keine Übereinstimmungen gefunden.",
"en-US": "There are no matches for your search.",
"es-ES": "No hay resultados para su búsqueda.",
"fr-FR": "Aucun résultat ne correspond à votre recherche.",
"it-IT": "Non è stata trovata alcuna corrispondenza per questa ricerca.",
"ja-JP": "検索に一致するものがありません。",
"ko-KR": "검색에 대해 일치하는 항목이 없습니다.",
"nl-NL": "Er zijn geen overeenkomsten voor uw zoekopdracht.",
"pl-PL": "Brak dopasowań dla tego wyszukiwania.",
"pt-BR": "Não há correspondências para sua pesquisa.",
"ru-RU": "Нет совпадений по вашему поисковому запросу.",
"sv-SE": "Det finns inga matchningar för din sökning.",
"tr-TR": "Aramanızla eşleşen sonuç yok.",
"zh-CN": "您的搜索条件没有任何匹配结果。",
"zh-TW": "沒有與您搜尋相符的項目。"
}
};
var Listbox_ResultFilterLabel = {
id: "Listbox.ResultFilterLabel",
locale: {
"de-DE": "Suchergebnisfilter",
"en-US": "Search Results Filter",
"es-ES": "Filtro de resultados de búsqueda",
"fr-FR": "Filtre de résultats de recherche",
"it-IT": "Filtro risultati Ricerca",
"ja-JP": "検索結果フィルター",
"ko-KR": "검색 결과 필터",
"nl-NL": "Filter voor zoekresultaten",
"pl-PL": "Filtr wyników wyszukiwania",
"pt-BR": "Filtro de resultados da pesquisa",
"ru-RU": "Фильтр результатов поиска",
"sv-SE": "Filter för sökresultat",
"tr-TR": "Arama Sonuçları Filtresi",
"zh-CN": "搜索结果筛选器",
"zh-TW": "搜尋結果篩選"
}
};
var Listbox_ScreenReader_SearchThenSelectionsMenu_WithAccSelMenu = {
id: "Listbox.ScreenReader.SearchThenSelectionsMenu.WithAccSelMenu",
locale: {
"de-DE": "Drücken Sie die Umschalttaste zusammen mit der Tabulatortaste, um den Fokus in die Suchleiste zu setzen, und dann erneut beide Tasten, um den Fokus in das Auswahlmenü zu setzen.",
"en-US": "Press Shift plus Tab to set focus on the search bar, then Shift plus Tab again to set focus on the selections menu.",
"es-ES": "Pulse Mayús + Tabulador para establecer el foco en la barra de búsqueda, luego Mayús + Tabulador nuevamente para establecer el foco en el menú de selecciones.",
"fr-FR": "Appuyez sur Maj + Tab pour mettre le focus sur la barre de recherche, puis de nouveau sur Maj + Tab pour mettre le focus sur le menu de sélections.",
"it-IT": "Premere MAIUSC+TAB per impostare lo stato attivo sulla barra di ricerca, quindi premere nuovamente MAIUSC+TAB per impostare lo stato attivo sul menu selezioni.",
"ja-JP": "Shift + Tab を押して検索バーにフォーカスを設定し、Shift + Tab をもう一度押して選択メニューにフォーカスを設定します。",
"ko-KR": "Shift+Tab을 눌러 검색 막대에 초점을 맞춘 다음 Shift+Tab을 다시 눌러 선택 메뉴에 초점을 맞추십시오.",
"nl-NL": "Druk op Shift + Tab om de focus in te stellen op de zoekbalk, druk vervolgens nogmaals op Shift + Tab om de focus in te stellen op het selectiemenu.",
"pl-PL": "Naciśnij Shift i Tab, aby ustawić ostrość na pasku wyszukiwania. Następnie ponownie użyj tej kombinacji klawiszy, aby ustawić ostrość na menu wyboru.",
"pt-BR": "Pressione Shift + Tab para definir o foco na barra de pesquisa e Shift + Tab novamente para definir o foco no menu de seleções.",
"ru-RU": "Нажмите клавиши SHIFT+TAB, чтобы переключиться на строку поиска. Затем снова нажмите клавиши SHIFT+TAB, чтобы переключиться на меню выбора.",
"sv-SE": "Tryck på Skift plus Tabb för att ställa in fokus på sökfältet, sedan Skift plus Tabb igen för att ställa in fokus på urvalsmenyn.",
"tr-TR": "Odağı arama çubuğuna ayarlamak için Shift ve Sekme tuşlarına birlikte basın, ardından bu tuşlara birlikte tekrar basarak odağı seçim menüsüne ayarlayın.",
"zh-CN": "按 Shift+Tab 在搜索栏上设置焦点,然后再次按 Shift+Tab 在“选择”菜单上设置焦点。",
"zh-TW": "按下 Shift 加 Tab 鍵以設定搜尋列上的焦點,然後再次按下 Shift 加 Tab 鍵,以設定選項功能表上的焦點。"
}
};
var Listbox_ScreenReader_SelectionMenu_WithAccSelMenu = {
id: "Listbox.ScreenReader.SelectionMenu.WithAccSelMenu",
locale: {
"de-DE": "Drücken Sie gleichzeitig die Umschalt- und die Tabulatortaste, um den Fokus in das Auswahlmenü zu setzen.",
"en-US": "Press Shift plus Tab to set focus on the selections menu.",
"es-ES": "Pulse Mayús + Tabulador para establecer el foco en el menú de selecciones.",
"fr-FR": "Appuyez sur Maj + Tab pour mettre le focus sur le menu de sélections.",
"it-IT": "Premere i tasti MAIUSC+TAB per evidenziare il menu di selezione.",
"ja-JP": "Shift キー + Tab キーを押して選択メニューにフォーカスを設定します。",
"ko-KR": "선택 메뉴에 초점을 설정하려면 Shift+Tab을 누르십시오.",
"nl-NL": "Druk op Shift + Tab om de focus in te stellen op het selectiemenu.",
"pl-PL": "Naciśnij Shift i Tab, aby ustawić ostrość na menu wyboru.",
"pt-BR": "Pressione Shift + Tab para definir o foco sobre o menu de seleções.",
"ru-RU": "Нажмите клавиши SHIFT+TAB, чтобы переключиться на меню выбора.",
"sv-SE": "Tryck på Skift plus Tabb när du vill ställa in fokus på urvalsmenyn.",
"tr-TR": "Odağı seçim menüsüne ayarlamak için Shift ve Sekme tuşlarına birlikte basın.",
"zh-CN": "按下 Shift 加 Tab 以将焦点设置在选择菜单上。",
"zh-TW": "按下 Shift 加 Tab 以在選項功能表上設定焦點。"
}
};
var Listbox_ScreenReaderInstructions = {
id: "Listbox.ScreenReaderInstructions",
locale: {
"de-DE": "Bei Aktivierung der Elemente unten wird der Seiteninhalt aktualisiert",
"en-US": "Activating the elements below will cause content on the page to be updated",
"es-ES": "La activación de los elementos siguientes hará que se actualice el contenido en la página",
"fr-FR": "L'activation des éléments ci-dessous actualisera le contenu de la page.",
"it-IT": "L'attivazione degli elementi sottostanti causerà l'aggiornamento del contenuto della pagina",
"ja-JP": "下記の要素をアクティブ化すると、ページのコンテンツが更新されます",
"ko-KR": "아래 요소를 활성화하면 페이지의 콘텐츠가 업데이트됩니다.",
"nl-NL": "Door de onderstaande elementen te activeren wordt de inhoud op de pagina bijgewerkt",
"pl-PL": "Aktywacja poniższych elementów spowoduje aktualizację zawartości na stronie",
"pt-BR": "A ativação dos elementos abaixo fará com que o conteúdo da página seja atualizado",
"ru-RU": "Активация приведенных ниже элементов приведет к обновлению содержимого страницы",
"sv-SE": "Om du aktiverar elementen nedan kommer innehåll på sidan att uppdateras",
"tr-TR": "Aşağıdaki öğeleri etkinleştirmek sayfadaki içeriğin güncellenmesine neden olur",
"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_Search_ScreenReaderInstructions = {
id: "Listbox.Search.ScreenReaderInstructions",
locale: {
"de-DE": "Über das folgende Suchfeld werden Ergebnisse während der Eingabe gefiltert",
"en-US": "The following search field filters results below as you type",
"es-ES": "El siguiente campo de búsqueda filtra los resultados siguientes a medida que escribe",
"fr-FR": "Le champ de recherche suivant filtrer les résultats ci-dessous à mesure de votre saisie.",
"it-IT": "Il seguente campo di ricerca filtra i risultati man mano che vengono digitati",
"ja-JP": "次の検索フィールドは、入力と同時に下記の結果をフィルターします",
"ko-KR": "다음 검색 필드는 입력할 때 아래의 결과를 필터링합니다.",
"nl-NL": "Het volgende zoekveld filtert resultaten terwijl u typt",
"pl-PL": "Następujące pole wyszukiwania filtruje wyniki poniżej w miarę pisania",
"pt-BR": "O campo de pesquisa a seguir filtra os resultados abaixo conforme você digita",
"ru-RU": "Следующее поле поиска фильтрует результаты ниже по мере ввода текста",
"sv-SE": "Följande sökfält filtrerar resultaten nedan medan du skriver",
"tr-TR": "Aşağıdaki arama alanı siz yazarken aşağıdaki sonuçları filtreler",
"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_ActionButton = {
id: "Object.ActionButton",
locale: {
"de-DE": "Schaltfläche",
"en-US": "Button",
"es-ES": "Botón",
"fr-FR": "Bouton",
"it-IT": "Pulsante",
"ja-JP": "ボタン",
"ko-KR": "버튼",
"nl-NL": "Knop",
"pl-PL": "Przycisk",
"pt-BR": "Botão",
"ru-RU": "Кнопка",
"sv-SE": "Knapp",
"tr-TR": "Düğme",
"zh-CN": "按钮",
"zh-TW": "按鈕"
}
};
var Object_AutoChart = {
id: "Object.AutoChart",
locale: {
"de-DE": "Automatisches Diagramm",
"en-US": "Autochart",
"es-ES": "Gráfico automático",
"fr-FR": "Graphique automatique",
"it-IT": "Grafico automatico",
"ja-JP": "オートチャート",
"ko-KR": "자동 차트",
"nl-NL": "Automatisch diagram",
"pl-PL": "Automatyczny wykres",
"pt-BR": "Gráfico automático",
"ru-RU": "Автодиаграмма",
"sv-SE": "Automatiskt diagram",
"tr-TR": "Otomatik grafik",
"zh-CN": "自动图表",
"zh-TW": "自動圖表"
}
};
var Object_BarChart = {
id: "Object.BarChart",
locale: {
"de-DE": "Balkendiagramm",
"en-US": "Bar chart",
"es-ES": "Gráfico de barras",
"fr-FR": "Graphique en barres",
"it-IT": "Grafico a barre",
"ja-JP": "棒グラフ",
"ko-KR": "막대형 차트",
"nl-NL": "Staafdiagram",
"pl-PL": "Wykres słupkowy",
"pt-BR": "Gráfico de barras",
"ru-RU": "Линейчатая диаграмма",
"sv-SE": "Stapeldiagram",
"tr-TR": "Sütun grafik",
"zh-CN": "条形图",
"zh-TW": "長條圖"
}
};
var Object_BoxPlot = {
id: "Object.BoxPlot",
locale: {
"de-DE": "Boxplot",
"en-US": "Box plot",
"es-ES": "Diagrama de caja",
"fr-FR": "Boîte à moustaches",
"it-IT": "Box plot",
"ja-JP": "ボックス プロット",
"ko-KR": "상자 그림",
"nl-NL": "Boxplot",
"pl-PL": "Wykres pudełkowy",
"pt-BR": "Plotagem de caixa",
"ru-RU": "Блочная диаграмма",
"sv-SE": "Lådagram",
"tr-TR": "Kutu çizimi",
"zh-CN": "框图",
"zh-TW": "盒狀圖"
}
};
var Object_BulletChart = {
id: "Object.BulletChart",
locale: {
"de-DE": "Bullet-Diagramm",
"en-US": "Bullet chart",
"es-ES": "Gráfico de viñetas",
"fr-FR": "Graphique à puces",
"it-IT": "Grafico bullet",
"ja-JP": "ブレット チャート",
"ko-KR": "글머리 기호 차트",
"nl-NL": "Bulletgrafiek",
"pl-PL": "Wykres pociskowy",
"pt-BR": "Quadro comparativo",
"ru-RU": "Диаграмма Буллет",
"sv-SE": "Nyansdiagram",
"tr-TR": "Madde imli grafik",
"zh-CN": "子弹图",
"zh-TW": "子彈圖"
}
};
var Object_ComboChart = {
id: "Object.ComboChart",
locale: {
"de-DE": "Kombi-Diagramm",
"en-US": "Combo chart",
"es-ES": "Gráfico combinado",
"fr-FR": "Graphique combiné",
"it-IT": "Grafico combinato",
"ja-JP": "コンボ チャート",
"ko-KR": "콤보 차트",
"nl-NL": "Combinatiegrafiek",
"pl-PL": "Wykres kombi",
"pt-BR": "Gráfico de combinação",
"ru-RU": "Комбинированная диаграмма",
"sv-SE": "Kombinationsdiagram",
"tr-TR": "Birleşik grafik",
"zh-CN": "组合图",
"zh-TW": "組合圖"
}
};
var Object_Container = {
id: "Object.Container",
locale: {
"de-DE": "Sammelbox",
"en-US": "Container",
"es-ES": "Contenedor",
"fr-FR": "Conteneur",
"it-IT": "Contenitore",
"ja-JP": "コンテナー",
"ko-KR": "컨테이너",
"nl-NL": "Container",
"pl-PL": "Kontener",
"pt-BR": "Contêiner",
"ru-RU": "Контейнер",
"sv-SE": "Behållare",
"tr-TR": "Kapsayıcı",
"zh-CN": "容器",
"zh-TW": "容器"
}
};
var Object_DistributionPlot = {
id: "Object.DistributionPlot",
locale: {
"de-DE": "Verteilungsdiagramm",
"en-US": "Distribution plot",
"es-ES": "Diagrama de distribución",
"fr-FR": "Diagramme de distribution",
"it-IT": "Grafico di distribuzione",
"ja-JP": "分布プロット",
"ko-KR": "분포도",
"nl-NL": "Verdelingsplot",
"pl-PL": "Wykres rozkładu",
"pt-BR": "Gráfico de distribuição",
"ru-RU": "График распределения",
"sv-SE": "Fördelningsdiagram",
"tr-TR": "Dağılım grafiği",
"zh-CN": "分布图",
"zh-TW": "分佈圖"
}
};
var Object_FilterLabel_All = {
id: "Object.FilterLabel.All",
locale: {
"de-DE": "ALLES",
"en-US": "ALL",
"es-ES": "TODOS",
"fr-FR": "TOUT",
"it-IT": "TUTTI",
"ja-JP": "すべて",
"ko-KR": "모두",
"nl-NL": "ALLE",
"pl-PL": "WSZYSTKIE",
"pt-BR": "TODOS",
"ru-RU": "ВСЕ",
"sv-SE": "ALLA",
"tr-TR": "TÜMÜ",
"zh-CN": "全部",
"zh-TW": "全部"
}
};
var Object_FilterLabel_Exclude = {
id: "Object.FilterLabel.Exclude",
locale: {
"de-DE": "NICHT",
"en-US": "NOT",
"es-ES": "NO",
"fr-FR": "EXCLURE",
"it-IT": "NON",
"ja-JP": "除外",
"ko-KR": "제외",
"nl-NL": "NIET",
"pl-PL": "NIE",
"pt-BR": "NÃO",
"ru-RU": "НЕ",
"sv-SE": "INTE",
"tr-TR": "DEĞİL",
"zh-CN": "非",
"zh-TW": "不是"
}
};
var Object_FilterLabel_Unknown = {
id: "Object.FilterLabel.Unknown",
locale: {
"de-DE": "Unbekannt",
"en-US": "Unknown",
"es-ES": "Desconocido",
"fr-FR": "Inconnu",
"it-IT": "Sconosciuto",
"ja-JP": "不明",
"ko-KR": "알 수 없음",
"nl-NL": "Onbekend",
"pl-PL": "Nieznany",
"pt-BR": "Desconhecido",
"ru-RU": "Неизвестный",
"sv-SE": "Okänt",
"tr-TR": "Bilinmiyor",
"zh-CN": "未知",
"zh-TW": "未知"
}
};
var Object_FilterPane = {
id: "Object.FilterPane",
locale: {
"de-DE": "Filterfenster",
"en-US": "Filter pane",
"es-ES": "Panel de filtrado",
"fr-FR": "Panneau de filtre",
"it-IT": "Casella di filtro",
"ja-JP": "フィルター パネル",
"ko-KR": "필터 창",
"nl-NL": "Filtervak",
"pl-PL": "Panel filtrowania",
"pt-BR": "Painel de filtro",
"ru-RU": "Фильтр",
"sv-SE": "Filterruta",
"tr-TR": "Filtre bölmesi",
"zh-CN": "筛选器窗格",
"zh-TW": "篩選窗格"
}
};
var Object_FiltersApplied = {
id: "Object.FiltersApplied",
locale: {
"de-DE": "Angewendete Filter:",
"en-US": "Filters applied:",
"es-ES": "Filtros aplicados:",
"fr-FR": "Filtres appliqués :",
"it-IT": "Filtri applicati:",
"ja-JP": "適用されているフィルター:",
"ko-KR": "적용된 필터:",
"nl-NL": "Toegepaste filters:",
"pl-PL": "Zastosowane filtry:",
"pt-BR": "Filtros aplicados:",
"ru-RU": "Примененные фильтры:",
"sv-SE": "Använda filter:",
"tr-TR": "Uygulanan filtreler:",
"zh-CN": "应用的筛选器:",
"zh-TW": "篩選器已套用:"
}
};
var Object_FunnelChart = {
id: "Object.FunnelChart",
locale: {
"de-DE": "Trichterdiagramm",
"en-US": "Funnel chart",
"es-ES": "Gráfico de embudo",
"fr-FR": "Graphique en entonnoir",
"it-IT": "Grafico a imbuto",
"ja-JP": "ファネル チャート",
"ko-KR": "깔때기형 차트",
"nl-NL": "Trechterdiagram",
"pl-PL": "Wykres lejkowy",
"pt-BR": "Gráfico de funil",
"ru-RU": "Диаграмма Воронка",
"sv-SE": "Trattdiagram",
"tr-TR": "Huni grafik",
"zh-CN": "漏斗图",
"zh-TW": "漏斗圖"
}
};
var Object_Gauge = {
id: "Object.Gauge",
locale: {
"de-DE": "Messzeiger",
"en-US": "Gauge",
"es-ES": "Indicador",
"fr-FR": "Jauge",
"it-IT": "Misuratore",
"ja-JP": "ゲージ",
"ko-KR": "게이지",
"nl-NL": "Meter",
"pl-PL": "Miernik",
"pt-BR": "Mostrador",
"ru-RU": "Датчик",
"sv-SE": "Mätare",
"tr-TR": "Gösterge",
"zh-CN": "仪表",
"zh-TW": "量表"
}
};
var Object_GridChart = {
id: "Object.GridChart",
locale: {
"de-DE": "Matrixdiagramm",
"en-US": "Grid chart",
"es-ES": "Gráfico de cuadrícula",
"fr-FR": "Bulles",
"it-IT": "Grafico a griglia",
"ja-JP": "グリッド チャート",
"ko-KR": "그리드형 차트",
"nl-NL": "Rasterdiagram",
"pl-PL": "Wykres siatkowy",
"pt-BR": "Gráfico de grade",
"ru-RU": "Сетчатая диаграмма",
"sv-SE": "Rutnätsdiagram",
"tr-TR": "Izgara grafik",
"zh-CN": "网格图",
"zh-TW": "格線圖"
}
};
var Object_Histogram = {
id: "Object.Histogram",
locale: {
"de-DE": "Histogramm",
"en-US": "Histogram",
"es-ES": "Histograma",
"fr-FR": "Histogramme",
"it-IT": "Istogramma",
"ja-JP": "ヒストグラム",
"ko-KR": "히스토그램",
"nl-NL": "Histogram",
"pl-PL": "Histogram",
"pt-BR": "Histograma",
"ru-RU": "Гистограмма",
"sv-SE": "Histogram",
"tr-TR": "Histogram",
"zh-CN": "直方图",
"zh-TW": "色階分佈圖"
}
};
var Object_Kpi = {
id: "Object.Kpi",
locale: {
"de-DE": "KPI",
"en-US": "KPI",
"es-ES": "KPI",
"fr-FR": "ICP",
"it-IT": "KPI",
"ja-JP": "KPI",
"ko-KR": "KPI",
"nl-NL": "KPI",
"pl-PL": "Wskaźnik KPI",
"pt-BR": "KPI",
"ru-RU": "Ключевой показатель эффективности",
"sv-SE": "KPI (nyckeltal)",
"tr-TR": "KPI",
"zh-CN": "KPI",
"zh-TW": "KPI"
}
};
var Object_LayoutContainer = {
id: "Object.LayoutContainer",
locale: {
"de-DE": "Layout-Sammelbox",
"en-US": "Layout container",
"es-ES": "Contenedor de diseño",
"fr-FR": "Conteneur de disposition",
"it-IT": "Contenitore layout",
"ja-JP": "レイアウト コンテナ",
"ko-KR": "레이아웃 컨테이너",
"nl-NL": "Lay-outcontainer",
"pl-PL": "Kontener układu",
"pt-BR": "Contêiner de layout",
"ru-RU": "Контейнер макета",
"sv-SE": "Layoutbehållare",
"tr-TR": "Düzen kapsayıcısı",
"zh-CN": "布局容器",
"zh-TW": "版面配置容器"
}
};
var Object_LineChart = {
id: "Object.LineChart",
locale: {
"de-DE": "Liniendiagramm",
"en-US": "Line chart",
"es-ES": "Gráfico de líneas",
"fr-FR": "Graphique en courbes",
"it-IT": "Grafico lineare",
"ja-JP": "折れ線グラフ",
"ko-KR": "꺾은선형 차트",
"nl-NL": "Lijndiagram",
"pl-PL": "Wykres liniowy",
"pt-BR": "Gráfico de linhas",
"ru-RU": "Линейный график",
"sv-SE": "Linjediagram",
"tr-TR": "Çizgi grafik",
"zh-CN": "折线图",
"zh-TW": "折線圖"
}
};
var Object_Listbox = {
id: "Object.Listbox",
locale: {
"de-DE": "Listbox",
"en-US": "List box",
"es-ES": "Cuadro de lista",
"fr-FR": "Liste de sélection",
"it-IT": "Casella di elenco",
"ja-JP": "リスト ボックス",
"ko-KR": "목록 상자",
"nl-NL": "Keuzelijst",
"pl-PL": "Lista wartości",
"pt-BR": "Lista",
"ru-RU": "Список",
"sv-SE": "Listruta",
"tr-TR": "Liste kutusu",
"zh-CN": "列表框",
"zh-TW": "清單方塊"
}
};
var Object_Listbox_Alternative = {
id: "Object.Listbox.Alternative",
locale: {
"de-DE": "Alternative",
"en-US": "Alternative",
"es-ES": "Alternativo",
"fr-FR": "Alternatif",
"it-IT": "Alternativo",
"ja-JP": "代替",
"ko-KR": "대체 항목",
"nl-NL": "Alternatief",
"pl-PL": "Alternatywne",
"pt-BR": "Alternativo",
"ru-RU": "Альтернативные",
"sv-SE": "Alternativ",
"tr-TR": "Alternatif",
"zh-CN": "可选",
"zh-TW": "替代選項"
}
};
var Object_Listbox_Excluded = {
id: "Object.Listbox.Excluded",
locale: {
"de-DE": "Ausgeschlossen",
"en-US": "Excluded",
"es-ES": "Excluido",
"fr-FR": "Exclu",
"it-IT": "Escluso",
"ja-JP": "除外済み",
"ko-KR": "제외됨",
"nl-NL": "Uitgesloten",
"pl-PL": "Wykluczone",
"pt-BR": "Excluído",
"ru-RU": "Исключенные",
"sv-SE": "Uteslutet",
"tr-TR": "Hariç tutulan",
"zh-CN": "已排除",
"zh-TW": "已排除"
}
};
var Object_Listbox_ExcludedLock = {
id: "Object.Listbox.ExcludedLock",
locale: {
"de-DE": "Ausgeschlossene Sperre",
"en-US": "Excluded lock",
"es-ES": "Bloqueo excluido",
"fr-FR": "Exclu verrouillé",
"it-IT": "Blocco escluso",
"ja-JP": "除外されたロック",
"ko-KR": "제외된 잠금",
"nl-NL": "Uitsluitingsvergrendeling",
"pl-PL": "Wykluczone zablokowane",
"pt-BR": "Bloqueado excluído",
"ru-RU": "Блокировать исключенные элементы",
"sv-SE": "Uteslutet låst",
"tr-TR": "Hariç tutulan kilit",
"zh-CN": "已排除锁定",
"zh-TW": "已排除鎖定"
}
};
var Object_Listbox_Locked = {
id: "Object.Listbox.Locked",
locale: {
"de-DE": "Gesperrt",
"en-US": "Locked",
"es-ES": "Bloqueado",
"fr-FR": "Verrouillé",
"it-IT": "Bloccato",
"ja-JP": "ロック済み",
"ko-KR": "잠김",
"nl-NL": "Vergrendeld",
"pl-PL": "Zablokowane",
"pt-BR": "Bloqueado",
"ru-RU": "Заблокированные",
"sv-SE": "Låst",
"tr-TR": "Kilitli",
"zh-CN": "已锁定",
"zh-TW": "已鎖定"
}
};
var Object_Listbox_Optional = {
id: "Object.Listbox.Optional",
locale: {
"de-DE": "Optional",
"en-US": "Optional",
"es-ES": "Opcional",
"fr-FR": "Facultatif",
"it-IT": "Opzionale",
"ja-JP": "オプション",
"ko-KR": "선택 사항",
"nl-NL": "Optioneel",
"pl-PL": "Opcjonalne",
"pt-BR": "Opcional",
"ru-RU": "Дополнительные",
"sv-SE": "Valfritt",
"tr-TR": "İsteğe bağlı",
"zh-CN": "可选",
"zh-TW": "選用"
}
};
var Object_Listbox_Selected = {
id: "Object.Listbox.Selected",
locale: {
"de-DE": "Ausgewählt",
"en-US": "Selected",
"es-ES": "Seleccionado",
"fr-FR": "Sélectionné",
"it-IT": "Selezionato",
"ja-JP": "選択済み",
"ko-KR": "선택됨",
"nl-NL": "Geselecteerd",
"pl-PL": "Wybrane",
"pt-BR": "Selecionado",
"ru-RU": "Выбранные",
"sv-SE": "Urval",
"tr-TR": "Seçilen",
"zh-CN": "已选择",
"zh-TW": "已選取"
}
};
var Object_Listbox_SelectedExcluded = {
id: "Object.Listbox.SelectedExcluded",
locale: {
"de-DE": "Ausgeschlossen ausgewählt",
"en-US": "Selected excluded",
"es-ES": "Seleccionado excluido",
"fr-FR": "Sélectionné exclu",
"it-IT": "Selezionato escluso",
"ja-JP": "選択された除外値",
"ko-KR": "제외 항목 선택됨",
"nl-NL": "Geselecteerde uitgesloten",
"pl-PL": "Wybrane wykluczone",
"pt-BR": "Excluído selecionado",
"ru-RU": "Выбранные исключенные элементы",
"sv-SE": "Urval uteslutet",
"tr-TR": "Seçili hariç tutulan",
"zh-CN": "已排除选择",
"zh-TW": "已選取排除值"
}
};
var Object_Map = {
id: "Object.Map",
locale: {
"de-DE": "Karte",
"en-US": "Map",
"es-ES": "Mapa",
"fr-FR": "Carte",
"it-IT": "Mappa",
"ja-JP": "マップ",
"ko-KR": "맵",
"nl-NL": "Kaart",
"pl-PL": "Mapa",
"pt-BR": "Mapa",
"ru-RU": "Карта",
"sv-SE": "Karta",
"tr-TR": "Harita",
"zh-CN": "映射",
"zh-TW": "地圖"
}
};
var Object_MekkoChart = {
id: "Object.MekkoChart",
locale: {
"de-DE": "Marimekko-Diagramm",
"en-US": "Mekko chart",
"es-ES": "Gráfico Mekko",
"fr-FR": "Graphique Mekko",
"it-IT": "Grafico Mekko",
"ja-JP": "メッコ チャート",
"ko-KR": "메코 차트",
"nl-NL": "Mekko-diagram",
"pl-PL": "Wykres Mekko",
"pt-BR": "Gráfico Mekko",
"ru-RU": "Диаграмма Мекко",
"sv-SE": "Mosaikdiagram",
"tr-TR": "Mekko grafiği",
"zh-CN": "玛丽麦高图",
"zh-TW": "Mekko 圖"
}
};
var Object_NavMenu = {
id: "Object.NavMenu",
locale: {
"de-DE": "Navigationsmenü",
"en-US": "Navigation menu",
"es-ES": "Menú de navegación",
"fr-FR": "Menu de navigation",
"it-IT": "Menu di navigazione",
"ja-JP": "ナビゲーション メニュー",
"ko-KR": "탐색 메뉴",
"nl-NL": "Navigatiemenu",
"pl-PL": "Menu nawigacji",
"pt-BR": "Menu de navegação",
"ru-RU": "Меню навигации",
"sv-SE": "Navigationsmeny",
"tr-TR": "Gezinti menüsü",
"zh-CN": "导航菜单",
"zh-TW": "導覽功能表"
}
};
var Object_NlgChart = {
id: "Object.NlgChart",
locale: {
"de-DE": "NL-Einblicke",
"en-US": "NL insights",
"es-ES": "Información en LN",
"fr-FR": "Informations analytiques NL",
"it-IT": "Informazioni strategiche NL",
"ja-JP": "NL インサイト",
"ko-KR": "NL 통찰력",
"nl-NL": "NL-inzichten",
"pl-PL": "Wnioski w języku naturalnym",
"pt-BR": "Ideias de NL",
"ru-RU": "Наблюдения на естественном языке",
"sv-SE": "Insikter på naturligt språk (NL)",
"tr-TR": "NL içgörüleri",
"zh-CN": "NL 见解",
"zh-TW": "自然語言深入資訊"
}
};
var Object_PieChart = {
id: "Object.PieChart",
locale: {
"de-DE": "Kreisdiagramm",
"en-US": "Pie chart",
"es-ES": "Gráfico de tarta",
"fr-FR": "Graphique en secteurs",
"it-IT": "Grafico a torta",
"ja-JP": "円グラフ",
"ko-KR": "원형 차트",
"nl-NL": "Cirkeldiagram",
"pl-PL": "Wykres kołowy",
"pt-BR": "Gráfico de pizza",
"ru-RU": "Круговая диаграмма",
"sv-SE": "Cirkeldiagram",
"tr-TR": "Pasta grafik",
"zh-CN": "饼图",
"zh-TW": "圓形圖"
}
};
var Object_PivotTable = {
id: "Object.PivotTable",
locale: {
"de-DE": "Pivottabelle",
"en-US": "Pivot table",
"es-ES": "Tabla dinámica",
"fr-FR": "Tableau croisé dynamique",
"it-IT": "Tabella pivot",
"ja-JP": "ピボット テーブル",
"ko-KR": "피벗 테이블",
"nl-NL": "Draaitabel",
"pl-PL": "Tabela przestawna",
"pt-BR": "Tabela dinâmica",
"ru-RU": "Сводная таблица",
"sv-SE": "Pivottabell",
"tr-TR": "Pivot tablo",
"zh-CN": "透视表",
"zh-TW": "樞紐分析表"
}
};
var Object_RadarChart = {
id: "Object.RadarChart",
locale: {
"de-DE": "Netzdiagramm",
"en-US": "Radar chart",
"es-ES": "Gráfico de radar",
"fr-FR": "Diagramme en étoile",
"it-IT": "Grafico a radar",
"ja-JP": "レーダー チャート",
"ko-KR": "방사형 차트",
"nl-NL": "Radardiagram",
"pl-PL": "Wykres radarowy",
"pt-BR": "Gráfico de radar",
"ru-RU": "Диаграмма Радар",
"sv-SE": "Radardiagram",
"tr-TR": "Radar grafiği",
"zh-CN": "雷达图",
"zh-TW": "雷達圖"
}
};
var Object_SankeyChart = {
id: "Object.SankeyChart",
locale: {
"de-DE": "Sankey-Diagramm",
"en-US": "Sankey chart",
"es-ES": "Diagrama de Sankey",
"fr-FR": "Diagramme de Sankey",
"it-IT": "Diagramma di Sankey",
"ja-JP": "サンキー グラフ",
"ko-KR": "Sankey 차트",
"nl-NL": "Sankey-diagram",
"pl-PL": "Wykres Sankeya",
"pt-BR": "Gráfico de Sankey",
"ru-RU": "Диаграмма Сэнки",
"sv-SE": "Sankey-diagram",
"tr-TR": "Sankey grafiği",
"zh-CN": "桑基图",
"zh-TW": "桑基圖"
}
};
var Object_ScatterPlot = {
id: "Object.ScatterPlot",
locale: {
"de-DE": "Punktdiagramm",
"en-US": "Scatter plot",
"es-ES": "Gráfico de dispersión",
"fr-FR": "Nuage de points",
"it-IT": "Grafico a dispersione",
"ja-JP": "散布図",
"ko-KR": "스캐터 차트",
"nl-NL": "Spreidingsplot",
"pl-PL": "Wykres punktowy",
"pt-BR": "Plotagem de dispersão",
"ru-RU": "Точечная диаграмма",
"sv-SE": "Spridningsdiagram",
"tr-TR": "Dağılım çizimi",
"zh-CN": "散点图",
"zh-TW": "散佈圖"
}
};
var Object_StraightTable = {
id: "Object.StraightTable",
locale: {
"de-DE": "Tabellendiagramm",
"en-US": "Straight table",
"es-ES": "Tabla simple",
"fr-FR": "Tableau simple",
"it-IT": "Tabella lineare",
"ja-JP": "ストレート テーブル",
"ko-KR": "일반표",
"nl-NL": "Strakke tabel",
"pl-PL": "Tabela prosta",
"pt-BR": "Tabela estática",
"ru-RU": "Прямая таблица",
"sv-SE": "Enkel tabell",
"tr-TR": "Düz tablo",
"zh-CN": "垂直表",
"zh-TW": "直表"
}
};
var Object_TabContainer = {
id: "Object.TabContainer",
locale: {
"de-DE": "Registerkarten-Container",
"en-US": "Tab container",
"es-ES": "Contenedor de pestañas",
"fr-FR": "Conteneur d'onglets",
"it-IT": "Contenitore a schede",
"ja-JP": "タブ付きコンテナ",
"ko-KR": "탭 컨테이너",
"nl-NL": "Tabbladcontainer",
"pl-PL": "Kontener karty",
"pt-BR": "Contêiner de guias",
"ru-RU": "Контейнер вкладок",
"sv-SE": "Flikbehållare",
"tr-TR": "Sekme kapsayıcısı",
"zh-CN": "选项卡容器",
"zh-TW": "索引標籤容器"
}
};
var Object_Table = {
id: "Object.Table",
locale: {
"de-DE": "Tabelle",
"en-US": "Table",
"es-ES": "Tabla",
"fr-FR": "Table",
"it-IT": "Tabella",
"ja-JP": "テーブル",
"ko-KR": "테이블",
"nl-NL": "Tabel",
"pl-PL": "Tabela",
"pt-BR": "Tabela",
"ru-RU": "Таблица",
"sv-SE": "Tabell",
"tr-TR": "Tablo",
"zh-CN": "表格",
"zh-TW": "表格"
}
};
var Object_Table_Deprecated = {
id: "Object.Table.Deprecated",
locale: {
"de-DE": "Tabelle",
"en-US": "Table ",
"es-ES": "Tabla",
"fr-FR": "Table",
"it-IT": "Tabella",
"ja-JP": "テーブル",
"ko-KR": "테이블",
"nl-NL": "Tabel",
"pl-PL": "Tabela",
"pt-BR": "Tabela",
"ru-RU": "Таблица",
"sv-SE": "Tabell",
"tr-TR": "Tablo",
"zh-CN": "表格",
"zh-TW": "表格"
}
};
var Object_Text = {
id: "Object.Text",
locale: {
"de-DE": "Text",
"en-US": "Text",
"es-ES": "Texto",
"fr-FR": "Texte",
"it-IT": "Testo",
"ja-JP": "テキスト",
"ko-KR": "텍스트",
"nl-NL": "Tekst",
"pl-PL": "Tekst",
"pt-BR": "Texto",
"ru-RU": "Текст",
"sv-SE": "Text",
"tr-TR": "Metin",
"zh-CN": "文本",
"zh-TW": "文字"
}
};
var Object_TextImage = {
id: "Object.TextImage",
locale: {
"de-DE": "Text und Bild",
"en-US": "Text & image",
"es-ES": "Texto e imagen",
"fr-FR": "Texte et image",
"it-IT": "Testo e immagine",
"ja-JP": "テキストと画像",
"ko-KR": "텍스트 및 이미지",
"nl-NL": "Tekst en afbeelding",
"pl-PL": "Tekst i grafika",
"pt-BR": "Texto e imagem",
"ru-RU": "Текст и изображение",
"sv-SE": "Text och bild",
"tr-TR": "Metin ve resim",
"zh-CN": "文本和图片",
"zh-TW": "文字與影像"
}
};
var Object_Treemap = {
id: "Object.Treemap",
locale: {
"de-DE": "Baumkarte",
"en-US": "Treemap",
"es-ES": "Gráfico de bloques",
"fr-FR": "Treemap",
"it-IT": "Mappa ad albero",
"ja-JP": "ツリーマップ",
"ko-KR": "트리맵",
"nl-NL": "Structuuroverzicht",
"pl-PL": "Mapa drzewa",
"pt-BR": "Mapa de árvore",
"ru-RU": "Карта дерева",
"sv-SE": "Trädkarta",
"tr-TR": "Ağaç haritası",
"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 Object_WaterfallChart = {
id: "Object.WaterfallChart",
locale: {
"de-DE": "Wasserfalldiagramm",
"en-US": "Waterfall chart",
"es-ES": "Gráfico de cascada",
"fr-FR": "Graphique en cascade",
"it-IT": "Grafico a cascata",
"ja-JP": "ウォーターフォール グラフ",
"ko-KR": "폭포형 차트",
"nl-NL": "Watervalgrafiek",
"pl-PL": "Wykres wodospadowy",
"pt-BR": "Gráfico em cascata",
"ru-RU": "Каскадная диаграмма",
"sv-SE": "Vattenfallsdiagram",
"tr-TR": "Şelale grafik",
"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 ScreenReader_ManySearchResults = {
id: "ScreenReader.ManySearchResults",
locale: {
"de-DE": "Es sind {0} Ergebnisse verfügbar",
"en-US": "There are {0} available results",
"es-ES": "Hay {0} resultados disponibles",
"fr-FR": "Il existe {0} résultats disponibles.",
"it-IT": "{0} risultati disponibili",
"ja-JP": "利用可能な結果が {0} つあります",
"ko-KR": "{0}개의 결과를 사용할 수 있음",
"nl-NL": "Er zijn {0} beschikbare resultaten",
"pl-PL": "Liczba dostępnych wyników: {0}",
"pt-BR": "Há {0} resultados disponíveis",
"ru-RU": "Имеются доступные результаты: {0}",
"sv-SE": "Det finns {0} tillgängliga resultat",
"tr-TR": "Kullanılabilir {0} sonuç mevcut",
"zh-CN": "有 {0} 个可用结果",
"zh-TW": "有 {0} 個可用的結果"
}
};
var ScreenReader_ManySelected = {
id: "ScreenReader.ManySelected",
locale: {
"de-DE": "Es sind {0} Werte ausgewählt.",
"en-US": "There are {0} selected values.",
"es-ES": "Hay {0} valores seleccionados.",
"fr-FR": "{0} valeurs sont sélectionnées.",
"it-IT": "Sono presenti {0} valori selezionati.",
"ja-JP": "値が {0} 個選択されています。",
"ko-KR": "{0}개의 값이 선택되었습니다.",
"nl-NL": "Er zijn {0} geselecteerde waarden.",
"pl-PL": "Wybranych wartości: {0}",
"pt-BR": "Há {0} valores selecionados.",
"ru-RU": "Выбраны {0} значений(я).",
"sv-SE": "{0} värden är valda.",
"tr-TR": "Seçilen {0} değer var.",
"zh-CN": "存在 {0} 个已选择的值。",
"zh-TW": "有 {0} 個選取的值。"
}
};
var ScreenReader_OneSearchResult = {
id: "ScreenReader.OneSearchResult",
locale: {
"de-DE": "Es ist ein Ergebnis verfügbar",
"en-US": "There is one available result",
"es-ES": "Hay un resultado disponible",
"fr-FR": "Il existe un résultat disponible.",
"it-IT": "Un risultato disponibile",
"ja-JP": "利用可能な結果が 1 つあります",
"ko-KR": "하나의 결과를 사용할 수 있음",
"nl-NL": "Er is één beschikbaar resultaat",
"pl-PL": "Jest jeden dostępny wynik",
"pt-BR": "Há um resultado disponível",
"ru-RU": "Имеется один доступный результат",
"sv-SE": "Det finns ett tillgängligt resultat",
"tr-TR": "Kullanılabilir bir sonuç mevcut",
"zh-CN": "有一个可用结果",
"zh-TW": "有一個可用的結果"
}
};
var ScreenReader_OneSelected = {
id: "ScreenReader.OneSelected",
locale: {
"de-DE": "Es ist ein Wert ausgewählt.",
"en-US": "There is one selected value.",
"es-ES": "Hay un valor seleccionado.",
"fr-FR": "Une valeur est sélectionnée.",
"it-IT": "È presente un valore selezionato.",
"ja-JP": "値が 1 つ選択されています。",
"ko-KR": "하나의 값이 선택되었습니다.",
"nl-NL": "Er is één waarde geselecteerd.",
"pl-PL": "Istnieje jedna wybrana wartość.",
"pt-BR": "Há um valor selecionado.",
"ru-RU": "Выбрано одно значение.",
"sv-SE": "Ett värde är valt.",
"tr-TR": "Seçilen bir değer var.",
"zh-CN": "存在一个已选择的值。",
"zh-TW": "有一個選取的值。"
}
};
var ScreenReader_ZeroSelected = {
id: "ScreenReader.ZeroSelected",
locale: {
"de-DE": "Es sind keine Werte ausgewählt.",
"en-US": "No values are selected.",
"es-ES": "No se ha seleccionado ningún valor.",
"fr-FR": "Aucune valeur n'est sélectionnée.",
"it-IT": "Nessun valore selezionato.",
"ja-JP": "値が選択されていません。",
"ko-KR": "선택된 값이 없습니다.",
"nl-NL": "Geen waarden geselecteerd.",
"pl-PL": "Brak wybranych wartości.",
"pt-BR": "Nenhum valor selecionado.",
"ru-RU": "Значения не выбраны.",
"sv-SE": "Inga värden är valda.",
"tr-TR": "Seçilen değer yok.",
"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 SelectionToolbar_ClickToLock = {
id: "SelectionToolbar.ClickToLock",
locale: {
"de-DE": "Klicken zum Sperren",
"en-US": "Click to lock",
"es-ES": "Haga clic para bloquearla",
"fr-FR": "Cliquez pour verrouiller",
"it-IT": "Fare clic per bloccare",
"ja-JP": "クリックしてロック",
"ko-KR": "클릭하여 잠금",
"nl-NL": "Klik om te vergrendelen",
"pl-PL": "Kliknij, aby zablokować",
"pt-BR": "Clique para bloquear",
"ru-RU": "Щелкните, чтобы заблокировать",
"sv-SE": "Klicka för att låsa",
"tr-TR": "Kilitlemek için tıklayın",
"zh-CN": "单击以锁定",
"zh-TW": "按一下以鎖定"
}
};
var SelectionToolbar_ClickToUnlock = {
id: "SelectionToolbar.ClickToUnlock",
locale: {
"de-DE": "Zum Entsperren klicken",
"en-US": "Click to unlock",
"es-ES": "Haga clic para desbloquearla",
"fr-FR": "Cliquez pour déverrouiller",
"it-IT": "Fare clic per sbloccare",
"ja-JP": "クリックしてロック解除",
"ko-KR": "잠금을 해제하려면 클릭하십시오.",
"nl-NL": "Klik om te ontgrendelen",
"pl-PL": "Aby odblokować, kliknij",
"pt-BR": "Clique para destravar",
"ru-RU": "Щелкните, чтобы разблокировать",
"sv-SE": "Klicka för att låsa upp",
"tr-TR": "Kilidi kaldırmak için tıklayın",
"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 = {
Accessibility_Object_NoTitle: Accessibility_Object_NoTitle,
Cancel: Cancel$1,
CurrentSelections_All: CurrentSelections_All,
CurrentSelections_Of: CurrentSelections_Of,
Listbox_Clear_Search: Listbox_Clear_Search,
Listbox_Cyclic: Listbox_Cyclic,
Listbox_Dismiss: Listbox_Dismiss,
Listbox_DrillDown: Listbox_DrillDown,
Listbox_ItemsOverflow: Listbox_ItemsOverflow,
Listbox_Lock: Listbox_Lock,
Listbox_NoMatchesForYourTerms: Listbox_NoMatchesForYourTerms,
Listbox_ResultFilterLabel: Listbox_ResultFilterLabel,
Listbox_ScreenReader_SearchThenSelectionsMenu_WithAccSelMenu: Listbox_ScreenReader_SearchThenSelectionsMenu_WithAccSelMenu,
Listbox_ScreenReader_SelectionMenu_WithAccSelMenu: Listbox_ScreenReader_SelectionMenu_WithAccSelMenu,
Listbox_ScreenReaderInstructions: Listbox_ScreenReaderInstructions,
Listbox_Search: Listbox_Search,
Listbox_Search_ScreenReaderInstructions: Listbox_Search_ScreenReaderInstructions,
Listbox_Unlock: Listbox_Unlock,
Menu_More: Menu_More,
Navigate_Back: Navigate_Back,
Navigate_Forward: Navigate_Forward,
OK: OK,
Object_ActionButton: Object_ActionButton,
Object_AutoChart: Object_AutoChart,
Object_BarChart: Object_BarChart,
Object_BoxPlot: Object_BoxPlot,
Object_BulletChart: Object_BulletChart,
Object_ComboChart: Object_ComboChart,
Object_Container: Object_Container,
Object_DistributionPlot: Object_DistributionPlot,
Object_FilterLabel_All: Object_FilterLabel_All,
Object_FilterLabel_Exclude: Object_FilterLabel_Exclude,
Object_FilterLabel_Unknown: Object_FilterLabel_Unknown,
Object_FilterPane: Object_FilterPane,
Object_FiltersApplied: Object_FiltersApplied,
Object_FunnelChart: Object_FunnelChart,
Object_Gauge: Object_Gauge,
Object_GridChart: Object_GridChart,
Object_Histogram: Object_Histogram,
Object_Kpi: Object_Kpi,
Object_LayoutContainer: Object_LayoutContainer,
Object_LineChart: Object_LineChart,
Object_Listbox: Object_Listbox,
Object_Listbox_Alternative: Object_Listbox_Alternative,
Object_Listbox_Excluded: Object_Listbox_Excluded,
Object_Listbox_ExcludedLock: Object_Listbox_ExcludedLock,
Object_Listbox_Locked: Object_Listbox_Locked,
Object_Listbox_Optional: Object_Listbox_Optional,
Object_Listbox_Selected: Object_Listbox_Selected,
Object_Listbox_SelectedExcluded: Object_Listbox_SelectedExcluded,
Object_Map: Object_Map,
Object_MekkoChart: Object_MekkoChart,
Object_NavMenu: Object_NavMenu,
Object_NlgChart: Object_NlgChart,
Object_PieChart: Object_PieChart,
Object_PivotTable: Object_PivotTable,
Object_RadarChart: Object_RadarChart,
Object_SankeyChart: Object_SankeyChart,
Object_ScatterPlot: Object_ScatterPlot,
Object_StraightTable: Object_StraightTable,
Object_TabContainer: Object_TabContainer,
Object_Table: Object_Table,
Object_Table_Deprecated: Object_Table_Deprecated,
Object_Text: Object_Text,
Object_TextImage: Object_TextImage,
Object_Treemap: Object_Treemap,
Object_Update_Active: Object_Update_Active,
Object_Update_Cancelled: Object_Update_Cancelled,
Object_WaterfallChart: Object_WaterfallChart,
Retry: Retry$1,
ScreenReader_ManySearchResults: ScreenReader_ManySearchResults,
ScreenReader_ManySelected: ScreenReader_ManySelected,
ScreenReader_OneSearchResult: ScreenReader_OneSearchResult,
ScreenReader_OneSelected: ScreenReader_OneSelected,
ScreenReader_ZeroSelected: ScreenReader_ZeroSelected,
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,
SelectionToolbar_ClickToLock: SelectionToolbar_ClickToLock,
SelectionToolbar_ClickToUnlock: SelectionToolbar_ClickToUnlock,
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 nodeEventEmitter;
var hasRequiredNodeEventEmitter;
function requireNodeEventEmitter () {
if (hasRequiredNodeEventEmitter) return nodeEventEmitter;
hasRequiredNodeEventEmitter = 1;
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);
}
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;
};
return nodeEventEmitter;
}
var nodeEventEmitterExports = requireNodeEventEmitter();
var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(nodeEventEmitterExports);
function define(constructor, factory, prototype) {
constructor.prototype = factory.prototype = prototype;
prototype.constructor = constructor;
}
function extend$2(parent, definition) {
var prototype = Object.create(parent.prototype);
for (var key in definition) prototype[key] = definition[key];
return prototype;
}
function Color$1() {}
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$1, color$3, {
copy(channels) {
return Object.assign(new this.constructor, this, channels);
},
displayable() {
return this.rgb().displayable();
},
hex: color_formatHex, // Deprecated! Use color.formatHex.
formatHex: color_formatHex,
formatHex8: color_formatHex8,
formatHsl: color_formatHsl,
formatRgb: color_formatRgb,
toString: color_formatRgb
});
function color_formatHex() {
return this.rgb().formatHex();
}
function color_formatHex8() {
return this.rgb().formatHex8();
}
function color_formatHsl() {
return hslConvert(this).formatHsl();
}
function color_formatRgb() {
return this.rgb().formatRgb();
}
function color$3(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$1(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000
: l === 4 ? rgba$1((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$1(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
: (m = reRgbaPercent.exec(format)) ? rgba$1(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
: (m = reHslPercent.exec(format)) ? hsla$1(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
: (m = reHslaPercent.exec(format)) ? hsla$1(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$1(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$1)) o = color$3(o);
if (!o) return new Rgb;
o = o.rgb();
return new Rgb(o.r, o.g, o.b, o.opacity);
}
function rgb$1(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$1, extend$2(Color$1, {
brighter(k) {
k = k == null ? brighter : Math.pow(brighter, k);
return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
},
darker(k) {
k = k == null ? darker : Math.pow(darker, k);
return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
},
rgb() {
return this;
},
clamp() {
return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));
},
displayable() {
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,
formatHex8: rgb_formatHex8,
formatRgb: rgb_formatRgb,
toString: rgb_formatRgb
}));
function rgb_formatHex() {
return `#${hex$1(this.r)}${hex$1(this.g)}${hex$1(this.b)}`;
}
function rgb_formatHex8() {
return `#${hex$1(this.r)}${hex$1(this.g)}${hex$1(this.b)}${hex$1((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;
}
function rgb_formatRgb() {
const a = clampa(this.opacity);
return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`;
}
function clampa(opacity) {
return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));
}
function clampi(value) {
return Math.max(0, Math.min(255, Math.round(value) || 0));
}
function hex$1(value) {
value = clampi(value);
return (value < 16 ? "0" : "") + value.toString(16);
}
function hsla$1(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$1)) o = color$3(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$1(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$1, extend$2(Color$1, {
brighter(k) {
k = k == null ? brighter : Math.pow(brighter, k);
return new Hsl(this.h, this.s, this.l * k, this.opacity);
},
darker(k) {
k = k == null ? darker : Math.pow(darker, k);
return new Hsl(this.h, this.s, this.l * k, this.opacity);
},
rgb() {
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
);
},
clamp() {
return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));
},
displayable() {
return (0 <= this.s && this.s <= 1 || isNaN(this.s))
&& (0 <= this.l && this.l <= 1)
&& (0 <= this.opacity && this.opacity <= 1);
},
formatHsl() {
const a = clampa(this.opacity);
return `${a === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`;
}
}));
function clamph(value) {
value = (value || 0) % 360;
return value < 0 ? value + 360 : value;
}
function clampt(value) {
return Math.max(0, Math.min(1, value || 0));
}
/* 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;
}
var extend$1;
var hasRequiredExtend;
function requireExtend () {
if (hasRequiredExtend) return extend$1;
hasRequiredExtend = 1;
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];
};
extend$1 = 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;
};
return extend$1;
}
var extendExports = requireExtend();
var originalExtend = /*@__PURE__*/getDefaultExportFromCjs(extendExports);
var fontSize = "12px";
var fontFamily = "'Source Sans Pro', 'Arial', 'sans-serif'";
var backgroundColor$1 = "transparent";
var dataColors = {
primaryColor: "#26a0a7",
othersColor: "#a5a5a5",
errorColor: "#ff4444",
nullColor: "#d2d2d2"
};
var object$2 = {
title: {
main: {
color: "@B50",
fontSize: "15px",
backgroundColor: "transparent"
},
subTitle: {
color: "@B50",
fontSize: "12px",
backgroundColor: "transparent"
},
footer: {
color: "@B50",
fontSize: "12px",
backgroundColor: "transparent"
}
}
};
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,
fontFamily: fontFamily,
backgroundColor: backgroundColor$1,
dataColors: dataColors,
object: object$2,
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$2 = "@B35";
var lightRawJSON = {
_variables: _variables$1,
type: type$1,
color: color$2
};
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$1 = "@B98";
var object$1 = {
listBox: {
backgroundColor: "@B20",
title: {
main: {
color: "@B98",
fontSize: "14px",
fontWeight: "bold"
}
},
content: {
color: "#@B98",
fontSize: "12px"
}
}
};
var darkRawJSON = {
_variables: _variables,
type: type,
color: color$1,
object: object$1
};
var object = {
listBox: {
backgroundColor: "#ffffff",
title: {
main: {
color: "#404040",
fontSize: "14px",
fontWeight: "bold"
}
},
content: {
color: "#404040",
fontSize: "12px"
}
}
};
var baseInheritRawJSON = {
object: object
};
/* eslint no-underscore-dangle:0 */
function setTheme(t, resolve) {
const colorRawJSON = t.type === 'dark' ? darkRawJSON : lightRawJSON;
let baseInherit = baseInheritRawJSON;
if (t._inherit === false || t._inherit === 'false') {
baseInherit = {};
}
const root = originalExtend(true, {}, baseRawJSON, baseInherit, colorRawJSON);
// avoid merging known array objects as it could cause issues if they are of different types (pyramid vs class) or length
const rawThemeJSON = originalExtend(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;
}
const colorStruct = {
aliceblue: {
r: 240,
g: 248,
b: 255
},
antiquewhite: {
r: 250,
g: 235,
b: 215
},
aqua: {
r: 0,
g: 255,
b: 255
},
aquamarine: {
r: 127,
g: 255,
b: 212
},
azure: {
r: 240,
g: 255,
b: 255
},
beige: {
r: 245,
g: 245,
b: 220
},
bisque: {
r: 255,
g: 228,
b: 196
},
black: {
r: 0,
g: 0,
b: 0
},
blanchedalmond: {
r: 255,
g: 235,
b: 205
},
blue: {
r: 0,
g: 0,
b: 255
},
blueviolet: {
r: 138,
g: 43,
b: 226
},
brown: {
r: 165,
g: 42,
b: 42
},
burlywood: {
r: 222,
g: 184,
b: 135
},
cadetblue: {
r: 95,
g: 158,
b: 160
},
chartreuse: {
r: 127,
g: 255,
b: 0
},
chocolate: {
r: 210,
g: 105,
b: 30
},
coral: {
r: 255,
g: 127,
b: 80
},
cornflowerblue: {
r: 100,
g: 149,
b: 237
},
cornsilk: {
r: 255,
g: 248,
b: 220
},
crimson: {
r: 220,
g: 20,
b: 60
},
cyan: {
r: 0,
g: 255,
b: 255
},
darkblue: {
r: 0,
g: 0,
b: 139
},
darkcyan: {
r: 0,
g: 139,
b: 139
},
darkgoldenrod: {
r: 184,
g: 134,
b: 11
},
darkgray: {
r: 169,
g: 169,
b: 169
},
darkgreen: {
r: 0,
g: 100,
b: 0
},
darkgrey: {
r: 169,
g: 169,
b: 169
},
darkkhaki: {
r: 189,
g: 183,
b: 107
},
darkmagenta: {
r: 139,
g: 0,
b: 139
},
darkolivegreen: {
r: 85,
g: 107,
b: 47
},
darkorange: {
r: 255,
g: 140,
b: 0
},
darkorchid: {
r: 153,
g: 50,
b: 204
},
darkred: {
r: 139,
g: 0,
b: 0
},
darksalmon: {
r: 233,
g: 150,
b: 122
},
darkseagreen: {
r: 143,
g: 188,
b: 143
},
darkslateblue: {
r: 72,
g: 61,
b: 139
},
darkslategray: {
r: 47,
g: 79,
b: 79
},
darkslategrey: {
r: 47,
g: 79,
b: 79
},
darkturquoise: {
r: 0,
g: 206,
b: 209
},
darkviolet: {
r: 148,
g: 0,
b: 211
},
deeppink: {
r: 255,
g: 20,
b: 147
},
deepskyblue: {
r: 0,
g: 191,
b: 255
},
dimgray: {
r: 105,
g: 105,
b: 105
},
dimgrey: {
r: 105,
g: 105,
b: 105
},
dodgerblue: {
r: 30,
g: 144,
b: 255
},
firebrick: {
r: 178,
g: 34,
b: 34
},
floralwhite: {
r: 255,
g: 250,
b: 240
},
forestgreen: {
r: 34,
g: 139,
b: 34
},
fuchsia: {
r: 255,
g: 0,
b: 255
},
gainsboro: {
r: 220,
g: 220,
b: 220
},
ghostwhite: {
r: 248,
g: 248,
b: 255
},
gold: {
r: 255,
g: 215,
b: 0
},
goldenrod: {
r: 218,
g: 165,
b: 32
},
gray: {
r: 128,
g: 128,
b: 128
},
green: {
r: 0,
g: 128,
b: 0
},
greenyellow: {
r: 173,
g: 255,
b: 47
},
grey: {
r: 128,
g: 128,
b: 128
},
honeydew: {
r: 240,
g: 255,
b: 240
},
hotpink: {
r: 255,
g: 105,
b: 180
},
indianred: {
r: 205,
g: 92,
b: 92
},
indigo: {
r: 75,
g: 0,
b: 130
},
ivory: {
r: 255,
g: 255,
b: 240
},
khaki: {
r: 240,
g: 230,
b: 140
},
lavender: {
r: 230,
g: 230,
b: 250
},
lavenderblush: {
r: 255,
g: 240,
b: 245
},
lawngreen: {
r: 124,
g: 252,
b: 0
},
lemonchiffon: {
r: 255,
g: 250,
b: 205
},
lightblue: {
r: 173,
g: 216,
b: 230
},
lightcoral: {
r: 240,
g: 128,
b: 128
},
lightcyan: {
r: 224,
g: 255,
b: 255
},
lightgoldenrodyellow: {
r: 250,
g: 250,
b: 210
},
lightgray: {
r: 211,
g: 211,
b: 211
},
lightgreen: {
r: 144,
g: 238,
b: 144
},
lightgrey: {
r: 211,
g: 211,
b: 211
},
lightpink: {
r: 255,
g: 182,
b: 193
},
lightsalmon: {
r: 255,
g: 160,
b: 122
},
lightseagreen: {
r: 32,
g: 178,
b: 170
},
lightskyblue: {
r: 135,
g: 206,
b: 250
},
lightslategray: {
r: 119,
g: 136,
b: 153
},
lightslategrey: {
r: 119,
g: 136,
b: 153
},
lightsteelblue: {
r: 176,
g: 196,
b: 222
},
lightyellow: {
r: 255,
g: 255,
b: 224
},
lime: {
r: 0,
g: 255,
b: 0
},
limegreen: {
r: 50,
g: 205,
b: 50
},
linen: {
r: 250,
g: 240,
b: 230
},
magenta: {
r: 255,
g: 0,
b: 255
},
maroon: {
r: 128,
g: 0,
b: 0
},
mediumaquamarine: {
r: 102,
g: 205,
b: 170
},
mediumblue: {
r: 0,
g: 0,
b: 205
},
mediumorchid: {
r: 186,
g: 85,
b: 211
},
mediumpurple: {
r: 147,
g: 112,
b: 219
},
mediumseagreen: {
r: 60,
g: 179,
b: 113
},
mediumslateblue: {
r: 123,
g: 104,
b: 238
},
mediumspringgreen: {
r: 0,
g: 250,
b: 154
},
mediumturquoise: {
r: 72,
g: 209,
b: 204
},
mediumvioletred: {
r: 199,
g: 21,
b: 133
},
midnightblue: {
r: 25,
g: 25,
b: 112
},
mintcream: {
r: 245,
g: 255,
b: 250
},
mistyrose: {
r: 255,
g: 228,
b: 225
},
moccasin: {
r: 255,
g: 228,
b: 181
},
navajowhite: {
r: 255,
g: 222,
b: 173
},
navy: {
r: 0,
g: 0,
b: 128
},
oldlace: {
r: 253,
g: 245,
b: 230
},
olive: {
r: 128,
g: 128,
b: 0
},
olivedrab: {
r: 107,
g: 142,
b: 35
},
orange: {
r: 255,
g: 165,
b: 0
},
orangered: {
r: 255,
g: 69,
b: 0
},
orchid: {
r: 218,
g: 112,
b: 214
},
palegoldenrod: {
r: 238,
g: 232,
b: 170
},
palegreen: {
r: 152,
g: 251,
b: 152
},
paleturquoise: {
r: 175,
g: 238,
b: 238
},
palevioletred: {
r: 219,
g: 112,
b: 147
},
papayawhip: {
r: 255,
g: 239,
b: 213
},
peachpuff: {
r: 255,
g: 218,
b: 185
},
peru: {
r: 205,
g: 133,
b: 63
},
pink: {
r: 255,
g: 192,
b: 203
},
plum: {
r: 221,
g: 160,
b: 221
},
powderblue: {
r: 176,
g: 224,
b: 230
},
purple: {
r: 128,
g: 0,
b: 128
},
red: {
r: 255,
g: 0,
b: 0
},
rosybrown: {
r: 188,
g: 143,
b: 143
},
royalblue: {
r: 65,
g: 105,
b: 225
},
saddlebrown: {
r: 139,
g: 69,
b: 19
},
salmon: {
r: 250,
g: 128,
b: 114
},
sandybrown: {
r: 244,
g: 164,
b: 96
},
seagreen: {
r: 46,
g: 139,
b: 87
},
seashell: {
r: 255,
g: 245,
b: 238
},
sienna: {
r: 160,
g: 82,
b: 45
},
silver: {
r: 192,
g: 192,
b: 192
},
skyblue: {
r: 135,
g: 206,
b: 235
},
slateblue: {
r: 106,
g: 90,
b: 205
},
slategray: {
r: 112,
g: 128,
b: 144
},
slategrey: {
r: 112,
g: 128,
b: 144
},
snow: {
r: 255,
g: 250,
b: 250
},
springgreen: {
r: 0,
g: 255,
b: 127
},
steelblue: {
r: 70,
g: 130,
b: 180
},
tan: {
r: 210,
g: 180,
b: 140
},
teal: {
r: 0,
g: 128,
b: 128
},
thistle: {
r: 216,
g: 191,
b: 216
},
tomato: {
r: 255,
g: 99,
b: 71
},
transparent: {
r: 255,
g: 255,
b: 255,
a: 0
},
turquoise: {
r: 64,
g: 224,
b: 208
},
violet: {
r: 238,
g: 130,
b: 238
},
wheat: {
r: 245,
g: 222,
b: 179
},
white: {
r: 255,
g: 255,
b: 255
},
whitesmoke: {
r: 245,
g: 245,
b: 245
},
yellow: {
r: 255,
g: 255,
b: 0
},
yellowgreen: {
r: 154,
g: 205,
b: 50
}
};
/* eslint-disable no-param-reassign */
/* eslint-disable camelcase */
/* eslint-disable no-nested-ternary */
/* eslint-disable no-cond-assign */
/* eslint-disable prefer-destructuring */
/* eslint-disable no-underscore-dangle */
/**
* Module which defines a color object
* @private
* @exports objects.views/charts/representation/color
* @expose module:objects.views/charts/representation/color~Color
*/
// color formats
const rgb = /^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/i;
const rgba = /^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),(\d(\.\d+)?)\)$/i;
const hex = /^#([A-f0-9]{2})([A-f0-9]{2})([A-f0-9]{2})$/i;
const hexShort = /^#([A-f0-9])([A-f0-9])([A-f0-9])$/i;
const hsl = /^hsl\(\s*(\d+(\.\d+)?)\s*,\s*(\d+(\.\d+)?%?)\s*,\s*(\d+(\.\d+)?%?)\s*\)$/i;
const hsla = /^hsla\(\s*(\d+(\.\d+)?)\s*,\s*(\d+(\.\d+)?%?)\s*,\s*(\d+(\.\d+)?%?)\s*,(\d(\.\d+)?)\)$/i;
const {
floor
} = Math;
const {
round: round$3
} = Math;
/**
* @class
* @classdesc Class which provides color transformation functionality
* @description This is a constructor.
* @private
* @param {object} - Parameters to create a color from different notations
* @example
* // a few ways of instantiating a red color
* var red;
* red = new Color(255, 0, 0, 1); // rgba as parameters
* red = new Color('#ff0000'); // hex
* red = new Color('rgb(255,0,0)');//rgb as string
* red = new Color('hsl(0, 100, 50)');// hsl as string
* red = new Color(16711680);// uint
*/
class Color {
constructor() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
let r = 0;
let g = 0;
let b = 0;
let a = 1;
let h;
let s;
let lcs;
let l;
let v;
let c;
let h_;
let x;
let rgb_;
let m;
let matches;
let colorString;
this._invalid = false;
if (args[0] instanceof Color) {
r = args[0]._r;
g = args[0]._g;
b = args[0]._b;
a = args[0]._a;
this._invalid = args[0]._invalid;
} else if (args.length < 3) {
if (typeof args[0] === 'string') {
colorString = args[0];
if (matches = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i.exec(colorString)) {
r = parseInt(matches[1], 10);
g = parseInt(matches[2], 10);
b = parseInt(matches[3], 10);
} else if (matches = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d(\.\d+)?)\s*\)$/i.exec(colorString)) {
// rgba(1, 2, 3, 0.4)
r = parseInt(matches[1], 10);
g = parseInt(matches[2], 10);
b = parseInt(matches[3], 10);
a = parseFloat(matches[4]);
} else if (matches = /^ARGB\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i.exec(colorString)) {
// ARGB(255,255,255,255)
a = parseInt(matches[1], 10) / 255;
r = parseInt(matches[2], 10);
g = parseInt(matches[3], 10);
b = parseInt(matches[4], 10);
} else if (matches = /^#([A-f0-9]{2})([A-f0-9]{2})([A-f0-9]{2})$/i.exec(colorString)) {
// #aBc123
r = parseInt(matches[1], 16);
g = parseInt(matches[2], 16);
b = parseInt(matches[3], 16);
a = 1;
} else if (matches = /^#([A-f0-9])([A-f0-9])([A-f0-9])$/i.exec(colorString)) {
// #a5F
r = parseInt(matches[1] + matches[1], 16);
g = parseInt(matches[2] + matches[2], 16);
b = parseInt(matches[3] + matches[3], 16);
a = 1;
} else if (matches = /^hsl\(\s*(\d+(\.\d+)?)\s*,\s*(\d+(\.\d+)?%?)\s*,\s*(\d+(\.\d+)?%?)\s*\)$/i.exec(colorString)) {
// hsl(1, 2, 3)
h = parseFloat(matches[1]);
s = parseFloat(matches[3]);
l = parseFloat(matches[5]);
h %= 360;
s /= 100;
l /= 100;
h = h < 0 ? 0 : h > 360 ? 360 : h;
s = s < 0 ? 0 : s > 1 ? 1 : s;
l = l < 0 ? 0 : l > 1 ? 1 : l;
c = l <= 0.5 ? 2 * l * s : (2 - 2 * l) * s;
h_ = h / 60;
x = c * (1 - Math.abs(h_ % 2 - 1));
rgb_ = [];
h_ = Math.floor(h_);
switch (h_) {
case 0:
rgb_ = [c, x, 0];
break;
case 1:
rgb_ = [x, c, 0];
break;
case 2:
rgb_ = [0, c, x];
break;
case 3:
rgb_ = [0, x, c];
break;
case 4:
rgb_ = [x, 0, c];
break;
case 5:
rgb_ = [c, 0, x];
break;
default:
rgb_ = [0, 0, 0];
}
m = l - 0.5 * c;
r = rgb_[0] + m;
g = rgb_[1] + m;
b = rgb_[2] + m;
r = round$3(255 * r);
g = round$3(255 * g);
b = round$3(255 * b);
a = 1.0;
} else if (matches = /^hsla\(\s*(\d+(\.\d+)?)\s*,\s*(\d+(\.\d+)?%?)\s*,\s*(\d+(\.\d+)?%?)\s*,(\d(\.\d+)?)\)$/i.exec(colorString)) {
// hsla(1,2,3,0.4)
h = parseFloat(matches[1]);
s = parseFloat(matches[3]);
l = parseFloat(matches[5]);
a = parseFloat(matches[7]);
h %= 360;
s /= 100;
l /= 100;
h = h < 0 ? 0 : h > 360 ? 360 : h;
s = s < 0 ? 0 : s > 1 ? 1 : s;
l = l < 0 ? 0 : l > 1 ? 1 : l;
c = l <= 0.5 ? 2 * l * s : (2 - 2 * l) * s;
h_ = h / 60;
x = c * (1 - Math.abs(h_ % 2 - 1));
rgb_ = [];
h_ = Math.floor(h_);
switch (h_) {
case 0:
rgb_ = [c, x, 0];
break;
case 1:
rgb_ = [x, c, 0];
break;
case 2:
rgb_ = [0, c, x];
break;
case 3:
rgb_ = [0, x, c];
break;
case 4:
rgb_ = [x, 0, c];
break;
case 5:
rgb_ = [c, 0, x];
break;
default:
rgb_ = [0, 0, 0];
}
m = l - 0.5 * c;
r = rgb_[0] + m;
g = rgb_[1] + m;
b = rgb_[2] + m;
r = round$3(255 * r);
g = round$3(255 * g);
b = round$3(255 * b);
} else if (matches = /^hsv\(\s*(\d+(\.\d+)?)\s*,\s*(\d+(\.\d+)?%?)\s*,\s*(\d+(\.\d+)?%?)\s*\)$/i.exec(colorString)) {
// hsv(1, 2, 3) {
h = parseFloat(matches[1]);
s = parseFloat(matches[3]);
v = parseFloat(matches[5]);
h %= 360;
s /= 100;
v /= 100;
h = h < 0 ? 0 : h > 360 ? 360 : h;
s = s < 0 ? 0 : s > 1 ? 1 : s;
v = v < 0 ? 0 : v > 1 ? 1 : v;
c = v * s;
h_ = h / 60;
x = c * (1 - Math.abs(h_ % 2 - 1));
rgb_ = [];
h_ = Math.floor(h_);
switch (h_) {
case 0:
rgb_ = [c, x, 0];
break;
case 1:
rgb_ = [x, c, 0];
break;
case 2:
rgb_ = [0, c, x];
break;
case 3:
rgb_ = [0, x, c];
break;
case 4:
rgb_ = [x, 0, c];
break;
case 5:
rgb_ = [c, 0, x];
break;
default:
rgb_ = [0, 0, 0];
}
m = v - c;
r = rgb_[0] + m;
g = rgb_[1] + m;
b = rgb_[2] + m;
r = round$3(255 * r);
g = round$3(255 * g);
b = round$3(255 * b);
a = 1.0;
} else if (colorStruct[colorString.toLowerCase()]) {
lcs = colorString.toLowerCase();
r = colorStruct[lcs].r;
g = colorStruct[lcs].g;
b = colorStruct[lcs].b;
a = typeof colorStruct[lcs].a === 'number' ? colorStruct[lcs].a : 1.0;
} else {
this._invalid = true;
}
} else if (typeof args[0] === 'number' && args[0] >= 0 && args[1] === 'argb') {
a = (0xff000000 & args[0]) >>> 24;
a /= 255;
r = (0xff0000 & args[0]) >> 16;
g = (0x00ff00 & args[0]) >> 8;
b = 0x0000ff & args[0];
} else if (typeof args[0] === 'number' && args[0] >= 0) {
r = (0xff0000 & args[0]) >> 16;
g = (0x00ff00 & args[0]) >> 8;
b = 0x0000ff & args[0];
} else {
this._invalid = true;
}
} else if (args.length >= 3) {
r = args[0];
g = args[1];
b = args[2];
a = arguments.length >= 4 ? args[3] : 1;
} else {
this._invalid = true;
}
if (Number.isNaN(+r + g + b + a)) {
this._invalid = true;
}
this._r = floor(r);
this._g = floor(g);
this._b = floor(b);
this._a = a;
// object to cache string representations in various color spaces
this._spaces = {};
}
isInvalid() {
return this._invalid;
}
/**
* Sets alpha value of color
* @private
* @param {number} a - Alpha value of the color
*/
setAlpha(a) {
this._a = a;
this._spaces = {};
}
/**
* Gets the alpha value of this color
* @private
* @returns {number}
*/
getAlpha() {
return this._a;
}
/**
* Returns an rgb string representation of this color.
* @private
* @return {string} An rgb string representation of this color
*/
toRGB() {
if (!this._spaces.rgb) {
this._spaces.rgb = Color.toRGB(this);
}
return this._spaces.rgb;
}
/**
* Returns an rgba string representation of this color.
* @private
* @return {string} An rgba string representation of this color.
*/
toRGBA() {
if (!this._spaces.rgba) {
this._spaces.rgba = Color.toRGBA(this);
}
return this._spaces.rgba;
}
toString() {
if (!this._spaces.rgb) {
this._spaces.rgb = Color.toRGB(this);
}
return this._spaces.rgb;
}
/**
* Returns a hex string representation of this color.
* @private
* @return {string}
*/
toHex() {
if (!this._spaces.hex) {
this._spaces.hex = Color.toHex(this);
}
return this._spaces.hex;
}
/**
* Returns a hsl string representation of this color using "bi-hexcone" model for lightness
* @private
* @param {boolean} luma - Whether to use luma calculation
* @return {string} In format hsl(0,0,0)
*/
toHSL(luma) {
if (!this._spaces.hsl) {
this._spaces.hsl = Color.toHSL(this, luma);
}
return this._spaces.hsl;
}
/**
* Returns a hsla string representation of this color using "bi-hexcone" model for lightness
* @private
* @param {boolean} luma - Whether to use luma calculation
* @return {string} In format hsla(0,0,0,0)
*/
toHSLA(luma) {
if (!this._spaces.hsla) {
this._spaces.hsla = Color.toHSLA(this, luma);
}
return this._spaces.hsla;
}
/**
* Return the color components in hsv space using "hexcone" model for value (lightness)
* @private
* @param {Color|string} c
* @returns {object} The color components in hsv space {h:0-360, s:0-100, v:0-100}
*/
toHSV() {
const hsvComp = this.toHSVComponents();
return "hsv(".concat(hsvComp.h, ",").concat(hsvComp.s, ",").concat(hsvComp.v, ")");
}
/**
* Return the color components in hsv space using "hexcone" model for value (lightness)
* @private
* @param {Color|string} c
* @returns {object} The color components in hsv space {h:0-360, s:0-100, v:0-100}
*/
toHSVComponents() {
if (!this._spaces.hsvComp) {
this._spaces.hsvComp = Color.toHSVComponents(this);
}
return this._spaces.hsvComp;
}
/**
* Returns a uint representation of this color
* @private
* @return {number}
*/
toNumber() {
if (!this._spaces.num) {
this._spaces.num = Color.toNumber(this);
}
return this._spaces.num;
}
/**
* Checks if this color is perceived as dark.
* @private
* @return {string} True if the luminance is below 160, false otherwise.
*/
isDark() {
return this.isInvalid() || this.getLuminance() < 125; // luminace calc option #2
// return this.getLuminance() < 160; //luminace calc option #3
}
/**
* Calculates the perceived luminance of the color.
* @private
* @return {number} A value in the range 0-255 where a low value is considered dark and vice versa.
*/
getLuminance() {
// alpha channel is not considered
if (typeof this._lumi === 'undefined') {
// calculate luminance
// this._lumi = 0.2126 * this._r + 0.7152 * this._g + 0.0722 * this._b; // option 1
this._lumi = 0.299 * this._r + 0.587 * this._g + 0.114 * this._b; // option 2
// this._lumi = Math.sqrt( 0.241 * this._r * this._r + 0.691 * this._g * this._g + 0.068 * this._b * this._b ); // option 3
}
return this._lumi;
}
/**
* Shifts the color towards a lighter or darker shade
* @private
* @param {number} value - A value in the range -100-100 to shift the color with along the HSL lightness.
* @return {string} The shifted color as hsla string.
*/
shiftLuminance(value) {
const chsla = this.toHSLA();
const matches = /^hsla\(\s*(\d+(\.\d+)?)\s*,\s*(\d+(\.\d+)?%?)\s*,\s*(\d+(\.\d+)?%?)\s*,(\d(\.\d+)?)\)$/i.exec(chsla);
const h = parseFloat(matches[1]);
const s = parseFloat(matches[3]);
let l = parseFloat(matches[5]);
const a = parseFloat(matches[7]);
// l *= 1 + value / 100;
// l = Math.max( 0, l % 100 );
l += value;
l = Math.max(0, Math.min(l, 100));
// if( value > 0 ){
// s = s*0.2; //removing saturation to avoid the border from being too light
// }
return "hsla(".concat(h, ",").concat(s, ",").concat(l, ",").concat(a, ")");
}
/**
* Compares two colors.
* @private
* @param {Color} c The color to compare with.
* @return {boolean} True if the rgba channels are the same, false otherwise
*/
isEqual(c) {
if (c instanceof Color) {
return this._r === c._r && this._g === c._g && this._b === c._b && this._a === c._a;
}
c = new Color(c);
return this._r === c._r && this._g === c._g && this._b === c._b && this._a === c._a;
}
/**
* Linearly interpolates each channel of two colors.
* @private
* @param {Color} c2 The other color.
* @param {number} t The interpolation value in the range (0-1).
* @return {string} The blend as an rgb string.
*/
blend(c2, t) {
const r = floor(this._r + (c2._r - this._r) * t);
const g = floor(this._g + (c2._g - this._g) * t);
const b = floor(this._b + (c2._b - this._b) * t);
const a = floor(this._a + (c2._a - this._a) * t);
return "rgba(".concat([r, g, b, a].join(','), ")");
}
createShiftedColor(v) {
if (v === undefined || Number.isNaN(+v)) {
v = 1;
}
const lumi = this.getLuminance();
const greenMultiplier = this._g < 126 ? 1 : 1 + this._g / 512;
const hsla_string = this.shiftLuminance((lumi * greenMultiplier < 220 ? 0.8 + 4 * (1 / (lumi + 1)) : -(0.8 + 1 * (lumi / 255))) * 20 * v);
return new Color(hsla_string);
}
/**
* Returns an rgb string representation of this color
* @private
* @param {Color|string} c
* @returns {string} An rgb string with channel values within range 0-255.
*/
static toRGB(c) {
if (c instanceof Color) {
return "rgb(".concat([c._r, c._g, c._b].join(','), ")");
}
if (typeof c === 'string') {
c = Color.toNumber(c);
}
const r = (c & 0xff0000) >> 16;
const g = (c & 0x00ff00) >> 8;
const b = c & 0x0000ff;
return "rgb(".concat(r, ",").concat(g, ",").concat(b, ")");
}
/**
*
* @private
* @param c
* @param a
* @returns {string} The color rgb format.
*/
static toRGBA(c, a) {
if (c instanceof Color) {
return "rgba(".concat([c._r, c._g, c._b, typeof a !== 'undefined' ? a : c._a].join(','), ")");
}
if (typeof c === 'string') {
c = Color.toNumber(c);
}
const r = (c & 0xff0000) >> 16;
const g = (c & 0x00ff00) >> 8;
const b = c & 0x0000ff;
return "rgba(".concat(r, ",").concat(g, ",").concat(b, ",").concat(typeof a !== 'undefined' ? a : c._a, ")");
}
/**
*
* @private
* @param {Color|string} c
* @returns {string} The color in hexadecimal space.
*/
static toHex(c) {
let r;
let g;
let b;
if (c instanceof Color) {
r = c._r.toString(16);
g = c._g.toString(16);
b = c._b.toString(16);
if (r.length === 1) {
r = "0".concat(r);
}
if (g.length === 1) {
g = "0".concat(g);
}
if (b.length === 1) {
b = "0".concat(b);
}
return "#".concat([r, g, b].join(''));
}
if (typeof c === 'string') {
c = Color.toNumber(c);
}
r = ((c & 0xff0000) >> 16).toString(16);
g = ((c & 0x00ff00) >> 8).toString(16);
b = (c & 0x0000ff).toString(16);
if (r.length === 1) {
r = "0".concat(r);
}
if (g.length === 1) {
g = "0".concat(g);
}
if (b.length === 1) {
b = "0".concat(b);
}
return "#".concat(r).concat(g).concat(b);
}
/**
* Return the color in hsl space using "bi-hexcone" model for lightness
* @private
* @param {Color|string} c
* @param {boolean} luma - Whether to use luma calculation
* @returns {string} The color in hsl space.
*/
static toHSL(c, luma) {
let h = 0;
let s;
let l;
let ch;
if (typeof c === 'string') {
c = new Color(c);
}
// red, green, blue, hue, saturation, lightness/luma, max, min, chroma
const r = c._r / 255;
const g = c._g / 255;
const b = c._b / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
if (luma) {
// Y'709 http://en.wikipedia.org/wiki/Rec._709
// Y′709 = 0.21R + 0.72G + 0.07B
l = 0.21 * r + 0.72 * g + 0.07 * b;
} else {
l = (max + min) / 2;
}
if (max === min) {
// greyscale
s = 0;
h = 0;
} else {
ch = max - min;
s = l > 0.5 ? ch / (2 - max - min) : ch / (max + min);
switch (max) {
case r:
h = (g - b) / ch + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / ch + 2;
break;
case b:
h = (r - g) / ch + 4;
break;
}
h /= 6;
}
return "hsl(".concat(h * 360, ",").concat(s * 100, ",").concat(l * 100, ")");
}
/**
* Return the color in hsla space using "bi-hexcone" model for lightness
* @private
* @param {Color|string} c
* @param {boolean} luma - Whether to use luma calculation
* @returns {string} The color in hsla space.
*/
static toHSLA(c, luma) {
let h = 0;
let s;
let l;
let ch;
if (typeof c === 'string') {
c = new Color(c);
}
// red, green, blue, hue, saturation, lightness/luma, max, min, chroma
const r = c._r / 255;
const g = c._g / 255;
const b = c._b / 255;
const a = c._a;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
if (luma) {
// Y'709 http://en.wikipedia.org/wiki/Rec._709
// Y′709 = 0.21R + 0.72G + 0.07B
l = 0.21 * r + 0.72 * g + 0.07 * b;
} else {
l = (max + min) / 2;
}
if (max === min) {
// greyscale
s = 0;
h = 0;
} else {
ch = max - min;
s = l > 0.5 ? ch / (2 - max - min) : ch / (max + min);
switch (max) {
case r:
h = (g - b) / ch + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / ch + 2;
break;
case b:
h = (r - g) / ch + 4;
break;
}
h /= 6;
}
return "hsla(".concat(h * 360, ",").concat(s * 100, ",").concat(l * 100, ",").concat(a, ")");
}
/**
* Return the color components in hsv space using "hexcone" model for value (lightness)
* @private
* @param {Color|string} c
* @returns {object} The color components in hsv space {h:0-360, s:0-100, v:0-100}
*/
static toHSVComponents(c) {
let h = 0;
let s;
let ch;
if (typeof c === 'string') {
c = new Color(c);
}
// red, green, blue, hue, saturation, value/luma, max, min, chroma
const r = c._r / 255;
const g = c._g / 255;
const b = c._b / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const v = max;
if (max === min) {
// greyscale
s = 0;
h = 0;
} else {
ch = max - min;
s = ch === 0 ? 0 : ch / v;
switch (max) {
case r:
h = (g - b) / ch + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / ch + 2;
break;
case b:
h = (r - g) / ch + 4;
break;
}
h /= 6;
}
return {
h: h * 360 % 360,
s: s * 100,
v: v * 100
};
}
/**
* Returns an number representation of the color
* @private
* @param {Color|string} c
* @returns {Number} Unsigned integer in the range 0-16 777 216
*/
static toNumber() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
if (args.length === 1 && args[0] instanceof Color) {
return (args[0]._r << 16) + (args[0]._g << 8) + args[0]._b;
}
let r = 0;
let g = 0;
let b = 0;
let matches;
let colorString;
if (args.length === 1) {
if (typeof args[0] === 'string') {
colorString = args[0];
if (matches = /^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/i.exec(colorString)) {
r = parseInt(matches[1], 10);
g = parseInt(matches[2], 10);
b = parseInt(matches[3], 10);
} else if (matches = /^#([A-f0-9]{2})([A-f0-9]{2})([A-f0-9]{2})$/i.exec(colorString)) {
r = parseInt(matches[1], 16);
g = parseInt(matches[2], 16);
b = parseInt(matches[3], 16);
} else if (matches = /^#([A-f0-9])([A-f0-9])([A-f0-9])$/i.exec(colorString)) {
r = parseInt(matches[1] + matches[1], 16);
g = parseInt(matches[2] + matches[2], 16);
b = parseInt(matches[3] + matches[3], 16);
}
}
}
return (r << 16) + (g << 8) + b;
}
static blend(c1, c2, t) {
c1 = Color.toNumber(c1);
c2 = Color.toNumber(c2);
const r1 = (c1 & 0xff0000) >> 16;
const g1 = (c1 & 0x00ff00) >> 8;
const b1 = c1 & 0x0000ff;
const r2 = (c2 & 0xff0000) >> 16;
const g2 = (c2 & 0x00ff00) >> 8;
const b2 = c2 & 0x0000ff;
const r = r1 + (r2 - r1) * t;
const g = g1 + (g2 - g1) * t;
const b = b1 + (b2 - b1) * t;
return (r << 16) + (g << 8) + b;
}
static getBlend(c1, c2, t) {
const r = c1._r + (c2._r - c1._r) * t;
const g = c1._g + (c2._g - c1._g) * t;
const b = c1._b + (c2._b - c1._b) * t;
const a = c1._a + (c2._a - c1._a) * t;
return new Color(r, g, b, a);
}
static isCSSColor(color) {
if (arguments.length > 1 || typeof color !== 'string') {
return false;
}
return rgb.test(color) || rgba.test(color) || hex.test(color) || hexShort.test(color) || hsl.test(color) || hsla.test(color) || colorStruct[color.toLowerCase()];
}
static getBestContrast(color, cl, cd) {
const lum = color.getLuminance();
return Math.abs(lum - cl.getLuminance()) > Math.abs(lum - cd.getLuminance()) ? cl : cd;
}
static getContrast(color1, color2) {
if (!color1 || !color2) {
return undefined;
}
const l1 = color1.getLuminance() / 100;
const l2 = color2.getLuminance() / 100;
if (l1 > l2) {
return (l1 + 0.05) / (l2 + 0.05);
}
return (l2 + 0.05) / (l1 + 0.05);
}
static isDark() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
const C = new Color(...args);
return C.isDark(...args);
}
static useDarkLabel(areaColor, bgIsDark) {
return areaColor._a > 0.5 ? !areaColor.isDark() : !bgIsDark;
}
}
/**
* @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 => {
const colors = s.colors && s.colors[0] !== 'none' ? ['none', ...s.colors] : s.colors;
pals.push({
key: 'ui',
name: s.name,
translation: s.translation,
type: 'row',
colors: 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) {
const indexIsValid = typeof (c === null || c === void 0 ? void 0 : c.index) === 'number' && !Number.isNaN(c === null || c === void 0 ? void 0 : c.index);
const colorIsValid = typeof (c === null || c === void 0 ? void 0 : c.color) === 'string';
const somethingIsValid = indexIsValid || colorIsValid;
if (!somethingIsValid) {
return undefined;
}
const getColor = () => {
if ((c === null || c === void 0 ? void 0 : c.index) < 0 || typeof (c === null || c === void 0 ? void 0 : 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];
};
const color = getColor();
if (c.alpha === undefined || c.alpha >= 1 || c.alpha < 0) {
return color;
}
const rgbaColor = new Color(color);
rgbaColor.setAlpha(c.alpha);
if (rgbaColor.isInvalid()) {
return color;
}
return rgbaColor.toRGBA();
}
};
}
/**
* 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$1(r, g, b, a);
}
class ColorScale {
constructor(nanColor) {
this.colorParts = [];
this.startLevel = 0;
this.max = 1;
this.min = 0;
this.nanColor = color$3(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$3(color1), color$3(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$3(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$2(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$2(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 = originalExtend(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$3(colStr); // this needs to handle bad colors
if (!c) return 0;
const {
r,
g,
b
} = c.rgb();
// 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;
/**
* Returns theme name
*
* @method
* @name Theme#name
* @returns {string} Current theme.
* @example
* theme.name();
*/
/**
* @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);
},
/**
* Validates a color string using d3-color.
* See https://www.npmjs.com/package/d3-color
* Additionally supports the non-standard engine
* format ARGB(0-255,0-255,0-255,0-255)
* @param {string} specifier
* @returns {string|undefined} The resolved color or undefined
* @ignore
*
* @example
* theme.validateColor("red"); // returns "rgba(255,0,0,1)"
* theme.validateColor("#00ff00"); // returns "rgba(0,255,0,1)"
* theme.validateColor("ARGB(102,255,50,100)"); // returns "rgba(255,50,100,0.4)"
* theme.validateColor("FOO"); // returns undefined
*/
validateColor() {
/* Added this to support the non-standard ARGB format from engine */
const colorString = arguments.length <= 0 ? undefined : arguments[0];
let matches;
/* eslint-disable no-cond-assign */
if (typeof colorString === 'string' && (matches = /^ARGB\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i.exec(colorString))) {
// ARGB(255,255,255,255)
const a = parseInt(matches[1], 10) / 255;
const r = parseInt(matches[2], 10);
const g = parseInt(matches[3], 10);
const b = parseInt(matches[4], 10);
return "rgba(".concat(r, ",").concat(g, ",").concat(b, ",").concat(a, ")");
}
/* eslint-enable no-cond-assign */
const c = color$3(...arguments);
return c ? c.toString() : undefined;
}
};
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(EventEmitter.prototype).forEach(key => {
externalAPI[key] = EventEmitter.prototype[key];
});
EventEmitter.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 = [],
loadTheme,
root
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const wrappedTheme = theme();
const setTheme = async themeId => {
let found = themes.filter(t => t.id === themeId)[0];
let muiTheme = themeId === 'dark' ? 'dark' : 'light';
if (!found && loadTheme) {
found = {
load: loadTheme
};
}
if (found && found.load) {
try {
const raw = await Promise.race([found.load(themeId), 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';
}
var client = {};
var reactDom = {exports: {}};
var reactDom_production_min = {};
var scheduler = {exports: {}};
var scheduler_production_min = {};
/**
* @license React
* scheduler.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 hasRequiredScheduler_production_min;
function requireScheduler_production_min () {
if (hasRequiredScheduler_production_min) return scheduler_production_min;
hasRequiredScheduler_production_min = 1;
(function (exports$1) {
function f(a,b){var c=a.length;a.push(b);a:for(;0<c;){var d=c-1>>>1,e=a[d];if(0<g(e,b))a[d]=b,a[c]=e,c=d;else break a}}function h(a){return 0===a.length?null:a[0]}function k(a){if(0===a.length)return null;var b=a[0],c=a.pop();if(c!==b){a[0]=c;a:for(var d=0,e=a.length,w=e>>>1;d<w;){var m=2*(d+1)-1,C=a[m],n=m+1,x=a[n];if(0>g(C,c))n<e&&0>g(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(n<e&&0>g(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}
function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports$1.unstable_now=function(){return l.now()};}else {var p=Date,q=p.now();exports$1.unstable_now=function(){return p.now()-q};}var r=[],t=[],u=1,v=null,y=3,z=false,A=false,B=false,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null;
"undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t);}}function H(a){B=false;G(a);if(!A)if(null!==h(r))A=true,I(J);else {var b=h(t);null!==b&&K(H,b.startTime-a);}}
function J(a,b){A=false;B&&(B=false,E(L),L=-1);z=true;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports$1.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b);}else k(r);v=h(r);}if(null!==v)var w=!0;else {var m=h(t);null!==m&&K(H,m.startTime-b);w=!1;}return w}finally{v=null,y=c,z=false;}}var N=false,O=null,L=-1,P=5,Q=-1;
function M(){return exports$1.unstable_now()-Q<P?false:true}function R(){if(null!==O){var a=exports$1.unstable_now();Q=a;var b=true;try{b=O(!0,a);}finally{b?S():(N=false,O=null);}}else N=false;}var S;if("function"===typeof F)S=function(){F(R);};else if("undefined"!==typeof MessageChannel){var T=new MessageChannel,U=T.port2;T.port1.onmessage=R;S=function(){U.postMessage(null);};}else S=function(){D(R,0);};function I(a){O=a;N||(N=true,S());}function K(a,b){L=D(function(){a(exports$1.unstable_now());},b);}
exports$1.unstable_IdlePriority=5;exports$1.unstable_ImmediatePriority=1;exports$1.unstable_LowPriority=4;exports$1.unstable_NormalPriority=3;exports$1.unstable_Profiling=null;exports$1.unstable_UserBlockingPriority=2;exports$1.unstable_cancelCallback=function(a){a.callback=null;};exports$1.unstable_continueExecution=function(){A||z||(A=true,I(J));};
exports$1.unstable_forceFrameRate=function(a){0>a||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):P=0<a?Math.floor(1E3/a):5;};exports$1.unstable_getCurrentPriorityLevel=function(){return y};exports$1.unstable_getFirstCallbackNode=function(){return h(r)};exports$1.unstable_next=function(a){switch(y){case 1:case 2:case 3:var b=3;break;default:b=y;}var c=y;y=b;try{return a()}finally{y=c;}};exports$1.unstable_pauseExecution=function(){};
exports$1.unstable_requestPaint=function(){};exports$1.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3;}var c=y;y=a;try{return b()}finally{y=c;}};
exports$1.unstable_scheduleCallback=function(a,b,c){var d=exports$1.unstable_now();"object"===typeof c&&null!==c?(c=c.delay,c="number"===typeof c&&0<c?d+c:d):c=d;switch(a){case 1:var e=-1;break;case 2:e=250;break;case 5:e=1073741823;break;case 4:e=1E4;break;default:e=5E3;}e=c+e;a={id:u++,callback:b,priorityLevel:a,startTime:c,expirationTime:e,sortIndex:-1};c>d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=true,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=true,I(J)));return a};
exports$1.unstable_shouldYield=M;exports$1.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c;}}};
} (scheduler_production_min));
return scheduler_production_min;
}
var hasRequiredScheduler;
function requireScheduler () {
if (hasRequiredScheduler) return scheduler.exports;
hasRequiredScheduler = 1;
{
scheduler.exports = requireScheduler_production_min();
}
return scheduler.exports;
}
/**
* @license React
* react-dom.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 hasRequiredReactDom_production_min;
function requireReactDom_production_min () {
if (hasRequiredReactDom_production_min) return reactDom_production_min;
hasRequiredReactDom_production_min = 1;
var aa=requireReact(),ca=requireScheduler();function p(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return "Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var da=new Set,ea={};function fa(a,b){ha(a,b);ha(a+"Capture",b);}
function ha(a,b){ea[a]=b;for(a=0;a<b.length;a++)da.add(b[a]);}
var ia=!("undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement),ja=Object.prototype.hasOwnProperty,ka=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,la=
{},ma={};function oa(a){if(ja.call(ma,a))return true;if(ja.call(la,a))return false;if(ka.test(a))return ma[a]=true;la[a]=true;return false}function pa(a,b,c,d){if(null!==c&&0===c.type)return false;switch(typeof b){case "function":case "symbol":return true;case "boolean":if(d)return false;if(null!==c)return !c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return "data-"!==a&&"aria-"!==a;default:return false}}
function qa(a,b,c,d){if(null===b||"undefined"===typeof b||pa(a,b,c,d))return true;if(d)return false;if(null!==c)switch(c.type){case 3:return !b;case 4:return false===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return false}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g;}var z={};
"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){z[a]=new v(a,0,false,a,null,false,false);});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,false,a[1],null,false,false);});["contentEditable","draggable","spellCheck","value"].forEach(function(a){z[a]=new v(a,2,false,a.toLowerCase(),null,false,false);});
["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){z[a]=new v(a,2,false,a,null,false,false);});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){z[a]=new v(a,3,false,a.toLowerCase(),null,false,false);});
["checked","multiple","muted","selected"].forEach(function(a){z[a]=new v(a,3,true,a,null,false,false);});["capture","download"].forEach(function(a){z[a]=new v(a,4,false,a,null,false,false);});["cols","rows","size","span"].forEach(function(a){z[a]=new v(a,6,false,a,null,false,false);});["rowSpan","start"].forEach(function(a){z[a]=new v(a,5,false,a.toLowerCase(),null,false,false);});var ra=/[\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}
"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ra,
sa);z[b]=new v(b,1,false,a,null,false,false);});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,false,a,"http://www.w3.org/1999/xlink",false,false);});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,false,a,"http://www.w3.org/XML/1998/namespace",false,false);});["tabIndex","crossOrigin"].forEach(function(a){z[a]=new v(a,1,false,a.toLowerCase(),null,false,false);});
z.xlinkHref=new v("xlinkHref",1,false,"xlink:href","http://www.w3.org/1999/xlink",true,false);["src","href","action","formAction"].forEach(function(a){z[a]=new v(a,1,false,a.toLowerCase(),null,true,true);});
function ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2<b.length)||"o"!==b[0]&&"O"!==b[0]||"n"!==b[1]&&"N"!==b[1])qa(b,c,e,d)&&(c=null),d||null===e?oa(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,""+c)):e.mustUseProperty?a[e.propertyName]=null===c?3===e.type?false:"":c:(b=e.attributeName,d=e.attributeNamespace,null===c?a.removeAttribute(b):(e=e.type,c=3===e||4===e&&true===c?"":""+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c)));}
var ua=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,va=Symbol.for("react.element"),wa=Symbol.for("react.portal"),ya=Symbol.for("react.fragment"),za=Symbol.for("react.strict_mode"),Aa=Symbol.for("react.profiler"),Ba=Symbol.for("react.provider"),Ca=Symbol.for("react.context"),Da=Symbol.for("react.forward_ref"),Ea=Symbol.for("react.suspense"),Fa=Symbol.for("react.suspense_list"),Ga=Symbol.for("react.memo"),Ha=Symbol.for("react.lazy"); var Ia=Symbol.for("react.offscreen");var Ja=Symbol.iterator;function Ka(a){if(null===a||"object"!==typeof a)return null;a=Ja&&a[Ja]||a["@@iterator"];return "function"===typeof a?a:null}var A=Object.assign,La;function Ma(a){if(void 0===La)try{throw Error();}catch(c){var b=c.stack.trim().match(/\n( *(at )?)/);La=b&&b[1]||"";}return "\n"+La+a}var Na=false;
function Oa(a,b){if(!a||Na)return "";Na=true;var c=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(b)if(b=function(){throw Error();},Object.defineProperty(b.prototype,"props",{set:function(){throw Error();}}),"object"===typeof Reflect&&Reflect.construct){try{Reflect.construct(b,[]);}catch(l){var d=l;}Reflect.construct(a,[],b);}else {try{b.call();}catch(l){d=l;}a.call(b.prototype);}else {try{throw Error();}catch(l){d=l;}a();}}catch(l){if(l&&d&&"string"===typeof l.stack){for(var e=l.stack.split("\n"),
f=d.stack.split("\n"),g=e.length-1,h=f.length-1;1<=g&&0<=h&&e[g]!==f[h];)h--;for(;1<=g&&0<=h;g--,h--)if(e[g]!==f[h]){if(1!==g||1!==h){do if(g--,h--,0>h||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("<anonymous>")&&(k=k.replace("<anonymous>",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=false,Error.prepareStackTrace=c;}return (a=a?a.displayName||a.name:"")?Ma(a):""}
function Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma("Lazy");case 13:return Ma("Suspense");case 19:return Ma("SuspenseList");case 0:case 2:case 15:return a=Oa(a.type,false),a;case 11:return a=Oa(a.type.render,false),a;case 1:return a=Oa(a.type,true),a;default:return ""}}
function Qa(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case ya:return "Fragment";case wa:return "Portal";case Aa:return "Profiler";case za:return "StrictMode";case Ea:return "Suspense";case Fa:return "SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Ca:return (a.displayName||"Context")+".Consumer";case Ba:return (a._context.displayName||"Context")+".Provider";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||
b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||"Memo";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}
function Ra(a){var b=a.type;switch(a.tag){case 24:return "Cache";case 9:return (b.displayName||"Context")+".Consumer";case 10:return (b._context.displayName||"Context")+".Provider";case 18:return "DehydratedFragment";case 11:return a=b.render,a=a.displayName||a.name||"",b.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return "Fragment";case 5:return b;case 4:return "Portal";case 3:return "Root";case 6:return "Text";case 16:return Qa(b);case 8:return b===za?"StrictMode":"Mode";case 22:return "Offscreen";
case 12:return "Profiler";case 21:return "Scope";case 13:return "Suspense";case 19:return "SuspenseList";case 25:return "TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof b)return b.displayName||b.name||null;if("string"===typeof b)return b}return null}function Sa(a){switch(typeof a){case "boolean":case "number":case "string":case "undefined":return a;case "object":return a;default:return ""}}
function Ta(a){var b=a.type;return (a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)}
function Ua(a){var b=Ta(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:true,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a);}});Object.defineProperty(a,b,{enumerable:c.enumerable});return {getValue:function(){return d},setValue:function(a){d=""+a;},stopTracking:function(){a._valueTracker=
null;delete a[b];}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a));}function Wa(a){if(!a)return false;var b=a._valueTracker;if(!b)return true;var c=b.getValue();var d="";a&&(d=Ta(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),true):false}function Xa(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}
function Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value};}function ab(a,b){b=b.checked;null!=b&&ta(a,"checked",b,false);}
function bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c;}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?cb(a,b.type,c):b.hasOwnProperty("defaultValue")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked);}
function db(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b;}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c);}
function cb(a,b,c){if("number"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c);}var eb=Array.isArray;
function fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e<c.length;e++)b["$"+c[e]]=true;for(c=0;c<a.length;c++)e=b.hasOwnProperty("$"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=true);}else {c=""+Sa(c);b=null;for(e=0;e<a.length;e++){if(a[e].value===c){a[e].selected=true;d&&(a[e].defaultSelected=true);return}null!==b||a[e].disabled||(b=a[e]);}null!==b&&(b.selected=true);}}
function gb(a,b){if(null!=b.dangerouslySetInnerHTML)throw Error(p(91));return A({},b,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function hb(a,b){var c=b.value;if(null==c){c=b.children;b=b.defaultValue;if(null!=c){if(null!=b)throw Error(p(92));if(eb(c)){if(1<c.length)throw Error(p(93));c=c[0];}b=c;}null==b&&(b="");c=b;}a._wrapperState={initialValue:Sa(c)};}
function ib(a,b){var c=Sa(b.value),d=Sa(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d);}function jb(a){var b=a.textContent;b===a._wrapperState.initialValue&&""!==b&&null!==b&&(a.value=b);}function kb(a){switch(a){case "svg":return "http://www.w3.org/2000/svg";case "math":return "http://www.w3.org/1998/Math/MathML";default:return "http://www.w3.org/1999/xhtml"}}
function lb(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?kb(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a}
var mb,nb=function(a){return "undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)});}:a}(function(a,b){if("http://www.w3.org/2000/svg"!==a.namespaceURI||"innerHTML"in a)a.innerHTML=b;else {mb=mb||document.createElement("div");mb.innerHTML="<svg>"+b.valueOf().toString()+"</svg>";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild);}});
function ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b;}
var pb={animationIterationCount:true,aspectRatio:true,borderImageOutset:true,borderImageSlice:true,borderImageWidth:true,boxFlex:true,boxFlexGroup:true,boxOrdinalGroup:true,columnCount:true,columns:true,flex:true,flexGrow:true,flexPositive:true,flexShrink:true,flexNegative:true,flexOrder:true,gridArea:true,gridRow:true,gridRowEnd:true,gridRowSpan:true,gridRowStart:true,gridColumn:true,gridColumnEnd:true,gridColumnSpan:true,gridColumnStart:true,fontWeight:true,lineClamp:true,lineHeight:true,opacity:true,order:true,orphans:true,tabSize:true,widows:true,zIndex:true,
zoom:true,fillOpacity:true,floodOpacity:true,stopOpacity:true,strokeDasharray:true,strokeDashoffset:true,strokeMiterlimit:true,strokeOpacity:true,strokeWidth:true},qb=["Webkit","ms","Moz","O"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a];});});function rb(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(""+b).trim():b+"px"}
function sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=rb(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e;}}var tb=A({menuitem:true},{area:true,base:true,br:true,col:true,embed:true,hr:true,img:true,input:true,keygen:true,link:true,meta:true,param:true,source:true,track:true,wbr:true});
function ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if("object"!==typeof b.dangerouslySetInnerHTML||!("__html"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(p(62));}}
function vb(a,b){if(-1===a.indexOf("-"))return "string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return false;default:return true}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;
function Bb(a){if(a=Cb(a)){if("function"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b));}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a;}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a<b.length;a++)Bb(b[a]);}}function Gb(a,b){return a(b)}function Hb(){}var Ib=false;function Jb(a,b,c){if(Ib)return a(b,c);Ib=true;try{return Gb(a,b,c)}finally{if(Ib=false,null!==zb||null!==Ab)Hb(),Fb();}}
function Kb(a,b){var c=a.stateNode;if(null===c)return null;var d=Db(c);if(null===d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":case "onMouseEnter":(d=!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=false;}if(a)return null;if(c&&"function"!==
typeof c)throw Error(p(231,b,typeof c));return c}var Lb=false;if(ia)try{var Mb={};Object.defineProperty(Mb,"passive",{get:function(){Lb=!0;}});window.addEventListener("test",Mb,Mb);window.removeEventListener("test",Mb,Mb);}catch(a){Lb=false;}function Nb(a,b,c,d,e,f,g,h,k){var l=Array.prototype.slice.call(arguments,3);try{b.apply(c,l);}catch(m){this.onError(m);}}var Ob=false,Pb=null,Qb=false,Rb=null,Sb={onError:function(a){Ob=true;Pb=a;}};function Tb(a,b,c,d,e,f,g,h,k){Ob=false;Pb=null;Nb.apply(Sb,arguments);}
function Ub(a,b,c,d,e,f,g,h,k){Tb.apply(this,arguments);if(Ob){if(Ob){var l=Pb;Ob=false;Pb=null;}else throw Error(p(198));Qb||(Qb=true,Rb=l);}}function Vb(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else {a=b;do b=a,0!==(b.flags&4098)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function Wb(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function Xb(a){if(Vb(a)!==a)throw Error(p(188));}
function Yb(a){var b=a.alternate;if(!b){b=Vb(a);if(null===b)throw Error(p(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return Xb(e),a;if(f===d)return Xb(e),b;f=f.sibling;}throw Error(p(188));}if(c.return!==d.return)c=e,d=f;else {for(var g=false,h=e.child;h;){if(h===c){g=true;c=e;d=f;break}if(h===d){g=true;d=e;c=f;break}h=h.sibling;}if(!g){for(h=f.child;h;){if(h===
c){g=true;c=f;d=e;break}if(h===d){g=true;d=f;c=e;break}h=h.sibling;}if(!g)throw Error(p(189));}}if(c.alternate!==d)throw Error(p(190));}if(3!==c.tag)throw Error(p(188));return c.stateNode.current===c?a:b}function Zb(a){a=Yb(a);return null!==a?$b(a):null}function $b(a){if(5===a.tag||6===a.tag)return a;for(a=a.child;null!==a;){var b=$b(a);if(null!==b)return b;a=a.sibling;}return null}
var ac=ca.unstable_scheduleCallback,bc=ca.unstable_cancelCallback,cc=ca.unstable_shouldYield,dc=ca.unstable_requestPaint,B=ca.unstable_now,ec=ca.unstable_getCurrentPriorityLevel,fc=ca.unstable_ImmediatePriority,gc=ca.unstable_UserBlockingPriority,hc=ca.unstable_NormalPriority,ic=ca.unstable_LowPriority,jc=ca.unstable_IdlePriority,kc=null,lc=null;function mc(a){if(lc&&"function"===typeof lc.onCommitFiberRoot)try{lc.onCommitFiberRoot(kc,a,void 0,128===(a.current.flags&128));}catch(b){}}
var oc=Math.clz32?Math.clz32:nc,pc=Math.log,qc=Math.LN2;function nc(a){a>>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;
function tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;
default:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)));}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0<b;)c=31-oc(b),e=1<<c,d|=a[c],b&=~e;return d}
function vc(a,b){switch(a){case 1:case 2:case 4:return b+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return b+5E3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return -1;case 134217728:case 268435456:case 536870912:case 1073741824:return -1;default:return -1}}
function wc(a,b){for(var c=a.suspendedLanes,d=a.pingedLanes,e=a.expirationTimes,f=a.pendingLanes;0<f;){var g=31-oc(f),h=1<<g,k=e[g];if(-1===k){if(0===(h&c)||0!==(h&d))e[g]=vc(h,b);}else k<=b&&(a.expiredLanes|=h);f&=~h;}}function xc(a){a=a.pendingLanes&-1073741825;return 0!==a?a:a&1073741824?1073741824:0}function yc(){var a=rc;rc<<=1;0===(rc&4194240)&&(rc=64);return a}function zc(a){for(var b=[],c=0;31>c;c++)b.push(a);return b}
function Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c;}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0<c;){var e=31-oc(c),f=1<<e;b[e]=0;d[e]=-1;a[e]=-1;c&=~f;}}
function Cc(a,b){var c=a.entangledLanes|=b;for(a=a.entanglements;c;){var d=31-oc(c),e=1<<d;e&b|a[d]&b&&(a[d]|=b);c&=~e;}}var C=0;function Dc(a){a&=-a;return 1<a?4<a?0!==(a&268435455)?16:536870912:4:1}var Ec,Fc,Gc,Hc,Ic,Jc=false,Kc=[],Lc=null,Mc=null,Nc=null,Oc=new Map,Pc=new Map,Qc=[],Rc="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");
function Sc(a,b){switch(a){case "focusin":case "focusout":Lc=null;break;case "dragenter":case "dragleave":Mc=null;break;case "mouseover":case "mouseout":Nc=null;break;case "pointerover":case "pointerout":Oc.delete(b.pointerId);break;case "gotpointercapture":case "lostpointercapture":Pc.delete(b.pointerId);}}
function Tc(a,b,c,d,e,f){if(null===a||a.nativeEvent!==f)return a={blockedOn:b,domEventName:c,eventSystemFlags:d,nativeEvent:f,targetContainers:[e]},null!==b&&(b=Cb(b),null!==b&&Fc(b)),a;a.eventSystemFlags|=d;b=a.targetContainers;null!==e&&-1===b.indexOf(e)&&b.push(e);return a}
function Uc(a,b,c,d,e){switch(b){case "focusin":return Lc=Tc(Lc,a,b,c,d,e),true;case "dragenter":return Mc=Tc(Mc,a,b,c,d,e),true;case "mouseover":return Nc=Tc(Nc,a,b,c,d,e),true;case "pointerover":var f=e.pointerId;Oc.set(f,Tc(Oc.get(f)||null,a,b,c,d,e));return true;case "gotpointercapture":return f=e.pointerId,Pc.set(f,Tc(Pc.get(f)||null,a,b,c,d,e)),true}return false}
function Vc(a){var b=Wc(a.target);if(null!==b){var c=Vb(b);if(null!==c)if(b=c.tag,13===b){if(b=Wb(c),null!==b){a.blockedOn=b;Ic(a.priority,function(){Gc(c);});return}}else if(3===b&&c.stateNode.current.memoizedState.isDehydrated){a.blockedOn=3===c.tag?c.stateNode.containerInfo:null;return}}a.blockedOn=null;}
function Xc(a){if(null!==a.blockedOn)return false;for(var b=a.targetContainers;0<b.length;){var c=Yc(a.domEventName,a.eventSystemFlags,b[0],a.nativeEvent);if(null===c){c=a.nativeEvent;var d=new c.constructor(c.type,c);wb=d;c.target.dispatchEvent(d);wb=null;}else return b=Cb(c),null!==b&&Fc(b),a.blockedOn=c,false;b.shift();}return true}function Zc(a,b,c){Xc(a)&&c.delete(b);}function $c(){Jc=false;null!==Lc&&Xc(Lc)&&(Lc=null);null!==Mc&&Xc(Mc)&&(Mc=null);null!==Nc&&Xc(Nc)&&(Nc=null);Oc.forEach(Zc);Pc.forEach(Zc);}
function ad(a,b){a.blockedOn===b&&(a.blockedOn=null,Jc||(Jc=true,ca.unstable_scheduleCallback(ca.unstable_NormalPriority,$c)));}
function bd(a){function b(b){return ad(b,a)}if(0<Kc.length){ad(Kc[0],a);for(var c=1;c<Kc.length;c++){var d=Kc[c];d.blockedOn===a&&(d.blockedOn=null);}}null!==Lc&&ad(Lc,a);null!==Mc&&ad(Mc,a);null!==Nc&&ad(Nc,a);Oc.forEach(b);Pc.forEach(b);for(c=0;c<Qc.length;c++)d=Qc[c],d.blockedOn===a&&(d.blockedOn=null);for(;0<Qc.length&&(c=Qc[0],null===c.blockedOn);)Vc(c),null===c.blockedOn&&Qc.shift();}var cd=ua.ReactCurrentBatchConfig,dd=true;
function ed(a,b,c,d){var e=C,f=cd.transition;cd.transition=null;try{C=1,fd(a,b,c,d);}finally{C=e,cd.transition=f;}}function gd(a,b,c,d){var e=C,f=cd.transition;cd.transition=null;try{C=4,fd(a,b,c,d);}finally{C=e,cd.transition=f;}}
function fd(a,b,c,d){if(dd){var e=Yc(a,b,c,d);if(null===e)hd(a,b,d,id,c),Sc(a,d);else if(Uc(e,a,b,c,d))d.stopPropagation();else if(Sc(a,d),b&4&&-1<Rc.indexOf(a)){for(;null!==e;){var f=Cb(e);null!==f&&Ec(f);f=Yc(a,b,c,d);null===f&&hd(a,b,d,id,c);if(f===e)break;e=f;}null!==e&&d.stopPropagation();}else hd(a,b,d,null,c);}}var id=null;
function Yc(a,b,c,d){id=null;a=xb(d);a=Wc(a);if(null!==a)if(b=Vb(a),null===b)a=null;else if(c=b.tag,13===c){a=Wb(b);if(null!==a)return a;a=null;}else if(3===c){if(b.stateNode.current.memoizedState.isDehydrated)return 3===b.tag?b.stateNode.containerInfo:null;a=null;}else b!==a&&(a=null);id=a;return null}
function jd(a){switch(a){case "cancel":case "click":case "close":case "contextmenu":case "copy":case "cut":case "auxclick":case "dblclick":case "dragend":case "dragstart":case "drop":case "focusin":case "focusout":case "input":case "invalid":case "keydown":case "keypress":case "keyup":case "mousedown":case "mouseup":case "paste":case "pause":case "play":case "pointercancel":case "pointerdown":case "pointerup":case "ratechange":case "reset":case "resize":case "seeked":case "submit":case "touchcancel":case "touchend":case "touchstart":case "volumechange":case "change":case "selectionchange":case "textInput":case "compositionstart":case "compositionend":case "compositionupdate":case "beforeblur":case "afterblur":case "beforeinput":case "blur":case "fullscreenchange":case "focus":case "hashchange":case "popstate":case "select":case "selectstart":return 1;case "drag":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "mousemove":case "mouseout":case "mouseover":case "pointermove":case "pointerout":case "pointerover":case "scroll":case "toggle":case "touchmove":case "wheel":case "mouseenter":case "mouseleave":case "pointerenter":case "pointerleave":return 4;
case "message":switch(ec()){case fc:return 1;case gc:return 4;case hc:case ic:return 16;case jc:return 536870912;default:return 16}default:return 16}}var kd=null,ld=null,md=null;function nd(){if(md)return md;var a,b=ld,c=b.length,d,e="value"in kd?kd.value:kd.textContent,f=e.length;for(a=0;a<c&&b[a]===e[a];a++);var g=c-a;for(d=1;d<=g&&b[c-d]===e[f-d];d++);return md=e.slice(a,1<d?1-d:void 0)}
function od(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0}function pd(){return true}function qd(){return false}
function rd(a){function b(b,d,e,f,g){this._reactName=b;this._targetInst=e;this.type=d;this.nativeEvent=f;this.target=g;this.currentTarget=null;for(var c in a)a.hasOwnProperty(c)&&(b=a[c],this[c]=b?b(f):f[c]);this.isDefaultPrevented=(null!=f.defaultPrevented?f.defaultPrevented:false===f.returnValue)?pd:qd;this.isPropagationStopped=qd;return this}A(b.prototype,{preventDefault:function(){this.defaultPrevented=true;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&
(a.returnValue=false),this.isDefaultPrevented=pd);},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=true),this.isPropagationStopped=pd);},persist:function(){},isPersistent:pd});return b}
var sd={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},td=rd(sd),ud=A({},sd,{view:0,detail:0}),vd=rd(ud),wd,xd,yd,Ad=A({},ud,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:zd,button:0,buttons:0,relatedTarget:function(a){return void 0===a.relatedTarget?a.fromElement===a.srcElement?a.toElement:a.fromElement:a.relatedTarget},movementX:function(a){if("movementX"in
a)return a.movementX;a!==yd&&(yd&&"mousemove"===a.type?(wd=a.screenX-yd.screenX,xd=a.screenY-yd.screenY):xd=wd=0,yd=a);return wd},movementY:function(a){return "movementY"in a?a.movementY:xd}}),Bd=rd(Ad),Cd=A({},Ad,{dataTransfer:0}),Dd=rd(Cd),Ed=A({},ud,{relatedTarget:0}),Fd=rd(Ed),Gd=A({},sd,{animationName:0,elapsedTime:0,pseudoElement:0}),Hd=rd(Gd),Id=A({},sd,{clipboardData:function(a){return "clipboardData"in a?a.clipboardData:window.clipboardData}}),Jd=rd(Id),Kd=A({},sd,{data:0}),Ld=rd(Kd),Md={Esc:"Escape",
Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Nd={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",
119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Od={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Pd(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=Od[a])?!!b[a]:false}function zd(){return Pd}
var Qd=A({},ud,{key:function(a){if(a.key){var b=Md[a.key]||a.key;if("Unidentified"!==b)return b}return "keypress"===a.type?(a=od(a),13===a?"Enter":String.fromCharCode(a)):"keydown"===a.type||"keyup"===a.type?Nd[a.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:zd,charCode:function(a){return "keypress"===a.type?od(a):0},keyCode:function(a){return "keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return "keypress"===
a.type?od(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}}),Rd=rd(Qd),Sd=A({},Ad,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Td=rd(Sd),Ud=A({},ud,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:zd}),Vd=rd(Ud),Wd=A({},sd,{propertyName:0,elapsedTime:0,pseudoElement:0}),Xd=rd(Wd),Yd=A({},Ad,{deltaX:function(a){return "deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},
deltaY:function(a){return "deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0}),Zd=rd(Yd),$d=[9,13,27,32],ae=ia&&"CompositionEvent"in window,be=null;ia&&"documentMode"in document&&(be=document.documentMode);var ce=ia&&"TextEvent"in window&&!be,de=ia&&(!ae||be&&8<be&&11>=be),ee=String.fromCharCode(32),fe=false;
function ge(a,b){switch(a){case "keyup":return -1!==$d.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "focusout":return true;default:return false}}function he(a){a=a.detail;return "object"===typeof a&&"data"in a?a.data:null}var ie=false;function je(a,b){switch(a){case "compositionend":return he(b);case "keypress":if(32!==b.which)return null;fe=true;return ee;case "textInput":return a=b.data,a===ee&&fe?null:a;default:return null}}
function ke(a,b){if(ie)return "compositionend"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=false,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;case "compositionend":return de&&"ko"!==b.locale?null:b.data;default:return null}}
var le={color:true,date:true,datetime:true,"datetime-local":true,email:true,month:true,number:true,password:true,range:true,search:true,tel:true,text:true,time:true,url:true,week:true};function me(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return "input"===b?!!le[a.type]:"textarea"===b?true:false}function ne(a,b,c,d){Eb(d);b=oe(b,"onChange");0<b.length&&(c=new td("onChange","change",null,c,d),a.push({event:c,listeners:b}));}var pe=null,qe=null;function re(a){se(a,0);}function te(a){var b=ue(a);if(Wa(b))return a}
function ve(a,b){if("change"===a)return b}var we=false;if(ia){var xe;if(ia){var ye="oninput"in document;if(!ye){var ze=document.createElement("div");ze.setAttribute("oninput","return;");ye="function"===typeof ze.oninput;}xe=ye;}else xe=false;we=xe&&(!document.documentMode||9<document.documentMode);}function Ae(){pe&&(pe.detachEvent("onpropertychange",Be),qe=pe=null);}function Be(a){if("value"===a.propertyName&&te(qe)){var b=[];ne(b,qe,a,xb(a));Jb(re,b);}}
function Ce(a,b,c){"focusin"===a?(Ae(),pe=b,qe=c,pe.attachEvent("onpropertychange",Be)):"focusout"===a&&Ae();}function De(a){if("selectionchange"===a||"keyup"===a||"keydown"===a)return te(qe)}function Ee(a,b){if("click"===a)return te(b)}function Fe(a,b){if("input"===a||"change"===a)return te(b)}function Ge(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var He="function"===typeof Object.is?Object.is:Ge;
function Ie(a,b){if(He(a,b))return true;if("object"!==typeof a||null===a||"object"!==typeof b||null===b)return false;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return false;for(d=0;d<c.length;d++){var e=c[d];if(!ja.call(b,e)||!He(a[e],b[e]))return false}return true}function Je(a){for(;a&&a.firstChild;)a=a.firstChild;return a}
function Ke(a,b){var c=Je(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;if(a<=b&&d>=b)return {node:c,offset:b-a};a=d;}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode;}c=void 0;}c=Je(c);}}function Le(a,b){return a&&b?a===b?true:a&&3===a.nodeType?false:b&&3===b.nodeType?Le(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):false:false}
function Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href;}catch(d){c=false;}if(c)a=b.contentWindow;else break;b=Xa(a.document);}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)}
function Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,
d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)));}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c<b.length;c++)a=b[c],a.element.scrollLeft=a.left,a.element.scrollTop=a.top;}}
var Pe=ia&&"documentMode"in document&&11>=document.documentMode,Qe=null,Re=null,Se=null,Te=false;
function Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,"selectionStart"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,"onSelect"),0<d.length&&(b=new td("onSelect","select",null,b,c),a.push({event:b,listeners:d}),b.target=Qe)));}
function Ve(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}var We={animationend:Ve("Animation","AnimationEnd"),animationiteration:Ve("Animation","AnimationIteration"),animationstart:Ve("Animation","AnimationStart"),transitionend:Ve("Transition","TransitionEnd")},Xe={},Ye={};
ia&&(Ye=document.createElement("div").style,"AnimationEvent"in window||(delete We.animationend.animation,delete We.animationiteration.animation,delete We.animationstart.animation),"TransitionEvent"in window||delete We.transitionend.transition);function Ze(a){if(Xe[a])return Xe[a];if(!We[a])return a;var b=We[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Ye)return Xe[a]=b[c];return a}var $e=Ze("animationend"),af=Ze("animationiteration"),bf=Ze("animationstart"),cf=Ze("transitionend"),df=new Map,ef="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");
function ff(a,b){df.set(a,b);fa(b,[a]);}for(var gf=0;gf<ef.length;gf++){var hf=ef[gf],jf=hf.toLowerCase(),kf=hf[0].toUpperCase()+hf.slice(1);ff(jf,"on"+kf);}ff($e,"onAnimationEnd");ff(af,"onAnimationIteration");ff(bf,"onAnimationStart");ff("dblclick","onDoubleClick");ff("focusin","onFocus");ff("focusout","onBlur");ff(cf,"onTransitionEnd");ha("onMouseEnter",["mouseout","mouseover"]);ha("onMouseLeave",["mouseout","mouseover"]);ha("onPointerEnter",["pointerout","pointerover"]);
ha("onPointerLeave",["pointerout","pointerover"]);fa("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));fa("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));fa("onBeforeInput",["compositionend","keypress","textInput","paste"]);fa("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));fa("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));
fa("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var lf="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),mf=new Set("cancel close invalid load scroll toggle".split(" ").concat(lf));
function nf(a,b,c){var d=a.type||"unknown-event";a.currentTarget=c;Ub(d,b,void 0,a);a.currentTarget=null;}
function se(a,b){b=0!==(b&4);for(var c=0;c<a.length;c++){var d=a[c],e=d.event;d=d.listeners;a:{var f=void 0;if(b)for(var g=d.length-1;0<=g;g--){var h=d[g],k=h.instance,l=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;nf(e,h,l);f=k;}else for(g=0;g<d.length;g++){h=d[g];k=h.instance;l=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;nf(e,h,l);f=k;}}}if(Qb)throw a=Rb,Qb=false,Rb=null,a;}
function D(a,b){var c=b[of];void 0===c&&(c=b[of]=new Set);var d=a+"__bubble";c.has(d)||(pf(b,a,2,false),c.add(d));}function qf(a,b,c){var d=0;b&&(d|=4);pf(c,a,d,b);}var rf="_reactListening"+Math.random().toString(36).slice(2);function sf(a){if(!a[rf]){a[rf]=true;da.forEach(function(b){"selectionchange"!==b&&(mf.has(b)||qf(b,false,a),qf(b,true,a));});var b=9===a.nodeType?a:a.ownerDocument;null===b||b[rf]||(b[rf]=true,qf("selectionchange",false,b));}}
function pf(a,b,c,d){switch(jd(b)){case 1:var e=ed;break;case 4:e=gd;break;default:e=fd;}c=e.bind(null,b,c,a);e=void 0;!Lb||"touchstart"!==b&&"touchmove"!==b&&"wheel"!==b||(e=true);d?void 0!==e?a.addEventListener(b,c,{capture:true,passive:e}):a.addEventListener(b,c,true):void 0!==e?a.addEventListener(b,c,{passive:e}):a.addEventListener(b,c,false);}
function hd(a,b,c,d,e){var f=d;if(0===(b&1)&&0===(b&2)&&null!==d)a:for(;;){if(null===d)return;var g=d.tag;if(3===g||4===g){var h=d.stateNode.containerInfo;if(h===e||8===h.nodeType&&h.parentNode===e)break;if(4===g)for(g=d.return;null!==g;){var k=g.tag;if(3===k||4===k)if(k=g.stateNode.containerInfo,k===e||8===k.nodeType&&k.parentNode===e)return;g=g.return;}for(;null!==h;){g=Wc(h);if(null===g)return;k=g.tag;if(5===k||6===k){d=f=g;continue a}h=h.parentNode;}}d=d.return;}Jb(function(){var d=f,e=xb(c),g=[];
a:{var h=df.get(a);if(void 0!==h){var k=td,n=a;switch(a){case "keypress":if(0===od(c))break a;case "keydown":case "keyup":k=Rd;break;case "focusin":n="focus";k=Fd;break;case "focusout":n="blur";k=Fd;break;case "beforeblur":case "afterblur":k=Fd;break;case "click":if(2===c.button)break a;case "auxclick":case "dblclick":case "mousedown":case "mousemove":case "mouseup":case "mouseout":case "mouseover":case "contextmenu":k=Bd;break;case "drag":case "dragend":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "dragstart":case "drop":k=
Dd;break;case "touchcancel":case "touchend":case "touchmove":case "touchstart":k=Vd;break;case $e:case af:case bf:k=Hd;break;case cf:k=Xd;break;case "scroll":k=vd;break;case "wheel":k=Zd;break;case "copy":case "cut":case "paste":k=Jd;break;case "gotpointercapture":case "lostpointercapture":case "pointercancel":case "pointerdown":case "pointermove":case "pointerout":case "pointerover":case "pointerup":k=Td;}var t=0!==(b&4),J=!t&&"scroll"===a,x=t?null!==h?h+"Capture":null:h;t=[];for(var w=d,u;null!==
w;){u=w;var F=u.stateNode;5===u.tag&&null!==F&&(u=F,null!==x&&(F=Kb(w,x),null!=F&&t.push(tf(w,F,u))));if(J)break;w=w.return;}0<t.length&&(h=new k(h,n,null,c,e),g.push({event:h,listeners:t}));}}if(0===(b&7)){a:{h="mouseover"===a||"pointerover"===a;k="mouseout"===a||"pointerout"===a;if(h&&c!==wb&&(n=c.relatedTarget||c.fromElement)&&(Wc(n)||n[uf]))break a;if(k||h){h=e.window===e?e:(h=e.ownerDocument)?h.defaultView||h.parentWindow:window;if(k){if(n=c.relatedTarget||c.toElement,k=d,n=n?Wc(n):null,null!==
n&&(J=Vb(n),n!==J||5!==n.tag&&6!==n.tag))n=null;}else k=null,n=d;if(k!==n){t=Bd;F="onMouseLeave";x="onMouseEnter";w="mouse";if("pointerout"===a||"pointerover"===a)t=Td,F="onPointerLeave",x="onPointerEnter",w="pointer";J=null==k?h:ue(k);u=null==n?h:ue(n);h=new t(F,w+"leave",k,c,e);h.target=J;h.relatedTarget=u;F=null;Wc(e)===d&&(t=new t(x,w+"enter",n,c,e),t.target=u,t.relatedTarget=J,F=t);J=F;if(k&&n)b:{t=k;x=n;w=0;for(u=t;u;u=vf(u))w++;u=0;for(F=x;F;F=vf(F))u++;for(;0<w-u;)t=vf(t),w--;for(;0<u-w;)x=
vf(x),u--;for(;w--;){if(t===x||null!==x&&t===x.alternate)break b;t=vf(t);x=vf(x);}t=null;}else t=null;null!==k&&wf(g,h,k,t,false);null!==n&&null!==J&&wf(g,J,n,t,true);}}}a:{h=d?ue(d):window;k=h.nodeName&&h.nodeName.toLowerCase();if("select"===k||"input"===k&&"file"===h.type)var na=ve;else if(me(h))if(we)na=Fe;else {na=De;var xa=Ce;}else (k=h.nodeName)&&"input"===k.toLowerCase()&&("checkbox"===h.type||"radio"===h.type)&&(na=Ee);if(na&&(na=na(a,d))){ne(g,na,c,e);break a}xa&&xa(a,h,d);"focusout"===a&&(xa=h._wrapperState)&&
xa.controlled&&"number"===h.type&&cb(h,"number",h.value);}xa=d?ue(d):window;switch(a){case "focusin":if(me(xa)||"true"===xa.contentEditable)Qe=xa,Re=d,Se=null;break;case "focusout":Se=Re=Qe=null;break;case "mousedown":Te=true;break;case "contextmenu":case "mouseup":case "dragend":Te=false;Ue(g,c,e);break;case "selectionchange":if(Pe)break;case "keydown":case "keyup":Ue(g,c,e);}var $a;if(ae)b:{switch(a){case "compositionstart":var ba="onCompositionStart";break b;case "compositionend":ba="onCompositionEnd";
break b;case "compositionupdate":ba="onCompositionUpdate";break b}ba=void 0;}else ie?ge(a,c)&&(ba="onCompositionEnd"):"keydown"===a&&229===c.keyCode&&(ba="onCompositionStart");ba&&(de&&"ko"!==c.locale&&(ie||"onCompositionStart"!==ba?"onCompositionEnd"===ba&&ie&&($a=nd()):(kd=e,ld="value"in kd?kd.value:kd.textContent,ie=true)),xa=oe(d,ba),0<xa.length&&(ba=new Ld(ba,a,null,c,e),g.push({event:ba,listeners:xa}),$a?ba.data=$a:($a=he(c),null!==$a&&(ba.data=$a))));if($a=ce?je(a,c):ke(a,c))d=oe(d,"onBeforeInput"),
0<d.length&&(e=new Ld("onBeforeInput","beforeinput",null,c,e),g.push({event:e,listeners:d}),e.data=$a);}se(g,b);});}function tf(a,b,c){return {instance:a,listener:b,currentTarget:c}}function oe(a,b){for(var c=b+"Capture",d=[];null!==a;){var e=a,f=e.stateNode;5===e.tag&&null!==f&&(e=f,f=Kb(a,c),null!=f&&d.unshift(tf(a,f,e)),f=Kb(a,b),null!=f&&d.push(tf(a,f,e)));a=a.return;}return d}function vf(a){if(null===a)return null;do a=a.return;while(a&&5!==a.tag);return a?a:null}
function wf(a,b,c,d,e){for(var f=b._reactName,g=[];null!==c&&c!==d;){var h=c,k=h.alternate,l=h.stateNode;if(null!==k&&k===d)break;5===h.tag&&null!==l&&(h=l,e?(k=Kb(c,f),null!=k&&g.unshift(tf(c,k,h))):e||(k=Kb(c,f),null!=k&&g.push(tf(c,k,h))));c=c.return;}0!==g.length&&a.push({event:b,listeners:g});}var xf=/\r\n?/g,yf=/\u0000|\uFFFD/g;function zf(a){return ("string"===typeof a?a:""+a).replace(xf,"\n").replace(yf,"")}function Af(a,b,c){b=zf(b);if(zf(a)!==b&&c)throw Error(p(425));}function Bf(){}
var Cf=null,Df=null;function Ef(a,b){return "textarea"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}
var Ff="function"===typeof setTimeout?setTimeout:void 0,Gf="function"===typeof clearTimeout?clearTimeout:void 0,Hf="function"===typeof Promise?Promise:void 0,Jf="function"===typeof queueMicrotask?queueMicrotask:"undefined"!==typeof Hf?function(a){return Hf.resolve(null).then(a).catch(If)}:Ff;function If(a){setTimeout(function(){throw a;});}
function Kf(a,b){var c=b,d=0;do{var e=c.nextSibling;a.removeChild(c);if(e&&8===e.nodeType)if(c=e.data,"/$"===c){if(0===d){a.removeChild(e);bd(b);return}d--;}else "$"!==c&&"$?"!==c&&"$!"!==c||d++;c=e;}while(c);bd(b);}function Lf(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break;if(8===b){b=a.data;if("$"===b||"$!"===b||"$?"===b)break;if("/$"===b)return null}}return a}
function Mf(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if("$"===c||"$!"===c||"$?"===c){if(0===b)return a;b--;}else "/$"===c&&b++;}a=a.previousSibling;}return null}var Nf=Math.random().toString(36).slice(2),Of="__reactFiber$"+Nf,Pf="__reactProps$"+Nf,uf="__reactContainer$"+Nf,of="__reactEvents$"+Nf,Qf="__reactListeners$"+Nf,Rf="__reactHandles$"+Nf;
function Wc(a){var b=a[Of];if(b)return b;for(var c=a.parentNode;c;){if(b=c[uf]||c[Of]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=Mf(a);null!==a;){if(c=a[Of])return c;a=Mf(a);}return b}a=c;c=a.parentNode;}return null}function Cb(a){a=a[Of]||a[uf];return !a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function ue(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(p(33));}function Db(a){return a[Pf]||null}var Sf=[],Tf=-1;function Uf(a){return {current:a}}
function E(a){0>Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--);}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b;}var Vf={},H=Uf(Vf),Wf=Uf(false),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}
function Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H);}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c);}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||"Unknown",e));return A({},c,d)}
function cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return true}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c);}var eg=null,fg=false,gg=false;function hg(a){null===eg?eg=[a]:eg.push(a);}function ig(a){fg=true;hg(a);}
function jg(){if(!gg&&null!==eg){gg=true;var a=0,b=C;try{var c=eg;for(C=1;a<c.length;a++){var d=c[a];do d=d(!0);while(null!==d)}eg=null;fg=!1;}catch(e){throw null!==eg&&(eg=eg.slice(a+1)),ac(fc,jg),e;}finally{C=b,gg=false;}}return null}var kg=[],lg=0,mg=null,ng=0,og=[],pg=0,qg=null,rg=1,sg="";function tg(a,b){kg[lg++]=ng;kg[lg++]=mg;mg=a;ng=b;}
function ug(a,b,c){og[pg++]=rg;og[pg++]=sg;og[pg++]=qg;qg=a;var d=rg;a=sg;var e=32-oc(d)-1;d&=~(1<<e);c+=1;var f=32-oc(b)+e;if(30<f){var g=e-e%5;f=(d&(1<<g)-1).toString(32);d>>=g;e-=g;rg=1<<32-oc(b)+e|c<<e|d;sg=f+a;}else rg=1<<f|c<<e|d,sg=a;}function vg(a){null!==a.return&&(tg(a,1),ug(a,1,0));}function wg(a){for(;a===mg;)mg=kg[--lg],kg[lg]=null,ng=kg[--lg],kg[lg]=null;for(;a===qg;)qg=og[--pg],og[pg]=null,sg=og[--pg],og[pg]=null,rg=og[--pg],og[pg]=null;}var xg=null,yg=null,I=false,zg=null;
function Ag(a,b){var c=Bg(5,null,null,0);c.elementType="DELETED";c.stateNode=b;c.return=a;b=a.deletions;null===b?(a.deletions=[c],a.flags|=16):b.push(c);}
function Cg(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,xg=a,yg=Lf(b.firstChild),true):false;case 6:return b=""===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,xg=a,yg=null,true):false;case 13:return b=8!==b.nodeType?null:b,null!==b?(c=null!==qg?{id:rg,overflow:sg}:null,a.memoizedState={dehydrated:b,treeContext:c,retryLane:1073741824},c=Bg(18,null,null,0),c.stateNode=b,c.return=a,a.child=c,xg=a,yg=
null,true):false;default:return false}}function Dg(a){return 0!==(a.mode&1)&&0===(a.flags&128)}function Eg(a){if(I){var b=yg;if(b){var c=b;if(!Cg(a,b)){if(Dg(a))throw Error(p(418));b=Lf(c.nextSibling);var d=xg;b&&Cg(a,b)?Ag(d,c):(a.flags=a.flags&-4097|2,I=false,xg=a);}}else {if(Dg(a))throw Error(p(418));a.flags=a.flags&-4097|2;I=false;xg=a;}}}function Fg(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;xg=a;}
function Gg(a){if(a!==xg)return false;if(!I)return Fg(a),I=true,false;var b;(b=3!==a.tag)&&!(b=5!==a.tag)&&(b=a.type,b="head"!==b&&"body"!==b&&!Ef(a.type,a.memoizedProps));if(b&&(b=yg)){if(Dg(a))throw Hg(),Error(p(418));for(;b;)Ag(a,b),b=Lf(b.nextSibling);}Fg(a);if(13===a.tag){a=a.memoizedState;a=null!==a?a.dehydrated:null;if(!a)throw Error(p(317));a:{a=a.nextSibling;for(b=0;a;){if(8===a.nodeType){var c=a.data;if("/$"===c){if(0===b){yg=Lf(a.nextSibling);break a}b--;}else "$"!==c&&"$!"!==c&&"$?"!==c||b++;}a=a.nextSibling;}yg=
null;}}else yg=xg?Lf(a.stateNode.nextSibling):null;return true}function Hg(){for(var a=yg;a;)a=Lf(a.nextSibling);}function Ig(){yg=xg=null;I=false;}function Jg(a){null===zg?zg=[a]:zg.push(a);}var Kg=ua.ReactCurrentBatchConfig;
function Lg(a,b,c){a=c.ref;if(null!==a&&"function"!==typeof a&&"object"!==typeof a){if(c._owner){c=c._owner;if(c){if(1!==c.tag)throw Error(p(309));var d=c.stateNode;}if(!d)throw Error(p(147,a));var e=d,f=""+a;if(null!==b&&null!==b.ref&&"function"===typeof b.ref&&b.ref._stringRef===f)return b.ref;b=function(a){var b=e.refs;null===a?delete b[f]:b[f]=a;};b._stringRef=f;return b}if("string"!==typeof a)throw Error(p(284));if(!c._owner)throw Error(p(290,a));}return a}
function Mg(a,b){a=Object.prototype.toString.call(b);throw Error(p(31,"[object Object]"===a?"object with keys {"+Object.keys(b).join(", ")+"}":a));}function Ng(a){var b=a._init;return b(a._payload)}
function Og(a){function b(b,c){if(a){var d=b.deletions;null===d?(b.deletions=[c],b.flags|=16):d.push(c);}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b){a=Pg(a,b);a.index=0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return b.flags|=1048576,c;d=b.alternate;if(null!==d)return d=d.index,d<c?(b.flags|=2,c):d;b.flags|=2;return c}function g(b){a&&
null===b.alternate&&(b.flags|=2);return b}function h(a,b,c,d){if(null===b||6!==b.tag)return b=Qg(c,a.mode,d),b.return=a,b;b=e(b,c);b.return=a;return b}function k(a,b,c,d){var f=c.type;if(f===ya)return m(a,b,c.props.children,d,c.key);if(null!==b&&(b.elementType===f||"object"===typeof f&&null!==f&&f.$$typeof===Ha&&Ng(f)===b.type))return d=e(b,c.props),d.ref=Lg(a,b,c),d.return=a,d;d=Rg(c.type,c.key,c.props,null,a.mode,d);d.ref=Lg(a,b,c);d.return=a;return d}function l(a,b,c,d){if(null===b||4!==b.tag||
b.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!==c.implementation)return b=Sg(c,a.mode,d),b.return=a,b;b=e(b,c.children||[]);b.return=a;return b}function m(a,b,c,d,f){if(null===b||7!==b.tag)return b=Tg(c,a.mode,d,f),b.return=a,b;b=e(b,c);b.return=a;return b}function q(a,b,c){if("string"===typeof b&&""!==b||"number"===typeof b)return b=Qg(""+b,a.mode,c),b.return=a,b;if("object"===typeof b&&null!==b){switch(b.$$typeof){case va:return c=Rg(b.type,b.key,b.props,null,a.mode,c),
c.ref=Lg(a,null,b),c.return=a,c;case wa:return b=Sg(b,a.mode,c),b.return=a,b;case Ha:var d=b._init;return q(a,d(b._payload),c)}if(eb(b)||Ka(b))return b=Tg(b,a.mode,c,null),b.return=a,b;Mg(a,b);}return null}function r(a,b,c,d){var e=null!==b?b.key:null;if("string"===typeof c&&""!==c||"number"===typeof c)return null!==e?null:h(a,b,""+c,d);if("object"===typeof c&&null!==c){switch(c.$$typeof){case va:return c.key===e?k(a,b,c,d):null;case wa:return c.key===e?l(a,b,c,d):null;case Ha:return e=c._init,r(a,
b,e(c._payload),d)}if(eb(c)||Ka(c))return null!==e?null:m(a,b,c,d,null);Mg(a,c);}return null}function y(a,b,c,d,e){if("string"===typeof d&&""!==d||"number"===typeof d)return a=a.get(c)||null,h(b,a,""+d,e);if("object"===typeof d&&null!==d){switch(d.$$typeof){case va:return a=a.get(null===d.key?c:d.key)||null,k(b,a,d,e);case wa:return a=a.get(null===d.key?c:d.key)||null,l(b,a,d,e);case Ha:var f=d._init;return y(a,b,c,f(d._payload),e)}if(eb(d)||Ka(d))return a=a.get(c)||null,m(b,a,d,e,null);Mg(b,d);}return null}
function n(e,g,h,k){for(var l=null,m=null,u=g,w=g=0,x=null;null!==u&&w<h.length;w++){u.index>w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x;}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;w<h.length;w++)u=q(e,h[w],k),null!==u&&(g=f(u,g,w),null===m?l=u:m.sibling=u,m=u);I&&tg(e,w);return l}for(u=d(e,u);w<h.length;w++)x=y(u,e,w,h[w],k),null!==x&&(a&&null!==x.alternate&&u.delete(null===
x.key?w:x.key),g=f(x,g,w),null===m?l=x:m.sibling=x,m=x);a&&u.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function t(e,g,h,k){var l=Ka(h);if("function"!==typeof l)throw Error(p(150));h=l.call(h);if(null==h)throw Error(p(151));for(var u=l=null,m=g,w=g=0,x=null,n=h.next();null!==m&&!n.done;w++,n=h.next()){m.index>w?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x;}if(n.done)return c(e,
m),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){"object"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=
f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===Ha&&Ng(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=Lg(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling;}f.type===ya?(d=Tg(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Rg(f.type,f.key,f.props,null,a.mode,h),h.ref=Lg(a,d,f),h.return=a,a=h);}return g(a);case wa:a:{for(l=f.key;null!==
d;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else {c(a,d);break}else b(a,d);d=d.sibling;}d=Sg(f,a.mode,h);d.return=a;a=d;}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);Mg(a,f);}return "string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):
(c(a,d),d=Qg(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Ug=Og(true),Vg=Og(false),Wg=Uf(null),Xg=null,Yg=null,Zg=null;function $g(){Zg=Yg=Xg=null;}function ah(a){var b=Wg.current;E(Wg);a._currentValue=b;}function bh(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return;}}
function ch(a,b){Xg=a;Zg=Yg=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(dh=true),a.firstContext=null);}function eh(a){var b=a._currentValue;if(Zg!==a)if(a={context:a,memoizedValue:b,next:null},null===Yg){if(null===Xg)throw Error(p(308));Yg=a;Xg.dependencies={lanes:0,firstContext:a};}else Yg=Yg.next=a;return b}var fh=null;function gh(a){null===fh?fh=[a]:fh.push(a);}
function hh(a,b,c,d){var e=b.interleaved;null===e?(c.next=c,gh(b)):(c.next=e.next,e.next=c);b.interleaved=c;return ih(a,d)}function ih(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}var jh=false;function kh(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null};}
function lh(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects});}function mh(a,b){return {eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}
function nh(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(K&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return ih(a,c)}e=d.interleaved;null===e?(b.next=b,gh(d)):(b.next=e.next,e.next=b);d.interleaved=b;return ih(a,c)}function oh(a,b,c){b=b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c);}}
function ph(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next;}while(null!==c);null===f?e=f=b:f=f.next=b;}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=
b;c.lastBaseUpdate=b;}
function qh(a,b,c,d){var e=a.updateQueue;jh=false;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,l=k.next;k.next=null;null===g?f=l:g.next=l;g=k;var m=a.alternate;null!==m&&(m=m.updateQueue,h=m.lastBaseUpdate,h!==g&&(null===h?m.firstBaseUpdate=l:h.next=l,m.lastBaseUpdate=k));}if(null!==f){var q=e.baseState;g=0;m=l=k=null;h=f;do{var r=h.lane,y=h.eventTime;if((d&r)===r){null!==m&&(m=m.next={eventTime:y,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,
next:null});a:{var n=a,t=h;r=b;y=c;switch(t.tag){case 1:n=t.payload;if("function"===typeof n){q=n.call(y,q,r);break a}q=n;break a;case 3:n.flags=n.flags&-65537|128;case 0:n=t.payload;r="function"===typeof n?n.call(y,q,r):n;if(null===r||void 0===r)break a;q=A({},q,r);break a;case 2:jh=true;}}null!==h.callback&&0!==h.lane&&(a.flags|=64,r=e.effects,null===r?e.effects=[h]:r.push(h));}else y={eventTime:y,lane:r,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===m?(l=m=y,k=q):m=m.next=y,g|=r;
h=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else r=h,h=r.next,r.next=null,e.lastBaseUpdate=r,e.shared.pending=null;}while(1);null===m&&(k=q);e.baseState=k;e.firstBaseUpdate=l;e.lastBaseUpdate=m;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);rh|=g;a.lanes=g;a.memoizedState=q;}}
function sh(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;b<a.length;b++){var d=a[b],e=d.callback;if(null!==e){d.callback=null;d=c;if("function"!==typeof e)throw Error(p(191,e));e.call(d);}}}var th={},uh=Uf(th),vh=Uf(th),wh=Uf(th);function xh(a){if(a===th)throw Error(p(174));return a}
function yh(a,b){G(wh,b);G(vh,a);G(uh,th);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a);}E(uh);G(uh,b);}function zh(){E(uh);E(vh);E(wh);}function Ah(a){xh(wh.current);var b=xh(uh.current);var c=lb(b,a.type);b!==c&&(G(vh,a),G(uh,c));}function Bh(a){vh.current===a&&(E(uh),E(vh));}var L=Uf(0);
function Ch(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||"$?"===c.data||"$!"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}return null}var Dh=[];
function Eh(){for(var a=0;a<Dh.length;a++)Dh[a]._workInProgressVersionPrimary=null;Dh.length=0;}var Fh=ua.ReactCurrentDispatcher,Gh=ua.ReactCurrentBatchConfig,Hh=0,M=null,N=null,O=null,Ih=false,Jh=false,Kh=0,Lh=0;function P(){throw Error(p(321));}function Mh(a,b){if(null===b)return false;for(var c=0;c<b.length&&c<a.length;c++)if(!He(a[c],b[c]))return false;return true}
function Nh(a,b,c,d,e,f){Hh=f;M=b;b.memoizedState=null;b.updateQueue=null;b.lanes=0;Fh.current=null===a||null===a.memoizedState?Oh:Ph;a=c(d,e);if(Jh){f=0;do{Jh=false;Kh=0;if(25<=f)throw Error(p(301));f+=1;O=N=null;b.updateQueue=null;Fh.current=Qh;a=c(d,e);}while(Jh)}Fh.current=Rh;b=null!==N&&null!==N.next;Hh=0;O=N=M=null;Ih=false;if(b)throw Error(p(300));return a}function Sh(){var a=0!==Kh;Kh=0;return a}
function Th(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===O?M.memoizedState=O=a:O=O.next=a;return O}function Uh(){if(null===N){var a=M.alternate;a=null!==a?a.memoizedState:null;}else a=N.next;var b=null===O?M.memoizedState:O.next;if(null!==b)O=b,N=a;else {if(null===a)throw Error(p(310));N=a;a={memoizedState:N.memoizedState,baseState:N.baseState,baseQueue:N.baseQueue,queue:N.queue,next:null};null===O?M.memoizedState=O=a:O=O.next=a;}return O}
function Vh(a,b){return "function"===typeof b?b(a):b}
function Wh(a){var b=Uh(),c=b.queue;if(null===c)throw Error(p(311));c.lastRenderedReducer=a;var d=N,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g;}d.baseQueue=e=f;c.pending=null;}if(null!==e){f=e.next;d=d.baseState;var h=g=null,k=null,l=f;do{var m=l.lane;if((Hh&m)===m)null!==k&&(k=k.next={lane:0,action:l.action,hasEagerState:l.hasEagerState,eagerState:l.eagerState,next:null}),d=l.hasEagerState?l.eagerState:a(d,l.action);else {var q={lane:m,action:l.action,hasEagerState:l.hasEagerState,
eagerState:l.eagerState,next:null};null===k?(h=k=q,g=d):k=k.next=q;M.lanes|=m;rh|=m;}l=l.next;}while(null!==l&&l!==f);null===k?g=d:k.next=h;He(d,b.memoizedState)||(dh=true);b.memoizedState=d;b.baseState=g;b.baseQueue=k;c.lastRenderedState=d;}a=c.interleaved;if(null!==a){e=a;do f=e.lane,M.lanes|=f,rh|=f,e=e.next;while(e!==a)}else null===e&&(c.lanes=0);return [b.memoizedState,c.dispatch]}
function Xh(a){var b=Uh(),c=b.queue;if(null===c)throw Error(p(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);He(f,b.memoizedState)||(dh=true);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f;}return [f,d]}function Yh(){}
function Zh(a,b){var c=M,d=Uh(),e=b(),f=!He(d.memoizedState,e);f&&(d.memoizedState=e,dh=true);d=d.queue;$h(ai.bind(null,c,d,a),[a]);if(d.getSnapshot!==b||f||null!==O&&O.memoizedState.tag&1){c.flags|=2048;bi(9,ci.bind(null,c,d,e,b),void 0,null);if(null===Q)throw Error(p(349));0!==(Hh&30)||di(c,b,e);}return e}function di(a,b,c){a.flags|=16384;a={getSnapshot:b,value:c};b=M.updateQueue;null===b?(b={lastEffect:null,stores:null},M.updateQueue=b,b.stores=[a]):(c=b.stores,null===c?b.stores=[a]:c.push(a));}
function ci(a,b,c,d){b.value=c;b.getSnapshot=d;ei(b)&&fi(a);}function ai(a,b,c){return c(function(){ei(b)&&fi(a);})}function ei(a){var b=a.getSnapshot;a=a.value;try{var c=b();return !He(a,c)}catch(d){return true}}function fi(a){var b=ih(a,1);null!==b&&gi(b,a,1,-1);}
function hi(a){var b=Th();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Vh,lastRenderedState:a};b.queue=a;a=a.dispatch=ii.bind(null,M,a);return [b.memoizedState,a]}
function bi(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};b=M.updateQueue;null===b?(b={lastEffect:null,stores:null},M.updateQueue=b,b.lastEffect=a.next=a):(c=b.lastEffect,null===c?b.lastEffect=a.next=a:(d=c.next,c.next=a,a.next=d,b.lastEffect=a));return a}function ji(){return Uh().memoizedState}function ki(a,b,c,d){var e=Th();M.flags|=a;e.memoizedState=bi(1|b,c,void 0,void 0===d?null:d);}
function li(a,b,c,d){var e=Uh();d=void 0===d?null:d;var f=void 0;if(null!==N){var g=N.memoizedState;f=g.destroy;if(null!==d&&Mh(d,g.deps)){e.memoizedState=bi(b,c,f,d);return}}M.flags|=a;e.memoizedState=bi(1|b,c,f,d);}function mi(a,b){return ki(8390656,8,a,b)}function $h(a,b){return li(2048,8,a,b)}function ni(a,b){return li(4,2,a,b)}function oi(a,b){return li(4,4,a,b)}
function pi(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null);};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null;}}function qi(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return li(4,4,pi.bind(null,b,a),c)}function ri(){}function si(a,b){var c=Uh();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Mh(b,d[1]))return d[0];c.memoizedState=[a,b];return a}
function ti(a,b){var c=Uh();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Mh(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a}function ui(a,b,c){if(0===(Hh&21))return a.baseState&&(a.baseState=false,dh=true),a.memoizedState=c;He(c,b)||(c=yc(),M.lanes|=c,rh|=c,a.baseState=true);return b}function vi(a,b){var c=C;C=0!==c&&4>c?c:4;a(true);var d=Gh.transition;Gh.transition={};try{a(!1),b();}finally{C=c,Gh.transition=d;}}function wi(){return Uh().memoizedState}
function xi(a,b,c){var d=yi(a);c={lane:d,action:c,hasEagerState:false,eagerState:null,next:null};if(zi(a))Ai(b,c);else if(c=hh(a,b,c,d),null!==c){var e=R();gi(c,a,d,e);Bi(c,b,d);}}
function ii(a,b,c){var d=yi(a),e={lane:d,action:c,hasEagerState:false,eagerState:null,next:null};if(zi(a))Ai(b,e);else {var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,gh(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=hh(a,b,e,d);null!==c&&(e=R(),gi(c,a,d,e),Bi(c,b,d));}}
function zi(a){var b=a.alternate;return a===M||null!==b&&b===M}function Ai(a,b){Jh=Ih=true;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b;}function Bi(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c);}}
var Rh={readContext:eh,useCallback:P,useContext:P,useEffect:P,useImperativeHandle:P,useInsertionEffect:P,useLayoutEffect:P,useMemo:P,useReducer:P,useRef:P,useState:P,useDebugValue:P,useDeferredValue:P,useTransition:P,useMutableSource:P,useSyncExternalStore:P,useId:P,unstable_isNewReconciler:false},Oh={readContext:eh,useCallback:function(a,b){Th().memoizedState=[a,void 0===b?null:b];return a},useContext:eh,useEffect:mi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ki(4194308,
4,pi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ki(4194308,4,a,b)},useInsertionEffect:function(a,b){return ki(4,2,a,b)},useMemo:function(a,b){var c=Th();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Th();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=xi.bind(null,M,a);return [d.memoizedState,a]},useRef:function(a){var b=
Th();a={current:a};return b.memoizedState=a},useState:hi,useDebugValue:ri,useDeferredValue:function(a){return Th().memoizedState=a},useTransition:function(){var a=hi(false),b=a[0];a=vi.bind(null,a[1]);Th().memoizedState=a;return [b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=M,e=Th();if(I){if(void 0===c)throw Error(p(407));c=c();}else {c=b();if(null===Q)throw Error(p(349));0!==(Hh&30)||di(d,b,c);}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;mi(ai.bind(null,d,
f,a),[a]);d.flags|=2048;bi(9,ci.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Th(),b=Q.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=Kh++;0<c&&(b+="H"+c.toString(32));b+=":";}else c=Lh++,b=":"+b+"r"+c.toString(32)+":";return a.memoizedState=b},unstable_isNewReconciler:false},Ph={readContext:eh,useCallback:si,useContext:eh,useEffect:$h,useImperativeHandle:qi,useInsertionEffect:ni,useLayoutEffect:oi,useMemo:ti,useReducer:Wh,useRef:ji,useState:function(){return Wh(Vh)},
useDebugValue:ri,useDeferredValue:function(a){var b=Uh();return ui(b,N.memoizedState,a)},useTransition:function(){var a=Wh(Vh)[0],b=Uh().memoizedState;return [a,b]},useMutableSource:Yh,useSyncExternalStore:Zh,useId:wi,unstable_isNewReconciler:false},Qh={readContext:eh,useCallback:si,useContext:eh,useEffect:$h,useImperativeHandle:qi,useInsertionEffect:ni,useLayoutEffect:oi,useMemo:ti,useReducer:Xh,useRef:ji,useState:function(){return Xh(Vh)},useDebugValue:ri,useDeferredValue:function(a){var b=Uh();return null===
N?b.memoizedState=a:ui(b,N.memoizedState,a)},useTransition:function(){var a=Xh(Vh)[0],b=Uh().memoizedState;return [a,b]},useMutableSource:Yh,useSyncExternalStore:Zh,useId:wi,unstable_isNewReconciler:false};function Ci(a,b){if(a&&a.defaultProps){b=A({},b);a=a.defaultProps;for(var c in a) void 0===b[c]&&(b[c]=a[c]);return b}return b}function Di(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:A({},b,c);a.memoizedState=c;0===a.lanes&&(a.updateQueue.baseState=c);}
var Ei={isMounted:function(a){return (a=a._reactInternals)?Vb(a)===a:false},enqueueSetState:function(a,b,c){a=a._reactInternals;var d=R(),e=yi(a),f=mh(d,e);f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=nh(a,f,e);null!==b&&(gi(b,a,e,d),oh(b,a,e));},enqueueReplaceState:function(a,b,c){a=a._reactInternals;var d=R(),e=yi(a),f=mh(d,e);f.tag=1;f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=nh(a,f,e);null!==b&&(gi(b,a,e,d),oh(b,a,e));},enqueueForceUpdate:function(a,b){a=a._reactInternals;var c=R(),d=
yi(a),e=mh(c,d);e.tag=2;void 0!==b&&null!==b&&(e.callback=b);b=nh(a,e,d);null!==b&&(gi(b,a,d,c),oh(b,a,d));}};function Fi(a,b,c,d,e,f,g){a=a.stateNode;return "function"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):b.prototype&&b.prototype.isPureReactComponent?!Ie(c,d)||!Ie(e,f):true}
function Gi(a,b,c){var d=false,e=Vf;var f=b.contextType;"object"===typeof f&&null!==f?f=eh(f):(e=Zf(b)?Xf:H.current,d=b.contextTypes,f=(d=null!==d&&void 0!==d)?Yf(a,e):Vf);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=Ei;a.stateNode=b;b._reactInternals=a;d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f);return b}
function Hi(a,b,c,d){a=b.state;"function"===typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d);"function"===typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d);b.state!==a&&Ei.enqueueReplaceState(b,b.state,null);}
function Ii(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs={};kh(a);var f=b.contextType;"object"===typeof f&&null!==f?e.context=eh(f):(f=Zf(b)?Xf:H.current,e.context=Yf(a,f));e.state=a.memoizedState;f=b.getDerivedStateFromProps;"function"===typeof f&&(Di(a,b,f,c),e.state=a.memoizedState);"function"===typeof b.getDerivedStateFromProps||"function"===typeof e.getSnapshotBeforeUpdate||"function"!==typeof e.UNSAFE_componentWillMount&&"function"!==typeof e.componentWillMount||(b=e.state,
"function"===typeof e.componentWillMount&&e.componentWillMount(),"function"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&Ei.enqueueReplaceState(e,e.state,null),qh(a,c,e,d),e.state=a.memoizedState);"function"===typeof e.componentDidMount&&(a.flags|=4194308);}function Ji(a,b){try{var c="",d=b;do c+=Pa(d),d=d.return;while(d);var e=c;}catch(f){e="\nError generating stack: "+f.message+"\n"+f.stack;}return {value:a,source:b,stack:e,digest:null}}
function Ki(a,b,c){return {value:a,source:null,stack:null!=c?c:null,digest:null!=b?b:null}}function Li(a,b){try{console.error(b.value);}catch(c){setTimeout(function(){throw c;});}}var Mi="function"===typeof WeakMap?WeakMap:Map;function Ni(a,b,c){c=mh(-1,c);c.tag=3;c.payload={element:null};var d=b.value;c.callback=function(){Oi||(Oi=true,Pi=d);Li(a,b);};return c}
function Qi(a,b,c){c=mh(-1,c);c.tag=3;var d=a.type.getDerivedStateFromError;if("function"===typeof d){var e=b.value;c.payload=function(){return d(e)};c.callback=function(){Li(a,b);};}var f=a.stateNode;null!==f&&"function"===typeof f.componentDidCatch&&(c.callback=function(){Li(a,b);"function"!==typeof d&&(null===Ri?Ri=new Set([this]):Ri.add(this));var c=b.stack;this.componentDidCatch(b.value,{componentStack:null!==c?c:""});});return c}
function Si(a,b,c){var d=a.pingCache;if(null===d){d=a.pingCache=new Mi;var e=new Set;d.set(b,e);}else e=d.get(b),void 0===e&&(e=new Set,d.set(b,e));e.has(c)||(e.add(c),a=Ti.bind(null,a,b,c),b.then(a,a));}function Ui(a){do{var b;if(b=13===a.tag)b=a.memoizedState,b=null!==b?null!==b.dehydrated?true:false:true;if(b)return a;a=a.return;}while(null!==a);return null}
function Vi(a,b,c,d,e){if(0===(a.mode&1))return a===b?a.flags|=65536:(a.flags|=128,c.flags|=131072,c.flags&=-52805,1===c.tag&&(null===c.alternate?c.tag=17:(b=mh(-1,1),b.tag=2,nh(c,b,1))),c.lanes|=1),a;a.flags|=65536;a.lanes=e;return a}var Wi=ua.ReactCurrentOwner,dh=false;function Xi(a,b,c,d){b.child=null===a?Vg(b,null,c,d):Ug(b,a.child,c,d);}
function Yi(a,b,c,d,e){c=c.render;var f=b.ref;ch(b,e);d=Nh(a,b,c,d,f,e);c=Sh();if(null!==a&&!dh)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Zi(a,b,e);I&&c&&vg(b);b.flags|=1;Xi(a,b,d,e);return b.child}
function $i(a,b,c,d,e){if(null===a){var f=c.type;if("function"===typeof f&&!aj(f)&&void 0===f.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=f,bj(a,b,f,d,e);a=Rg(c.type,null,d,b,b.mode,e);a.ref=b.ref;a.return=b;return b.child=a}f=a.child;if(0===(a.lanes&e)){var g=f.memoizedProps;c=c.compare;c=null!==c?c:Ie;if(c(g,d)&&a.ref===b.ref)return Zi(a,b,e)}b.flags|=1;a=Pg(f,d);a.ref=b.ref;a.return=b;return b.child=a}
function bj(a,b,c,d,e){if(null!==a){var f=a.memoizedProps;if(Ie(f,d)&&a.ref===b.ref)if(dh=false,b.pendingProps=d=f,0!==(a.lanes&e))0!==(a.flags&131072)&&(dh=true);else return b.lanes=a.lanes,Zi(a,b,e)}return cj(a,b,c,d,e)}
function dj(a,b,c){var d=b.pendingProps,e=d.children,f=null!==a?a.memoizedState:null;if("hidden"===d.mode)if(0===(b.mode&1))b.memoizedState={baseLanes:0,cachePool:null,transitions:null},G(ej,fj),fj|=c;else {if(0===(c&1073741824))return a=null!==f?f.baseLanes|c:c,b.lanes=b.childLanes=1073741824,b.memoizedState={baseLanes:a,cachePool:null,transitions:null},b.updateQueue=null,G(ej,fj),fj|=a,null;b.memoizedState={baseLanes:0,cachePool:null,transitions:null};d=null!==f?f.baseLanes:c;G(ej,fj);fj|=d;}else null!==
f?(d=f.baseLanes|c,b.memoizedState=null):d=c,G(ej,fj),fj|=d;Xi(a,b,e,c);return b.child}function gj(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.flags|=512,b.flags|=2097152;}function cj(a,b,c,d,e){var f=Zf(c)?Xf:H.current;f=Yf(b,f);ch(b,e);c=Nh(a,b,c,d,f,e);d=Sh();if(null!==a&&!dh)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,Zi(a,b,e);I&&d&&vg(b);b.flags|=1;Xi(a,b,c,e);return b.child}
function hj(a,b,c,d,e){if(Zf(c)){var f=true;cg(b);}else f=false;ch(b,e);if(null===b.stateNode)ij(a,b),Gi(b,c,d),Ii(b,c,d,e),d=true;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;"object"===typeof l&&null!==l?l=eh(l):(l=Zf(c)?Xf:H.current,l=Yf(b,l));var m=c.getDerivedStateFromProps,q="function"===typeof m||"function"===typeof g.getSnapshotBeforeUpdate;q||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||
(h!==d||k!==l)&&Hi(b,g,d,l);jh=false;var r=b.memoizedState;g.state=r;qh(b,d,g,e);k=b.memoizedState;h!==d||r!==k||Wf.current||jh?("function"===typeof m&&(Di(b,c,m,d),k=b.memoizedState),(h=jh||Fi(b,c,h,d,r,k,l))?(q||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),"function"===typeof g.componentDidMount&&(b.flags|=4194308)):
("function"===typeof g.componentDidMount&&(b.flags|=4194308),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):("function"===typeof g.componentDidMount&&(b.flags|=4194308),d=false);}else {g=b.stateNode;lh(a,b);h=b.memoizedProps;l=b.type===b.elementType?h:Ci(b.type,h);g.props=l;q=b.pendingProps;r=g.context;k=c.contextType;"object"===typeof k&&null!==k?k=eh(k):(k=Zf(c)?Xf:H.current,k=Yf(b,k));var y=c.getDerivedStateFromProps;(m="function"===typeof y||"function"===typeof g.getSnapshotBeforeUpdate)||
"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==q||r!==k)&&Hi(b,g,d,k);jh=false;r=b.memoizedState;g.state=r;qh(b,d,g,e);var n=b.memoizedState;h!==q||r!==n||Wf.current||jh?("function"===typeof y&&(Di(b,c,y,d),n=b.memoizedState),(l=jh||Fi(b,c,l,d,r,n,k)||false)?(m||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||("function"===typeof g.componentWillUpdate&&g.componentWillUpdate(d,n,k),"function"===typeof g.UNSAFE_componentWillUpdate&&
g.UNSAFE_componentWillUpdate(d,n,k)),"function"===typeof g.componentDidUpdate&&(b.flags|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.flags|=1024)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),b.memoizedProps=d,b.memoizedState=n),g.props=d,g.state=n,g.context=k,d=l):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===
a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),d=false);}return jj(a,b,c,d,f,e)}
function jj(a,b,c,d,e,f){gj(a,b);var g=0!==(b.flags&128);if(!d&&!g)return e&&dg(b,c,false),Zi(a,b,f);d=b.stateNode;Wi.current=b;var h=g&&"function"!==typeof c.getDerivedStateFromError?null:d.render();b.flags|=1;null!==a&&g?(b.child=Ug(b,a.child,null,f),b.child=Ug(b,null,h,f)):Xi(a,b,h,f);b.memoizedState=d.state;e&&dg(b,c,true);return b.child}function kj(a){var b=a.stateNode;b.pendingContext?ag(a,b.pendingContext,b.pendingContext!==b.context):b.context&&ag(a,b.context,false);yh(a,b.containerInfo);}
function lj(a,b,c,d,e){Ig();Jg(e);b.flags|=256;Xi(a,b,c,d);return b.child}var mj={dehydrated:null,treeContext:null,retryLane:0};function nj(a){return {baseLanes:a,cachePool:null,transitions:null}}
function oj(a,b,c){var d=b.pendingProps,e=L.current,f=false,g=0!==(b.flags&128),h;(h=g)||(h=null!==a&&null===a.memoizedState?false:0!==(e&2));if(h)f=true,b.flags&=-129;else if(null===a||null!==a.memoizedState)e|=1;G(L,e&1);if(null===a){Eg(b);a=b.memoizedState;if(null!==a&&(a=a.dehydrated,null!==a))return 0===(b.mode&1)?b.lanes=1:"$!"===a.data?b.lanes=8:b.lanes=1073741824,null;g=d.children;a=d.fallback;return f?(d=b.mode,f=b.child,g={mode:"hidden",children:g},0===(d&1)&&null!==f?(f.childLanes=0,f.pendingProps=
g):f=pj(g,d,0,null),a=Tg(a,d,c,null),f.return=b,a.return=b,f.sibling=a,b.child=f,b.child.memoizedState=nj(c),b.memoizedState=mj,a):qj(b,g)}e=a.memoizedState;if(null!==e&&(h=e.dehydrated,null!==h))return rj(a,b,g,d,h,e,c);if(f){f=d.fallback;g=b.mode;e=a.child;h=e.sibling;var k={mode:"hidden",children:d.children};0===(g&1)&&b.child!==e?(d=b.child,d.childLanes=0,d.pendingProps=k,b.deletions=null):(d=Pg(e,k),d.subtreeFlags=e.subtreeFlags&14680064);null!==h?f=Pg(h,f):(f=Tg(f,g,c,null),f.flags|=2);f.return=
b;d.return=b;d.sibling=f;b.child=d;d=f;f=b.child;g=a.child.memoizedState;g=null===g?nj(c):{baseLanes:g.baseLanes|c,cachePool:null,transitions:g.transitions};f.memoizedState=g;f.childLanes=a.childLanes&~c;b.memoizedState=mj;return d}f=a.child;a=f.sibling;d=Pg(f,{mode:"visible",children:d.children});0===(b.mode&1)&&(d.lanes=c);d.return=b;d.sibling=null;null!==a&&(c=b.deletions,null===c?(b.deletions=[a],b.flags|=16):c.push(a));b.child=d;b.memoizedState=null;return d}
function qj(a,b){b=pj({mode:"visible",children:b},a.mode,0,null);b.return=a;return a.child=b}function sj(a,b,c,d){null!==d&&Jg(d);Ug(b,a.child,null,c);a=qj(b,b.pendingProps.children);a.flags|=2;b.memoizedState=null;return a}
function rj(a,b,c,d,e,f,g){if(c){if(b.flags&256)return b.flags&=-257,d=Ki(Error(p(422))),sj(a,b,g,d);if(null!==b.memoizedState)return b.child=a.child,b.flags|=128,null;f=d.fallback;e=b.mode;d=pj({mode:"visible",children:d.children},e,0,null);f=Tg(f,e,g,null);f.flags|=2;d.return=b;f.return=b;d.sibling=f;b.child=d;0!==(b.mode&1)&&Ug(b,a.child,null,g);b.child.memoizedState=nj(g);b.memoizedState=mj;return f}if(0===(b.mode&1))return sj(a,b,g,null);if("$!"===e.data){d=e.nextSibling&&e.nextSibling.dataset;
if(d)var h=d.dgst;d=h;f=Error(p(419));d=Ki(f,d,void 0);return sj(a,b,g,d)}h=0!==(g&a.childLanes);if(dh||h){d=Q;if(null!==d){switch(g&-g){case 4:e=2;break;case 16:e=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:e=32;break;case 536870912:e=268435456;break;default:e=0;}e=0!==(e&(d.suspendedLanes|g))?0:e;
0!==e&&e!==f.retryLane&&(f.retryLane=e,ih(a,e),gi(d,a,e,-1));}tj();d=Ki(Error(p(421)));return sj(a,b,g,d)}if("$?"===e.data)return b.flags|=128,b.child=a.child,b=uj.bind(null,a),e._reactRetry=b,null;a=f.treeContext;yg=Lf(e.nextSibling);xg=b;I=true;zg=null;null!==a&&(og[pg++]=rg,og[pg++]=sg,og[pg++]=qg,rg=a.id,sg=a.overflow,qg=b);b=qj(b,d.children);b.flags|=4096;return b}function vj(a,b,c){a.lanes|=b;var d=a.alternate;null!==d&&(d.lanes|=b);bh(a.return,b,c);}
function wj(a,b,c,d,e){var f=a.memoizedState;null===f?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailMode:e}:(f.isBackwards=b,f.rendering=null,f.renderingStartTime=0,f.last=d,f.tail=c,f.tailMode=e);}
function xj(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;Xi(a,b,d.children,c);d=L.current;if(0!==(d&2))d=d&1|2,b.flags|=128;else {if(null!==a&&0!==(a.flags&128))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&vj(a,c,b);else if(19===a.tag)vj(a,c,b);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return;}a.sibling.return=a.return;a=a.sibling;}d&=1;}G(L,d);if(0===(b.mode&1))b.memoizedState=
null;else switch(e){case "forwards":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===Ch(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);wj(b,false,e,c,f);break;case "backwards":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===Ch(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a;}wj(b,true,c,null,f);break;case "together":wj(b,false,null,null,void 0);break;default:b.memoizedState=null;}return b.child}
function ij(a,b){0===(b.mode&1)&&null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);}function Zi(a,b,c){null!==a&&(b.dependencies=a.dependencies);rh|=b.lanes;if(0===(c&b.childLanes))return null;if(null!==a&&b.child!==a.child)throw Error(p(153));if(null!==b.child){a=b.child;c=Pg(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=Pg(a,a.pendingProps),c.return=b;c.sibling=null;}return b.child}
function yj(a,b,c){switch(b.tag){case 3:kj(b);Ig();break;case 5:Ah(b);break;case 1:Zf(b.type)&&cg(b);break;case 4:yh(b,b.stateNode.containerInfo);break;case 10:var d=b.type._context,e=b.memoizedProps.value;G(Wg,d._currentValue);d._currentValue=e;break;case 13:d=b.memoizedState;if(null!==d){if(null!==d.dehydrated)return G(L,L.current&1),b.flags|=128,null;if(0!==(c&b.child.childLanes))return oj(a,b,c);G(L,L.current&1);a=Zi(a,b,c);return null!==a?a.sibling:null}G(L,L.current&1);break;case 19:d=0!==(c&
b.childLanes);if(0!==(a.flags&128)){if(d)return xj(a,b,c);b.flags|=128;}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);G(L,L.current);if(d)break;else return null;case 22:case 23:return b.lanes=0,dj(a,b,c)}return Zi(a,b,c)}var zj,Aj,Bj,Cj;
zj=function(a,b){for(var c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return;}c.sibling.return=c.return;c=c.sibling;}};Aj=function(){};
Bj=function(a,b,c,d){var e=a.memoizedProps;if(e!==d){a=b.stateNode;xh(uh.current);var f=null;switch(c){case "input":e=Ya(a,e);d=Ya(a,d);f=[];break;case "select":e=A({},e,{value:void 0});d=A({},d,{value:void 0});f=[];break;case "textarea":e=gb(a,e);d=gb(a,d);f=[];break;default:"function"!==typeof e.onClick&&"function"===typeof d.onClick&&(a.onclick=Bf);}ub(c,d);var g;c=null;for(l in e)if(!d.hasOwnProperty(l)&&e.hasOwnProperty(l)&&null!=e[l])if("style"===l){var h=e[l];for(g in h)h.hasOwnProperty(g)&&
(c||(c={}),c[g]="");}else "dangerouslySetInnerHTML"!==l&&"children"!==l&&"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&"autoFocus"!==l&&(ea.hasOwnProperty(l)?f||(f=[]):(f=f||[]).push(l,null));for(l in d){var k=d[l];h=null!=e?e[l]:void 0;if(d.hasOwnProperty(l)&&k!==h&&(null!=k||null!=h))if("style"===l)if(h){for(g in h)!h.hasOwnProperty(g)||k&&k.hasOwnProperty(g)||(c||(c={}),c[g]="");for(g in k)k.hasOwnProperty(g)&&h[g]!==k[g]&&(c||(c={}),c[g]=k[g]);}else c||(f||(f=[]),f.push(l,
c)),c=k;else "dangerouslySetInnerHTML"===l?(k=k?k.__html:void 0,h=h?h.__html:void 0,null!=k&&h!==k&&(f=f||[]).push(l,k)):"children"===l?"string"!==typeof k&&"number"!==typeof k||(f=f||[]).push(l,""+k):"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&(ea.hasOwnProperty(l)?(null!=k&&"onScroll"===l&&D("scroll",a),f||h===k||(f=[])):(f=f||[]).push(l,k));}c&&(f=f||[]).push("style",c);var l=f;if(b.updateQueue=l)b.flags|=4;}};Cj=function(a,b,c,d){c!==d&&(b.flags|=4);};
function Dj(a,b){if(!I)switch(a.tailMode){case "hidden":b=a.tail;for(var c=null;null!==b;)null!==b.alternate&&(c=b),b=b.sibling;null===c?a.tail=null:c.sibling=null;break;case "collapsed":c=a.tail;for(var d=null;null!==c;)null!==c.alternate&&(d=c),c=c.sibling;null===d?b||null===a.tail?a.tail=null:a.tail.sibling=null:d.sibling=null;}}
function S(a){var b=null!==a.alternate&&a.alternate.child===a.child,c=0,d=0;if(b)for(var e=a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags&14680064,d|=e.flags&14680064,e.return=a,e=e.sibling;else for(e=a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags,d|=e.flags,e.return=a,e=e.sibling;a.subtreeFlags|=d;a.childLanes=c;return b}
function Ej(a,b,c){var d=b.pendingProps;wg(b);switch(b.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return S(b),null;case 1:return Zf(b.type)&&$f(),S(b),null;case 3:d=b.stateNode;zh();E(Wf);E(H);Eh();d.pendingContext&&(d.context=d.pendingContext,d.pendingContext=null);if(null===a||null===a.child)Gg(b)?b.flags|=4:null===a||a.memoizedState.isDehydrated&&0===(b.flags&256)||(b.flags|=1024,null!==zg&&(Fj(zg),zg=null));Aj(a,b);S(b);return null;case 5:Bh(b);var e=xh(wh.current);
c=b.type;if(null!==a&&null!=b.stateNode)Bj(a,b,c,d,e),a.ref!==b.ref&&(b.flags|=512,b.flags|=2097152);else {if(!d){if(null===b.stateNode)throw Error(p(166));S(b);return null}a=xh(uh.current);if(Gg(b)){d=b.stateNode;c=b.type;var f=b.memoizedProps;d[Of]=b;d[Pf]=f;a=0!==(b.mode&1);switch(c){case "dialog":D("cancel",d);D("close",d);break;case "iframe":case "object":case "embed":D("load",d);break;case "video":case "audio":for(e=0;e<lf.length;e++)D(lf[e],d);break;case "source":D("error",d);break;case "img":case "image":case "link":D("error",
d);D("load",d);break;case "details":D("toggle",d);break;case "input":Za(d,f);D("invalid",d);break;case "select":d._wrapperState={wasMultiple:!!f.multiple};D("invalid",d);break;case "textarea":hb(d,f),D("invalid",d);}ub(c,f);e=null;for(var g in f)if(f.hasOwnProperty(g)){var h=f[g];"children"===g?"string"===typeof h?d.textContent!==h&&(true!==f.suppressHydrationWarning&&Af(d.textContent,h,a),e=["children",h]):"number"===typeof h&&d.textContent!==""+h&&(true!==f.suppressHydrationWarning&&Af(d.textContent,
h,a),e=["children",""+h]):ea.hasOwnProperty(g)&&null!=h&&"onScroll"===g&&D("scroll",d);}switch(c){case "input":Va(d);db(d,f,true);break;case "textarea":Va(d);jb(d);break;case "select":case "option":break;default:"function"===typeof f.onClick&&(d.onclick=Bf);}d=e;b.updateQueue=d;null!==d&&(b.flags|=4);}else {g=9===e.nodeType?e:e.ownerDocument;"http://www.w3.org/1999/xhtml"===a&&(a=kb(c));"http://www.w3.org/1999/xhtml"===a?"script"===c?(a=g.createElement("div"),a.innerHTML="<script>\x3c/script>",a=a.removeChild(a.firstChild)):
"string"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),"select"===c&&(g=a,d.multiple?g.multiple=true:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;zj(a,b,false,false);b.stateNode=a;a:{g=vb(c,d);switch(c){case "dialog":D("cancel",a);D("close",a);e=d;break;case "iframe":case "object":case "embed":D("load",a);e=d;break;case "video":case "audio":for(e=0;e<lf.length;e++)D(lf[e],a);e=d;break;case "source":D("error",a);e=d;break;case "img":case "image":case "link":D("error",
a);D("load",a);e=d;break;case "details":D("toggle",a);e=d;break;case "input":Za(a,d);e=Ya(a,d);D("invalid",a);break;case "option":e=d;break;case "select":a._wrapperState={wasMultiple:!!d.multiple};e=A({},d,{value:void 0});D("invalid",a);break;case "textarea":hb(a,d);e=gb(a,d);D("invalid",a);break;default:e=d;}ub(c,e);h=e;for(f in h)if(h.hasOwnProperty(f)){var k=h[f];"style"===f?sb(a,k):"dangerouslySetInnerHTML"===f?(k=k?k.__html:void 0,null!=k&&nb(a,k)):"children"===f?"string"===typeof k?("textarea"!==
c||""!==k)&&ob(a,k):"number"===typeof k&&ob(a,""+k):"suppressContentEditableWarning"!==f&&"suppressHydrationWarning"!==f&&"autoFocus"!==f&&(ea.hasOwnProperty(f)?null!=k&&"onScroll"===f&&D("scroll",a):null!=k&&ta(a,f,k,g));}switch(c){case "input":Va(a);db(a,d,false);break;case "textarea":Va(a);jb(a);break;case "option":null!=d.value&&a.setAttribute("value",""+Sa(d.value));break;case "select":a.multiple=!!d.multiple;f=d.value;null!=f?fb(a,!!d.multiple,f,false):null!=d.defaultValue&&fb(a,!!d.multiple,d.defaultValue,
true);break;default:"function"===typeof e.onClick&&(a.onclick=Bf);}switch(c){case "button":case "input":case "select":case "textarea":d=!!d.autoFocus;break a;case "img":d=true;break a;default:d=false;}}d&&(b.flags|=4);}null!==b.ref&&(b.flags|=512,b.flags|=2097152);}S(b);return null;case 6:if(a&&null!=b.stateNode)Cj(a,b,a.memoizedProps,d);else {if("string"!==typeof d&&null===b.stateNode)throw Error(p(166));c=xh(wh.current);xh(uh.current);if(Gg(b)){d=b.stateNode;c=b.memoizedProps;d[Of]=b;if(f=d.nodeValue!==c)if(a=
xg,null!==a)switch(a.tag){case 3:Af(d.nodeValue,c,0!==(a.mode&1));break;case 5:true!==a.memoizedProps.suppressHydrationWarning&&Af(d.nodeValue,c,0!==(a.mode&1));}f&&(b.flags|=4);}else d=(9===c.nodeType?c:c.ownerDocument).createTextNode(d),d[Of]=b,b.stateNode=d;}S(b);return null;case 13:E(L);d=b.memoizedState;if(null===a||null!==a.memoizedState&&null!==a.memoizedState.dehydrated){if(I&&null!==yg&&0!==(b.mode&1)&&0===(b.flags&128))Hg(),Ig(),b.flags|=98560,f=false;else if(f=Gg(b),null!==d&&null!==d.dehydrated){if(null===
a){if(!f)throw Error(p(318));f=b.memoizedState;f=null!==f?f.dehydrated:null;if(!f)throw Error(p(317));f[Of]=b;}else Ig(),0===(b.flags&128)&&(b.memoizedState=null),b.flags|=4;S(b);f=false;}else null!==zg&&(Fj(zg),zg=null),f=true;if(!f)return b.flags&65536?b:null}if(0!==(b.flags&128))return b.lanes=c,b;d=null!==d;d!==(null!==a&&null!==a.memoizedState)&&d&&(b.child.flags|=8192,0!==(b.mode&1)&&(null===a||0!==(L.current&1)?0===T&&(T=3):tj()));null!==b.updateQueue&&(b.flags|=4);S(b);return null;case 4:return zh(),
Aj(a,b),null===a&&sf(b.stateNode.containerInfo),S(b),null;case 10:return ah(b.type._context),S(b),null;case 17:return Zf(b.type)&&$f(),S(b),null;case 19:E(L);f=b.memoizedState;if(null===f)return S(b),null;d=0!==(b.flags&128);g=f.rendering;if(null===g)if(d)Dj(f,false);else {if(0!==T||null!==a&&0!==(a.flags&128))for(a=b.child;null!==a;){g=Ch(a);if(null!==g){b.flags|=128;Dj(f,false);d=g.updateQueue;null!==d&&(b.updateQueue=d,b.flags|=4);b.subtreeFlags=0;d=c;for(c=b.child;null!==c;)f=c,a=d,f.flags&=14680066,
g=f.alternate,null===g?(f.childLanes=0,f.lanes=a,f.child=null,f.subtreeFlags=0,f.memoizedProps=null,f.memoizedState=null,f.updateQueue=null,f.dependencies=null,f.stateNode=null):(f.childLanes=g.childLanes,f.lanes=g.lanes,f.child=g.child,f.subtreeFlags=0,f.deletions=null,f.memoizedProps=g.memoizedProps,f.memoizedState=g.memoizedState,f.updateQueue=g.updateQueue,f.type=g.type,a=g.dependencies,f.dependencies=null===a?null:{lanes:a.lanes,firstContext:a.firstContext}),c=c.sibling;G(L,L.current&1|2);return b.child}a=
a.sibling;}null!==f.tail&&B()>Gj&&(b.flags|=128,d=true,Dj(f,false),b.lanes=4194304);}else {if(!d)if(a=Ch(g),null!==a){if(b.flags|=128,d=true,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Dj(f,true),null===f.tail&&"hidden"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Gj&&1073741824!==c&&(b.flags|=128,d=true,Dj(f,false),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g);}if(null!==f.tail)return b=f.tail,f.rendering=
b,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=L.current,G(L,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Hj(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(fj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}
function Ij(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return zh(),E(Wf),E(H),Eh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Bh(b),null;case 13:E(L);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig();}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(L),null;case 4:return zh(),null;case 10:return ah(b.type._context),null;case 22:case 23:return Hj(),
null;case 24:return null;default:return null}}var Jj=false,U=false,Kj="function"===typeof WeakSet?WeakSet:Set,V=null;function Lj(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null);}catch(d){W(a,b,d);}else c.current=null;}function Mj(a,b,c){try{c();}catch(d){W(a,b,d);}}var Nj=false;
function Oj(a,b){Cf=dd;a=Me();if(Ne(a)){if("selectionStart"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType;}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=
q.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y;}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode;}q=y;}c=-1===h||-1===k?null:{start:h,end:k};}else c=null;}c=c||{start:0,end:0};}else c=null;Df={focusedElem:a,selectionRange:c};dd=false;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;
case 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Ci(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w;}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent="":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F);}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return;}n=Nj;Nj=false;return n}
function Pj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Mj(b,c,f);}e=e.next;}while(e!==d)}}function Qj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d();}c=c.next;}while(c!==b)}}function Rj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c;}"function"===typeof b?b(a):b.current=a;}}
function Sj(a){var b=a.alternate;null!==b&&(a.alternate=null,Sj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null;}function Tj(a){return 5===a.tag||3===a.tag||4===a.tag}
function Uj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Tj(a.return))return null;a=a.return;}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child;}if(!(a.flags&2))return a.stateNode}}
function Vj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Vj(a,b,c),a=a.sibling;null!==a;)Vj(a,b,c),a=a.sibling;}
function Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling;}var X=null,Xj=false;function Yj(a,b,c){for(c=c.child;null!==c;)Zj(a,b,c),c=c.sibling;}
function Zj(a,b,c){if(lc&&"function"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c);}catch(h){}switch(c.tag){case 5:U||Lj(c,b);case 6:var d=X,e=Xj;X=null;Yj(a,b,c);X=d;Xj=e;null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Xj;X=c.stateNode.containerInfo;Xj=true;
Yj(a,b,c);X=d;Xj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Mj(c,b,g):0!==(f&4)&&Mj(c,b,g));e=e.next;}while(e!==d)}Yj(a,b,c);break;case 1:if(!U&&(Lj(c,b),d=c.stateNode,"function"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount();}catch(h){W(c,b,h);}Yj(a,b,c);break;case 21:Yj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==
c.memoizedState,Yj(a,b,c),U=d):Yj(a,b,c);break;default:Yj(a,b,c);}}function ak(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Kj);b.forEach(function(b){var d=bk.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d));});}}
function ck(a,b){var c=b.deletions;if(null!==c)for(var d=0;d<c.length;d++){var e=c[d];try{var f=a,g=b,h=g;a:for(;null!==h;){switch(h.tag){case 5:X=h.stateNode;Xj=!1;break a;case 3:X=h.stateNode.containerInfo;Xj=!0;break a;case 4:X=h.stateNode.containerInfo;Xj=!0;break a}h=h.return;}if(null===X)throw Error(p(160));Zj(f,g,e);X=null;Xj=!1;var k=e.alternate;null!==k&&(k.return=null);e.return=null;}catch(l){W(e,b,l);}}if(b.subtreeFlags&12854)for(b=b.child;null!==b;)dk(b,a),b=b.sibling;}
function dk(a,b){var c=a.alternate,d=a.flags;switch(a.tag){case 0:case 11:case 14:case 15:ck(b,a);ek(a);if(d&4){try{Pj(3,a,a.return),Qj(3,a);}catch(t){W(a,a.return,t);}try{Pj(5,a,a.return);}catch(t){W(a,a.return,t);}}break;case 1:ck(b,a);ek(a);d&512&&null!==c&&Lj(c,c.return);break;case 5:ck(b,a);ek(a);d&512&&null!==c&&Lj(c,c.return);if(a.flags&32){var e=a.stateNode;try{ob(e,"");}catch(t){W(a,a.return,t);}}if(d&4&&(e=a.stateNode,null!=e)){var f=a.memoizedProps,g=null!==c?c.memoizedProps:f,h=a.type,k=a.updateQueue;
a.updateQueue=null;if(null!==k)try{"input"===h&&"radio"===f.type&&null!=f.name&&ab(e,f);vb(h,g);var l=vb(h,f);for(g=0;g<k.length;g+=2){var m=k[g],q=k[g+1];"style"===m?sb(e,q):"dangerouslySetInnerHTML"===m?nb(e,q):"children"===m?ob(e,q):ta(e,m,q,l);}switch(h){case "input":bb(e,f);break;case "textarea":ib(e,f);break;case "select":var r=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=!!f.multiple;var y=f.value;null!=y?fb(e,!!f.multiple,y,!1):r!==!!f.multiple&&(null!=f.defaultValue?fb(e,!!f.multiple,
f.defaultValue,!0):fb(e,!!f.multiple,f.multiple?[]:"",!1));}e[Pf]=f;}catch(t){W(a,a.return,t);}}break;case 6:ck(b,a);ek(a);if(d&4){if(null===a.stateNode)throw Error(p(162));e=a.stateNode;f=a.memoizedProps;try{e.nodeValue=f;}catch(t){W(a,a.return,t);}}break;case 3:ck(b,a);ek(a);if(d&4&&null!==c&&c.memoizedState.isDehydrated)try{bd(b.containerInfo);}catch(t){W(a,a.return,t);}break;case 4:ck(b,a);ek(a);break;case 13:ck(b,a);ek(a);e=a.child;e.flags&8192&&(f=null!==e.memoizedState,e.stateNode.isHidden=f,!f||
null!==e.alternate&&null!==e.alternate.memoizedState||(fk=B()));d&4&&ak(a);break;case 22:m=null!==c&&null!==c.memoizedState;a.mode&1?(U=(l=U)||m,ck(b,a),U=l):ck(b,a);ek(a);if(d&8192){l=null!==a.memoizedState;if((a.stateNode.isHidden=l)&&!m&&0!==(a.mode&1))for(V=a,m=a.child;null!==m;){for(q=V=m;null!==V;){r=V;y=r.child;switch(r.tag){case 0:case 11:case 14:case 15:Pj(4,r,r.return);break;case 1:Lj(r,r.return);var n=r.stateNode;if("function"===typeof n.componentWillUnmount){d=r;c=r.return;try{b=d,n.props=
b.memoizedProps,n.state=b.memoizedState,n.componentWillUnmount();}catch(t){W(d,c,t);}}break;case 5:Lj(r,r.return);break;case 22:if(null!==r.memoizedState){gk(q);continue}}null!==y?(y.return=r,V=y):gk(q);}m=m.sibling;}a:for(m=null,q=a;;){if(5===q.tag){if(null===m){m=q;try{e=q.stateNode,l?(f=e.style,"function"===typeof f.setProperty?f.setProperty("display","none","important"):f.display="none"):(h=q.stateNode,k=q.memoizedProps.style,g=void 0!==k&&null!==k&&k.hasOwnProperty("display")?k.display:null,h.style.display=
rb("display",g));}catch(t){W(a,a.return,t);}}}else if(6===q.tag){if(null===m)try{q.stateNode.nodeValue=l?"":q.memoizedProps;}catch(t){W(a,a.return,t);}}else if((22!==q.tag&&23!==q.tag||null===q.memoizedState||q===a)&&null!==q.child){q.child.return=q;q=q.child;continue}if(q===a)break a;for(;null===q.sibling;){if(null===q.return||q.return===a)break a;m===q&&(m=null);q=q.return;}m===q&&(m=null);q.sibling.return=q.return;q=q.sibling;}}break;case 19:ck(b,a);ek(a);d&4&&ak(a);break;case 21:break;default:ck(b,
a),ek(a);}}function ek(a){var b=a.flags;if(b&2){try{a:{for(var c=a.return;null!==c;){if(Tj(c)){var d=c;break a}c=c.return;}throw Error(p(160));}switch(d.tag){case 5:var e=d.stateNode;d.flags&32&&(ob(e,""),d.flags&=-33);var f=Uj(a);Wj(a,f,e);break;case 3:case 4:var g=d.stateNode.containerInfo,h=Uj(a);Vj(a,h,g);break;default:throw Error(p(161));}}catch(k){W(a,a.return,k);}a.flags&=-3;}b&4096&&(a.flags&=-4097);}function hk(a,b,c){V=a;ik(a);}
function ik(a,b,c){for(var d=0!==(a.mode&1);null!==V;){var e=V,f=e.child;if(22===e.tag&&d){var g=null!==e.memoizedState||Jj;if(!g){var h=e.alternate,k=null!==h&&null!==h.memoizedState||U;h=Jj;var l=U;Jj=g;if((U=k)&&!l)for(V=e;null!==V;)g=V,k=g.child,22===g.tag&&null!==g.memoizedState?jk(e):null!==k?(k.return=g,V=k):jk(e);for(;null!==f;)V=f,ik(f),f=f.sibling;V=e;Jj=h;U=l;}kk(a);}else 0!==(e.subtreeFlags&8772)&&null!==f?(f.return=e,V=f):kk(a);}}
function kk(a){for(;null!==V;){var b=V;if(0!==(b.flags&8772)){var c=b.alternate;try{if(0!==(b.flags&8772))switch(b.tag){case 0:case 11:case 15:U||Qj(5,b);break;case 1:var d=b.stateNode;if(b.flags&4&&!U)if(null===c)d.componentDidMount();else {var e=b.elementType===b.type?c.memoizedProps:Ci(b.type,c.memoizedProps);d.componentDidUpdate(e,c.memoizedState,d.__reactInternalSnapshotBeforeUpdate);}var f=b.updateQueue;null!==f&&sh(b,f,d);break;case 3:var g=b.updateQueue;if(null!==g){c=null;if(null!==b.child)switch(b.child.tag){case 5:c=
b.child.stateNode;break;case 1:c=b.child.stateNode;}sh(b,g,c);}break;case 5:var h=b.stateNode;if(null===c&&b.flags&4){c=h;var k=b.memoizedProps;switch(b.type){case "button":case "input":case "select":case "textarea":k.autoFocus&&c.focus();break;case "img":k.src&&(c.src=k.src);}}break;case 6:break;case 4:break;case 12:break;case 13:if(null===b.memoizedState){var l=b.alternate;if(null!==l){var m=l.memoizedState;if(null!==m){var q=m.dehydrated;null!==q&&bd(q);}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;
default:throw Error(p(163));}U||b.flags&512&&Rj(b);}catch(r){W(b,b.return,r);}}if(b===a){V=null;break}c=b.sibling;if(null!==c){c.return=b.return;V=c;break}V=b.return;}}function gk(a){for(;null!==V;){var b=V;if(b===a){V=null;break}var c=b.sibling;if(null!==c){c.return=b.return;V=c;break}V=b.return;}}
function jk(a){for(;null!==V;){var b=V;try{switch(b.tag){case 0:case 11:case 15:var c=b.return;try{Qj(4,b);}catch(k){W(b,c,k);}break;case 1:var d=b.stateNode;if("function"===typeof d.componentDidMount){var e=b.return;try{d.componentDidMount();}catch(k){W(b,e,k);}}var f=b.return;try{Rj(b);}catch(k){W(b,f,k);}break;case 5:var g=b.return;try{Rj(b);}catch(k){W(b,g,k);}}}catch(k){W(b,b.return,k);}if(b===a){V=null;break}var h=b.sibling;if(null!==h){h.return=b.return;V=h;break}V=b.return;}}
var lk=Math.ceil,mk=ua.ReactCurrentDispatcher,nk=ua.ReactCurrentOwner,ok=ua.ReactCurrentBatchConfig,K=0,Q=null,Y=null,Z=0,fj=0,ej=Uf(0),T=0,pk=null,rh=0,qk=0,rk=0,sk=null,tk=null,fk=0,Gj=Infinity,uk=null,Oi=false,Pi=null,Ri=null,vk=false,wk=null,xk=0,yk=0,zk=null,Ak=-1,Bk=0;function R(){return 0!==(K&6)?B():-1!==Ak?Ak:Ak=B()}
function yi(a){if(0===(a.mode&1))return 1;if(0!==(K&2)&&0!==Z)return Z&-Z;if(null!==Kg.transition)return 0===Bk&&(Bk=yc()),Bk;a=C;if(0!==a)return a;a=window.event;a=void 0===a?16:jd(a.type);return a}function gi(a,b,c,d){if(50<yk)throw yk=0,zk=null,Error(p(185));Ac(a,c,d);if(0===(K&2)||a!==Q)a===Q&&(0===(K&2)&&(qk|=c),4===T&&Ck(a,Z)),Dk(a,d),1===c&&0===K&&0===(b.mode&1)&&(Gj=B()+500,fg&&jg());}
function Dk(a,b){var c=a.callbackNode;wc(a,b);var d=uc(a,a===Q?Z:0);if(0===d)null!==c&&bc(c),a.callbackNode=null,a.callbackPriority=0;else if(b=d&-d,a.callbackPriority!==b){null!=c&&bc(c);if(1===b)0===a.tag?ig(Ek.bind(null,a)):hg(Ek.bind(null,a)),Jf(function(){0===(K&6)&&jg();}),c=null;else {switch(Dc(d)){case 1:c=fc;break;case 4:c=gc;break;case 16:c=hc;break;case 536870912:c=jc;break;default:c=hc;}c=Fk(c,Gk.bind(null,a));}a.callbackPriority=b;a.callbackNode=c;}}
function Gk(a,b){Ak=-1;Bk=0;if(0!==(K&6))throw Error(p(327));var c=a.callbackNode;if(Hk()&&a.callbackNode!==c)return null;var d=uc(a,a===Q?Z:0);if(0===d)return null;if(0!==(d&30)||0!==(d&a.expiredLanes)||b)b=Ik(a,d);else {b=d;var e=K;K|=2;var f=Jk();if(Q!==a||Z!==b)uk=null,Gj=B()+500,Kk(a,b);do try{Lk();break}catch(h){Mk(a,h);}while(1);$g();mk.current=f;K=e;null!==Y?b=0:(Q=null,Z=0,b=T);}if(0!==b){2===b&&(e=xc(a),0!==e&&(d=e,b=Nk(a,e)));if(1===b)throw c=pk,Kk(a,0),Ck(a,d),Dk(a,B()),c;if(6===b)Ck(a,d);
else {e=a.current.alternate;if(0===(d&30)&&!Ok(e)&&(b=Ik(a,d),2===b&&(f=xc(a),0!==f&&(d=f,b=Nk(a,f))),1===b))throw c=pk,Kk(a,0),Ck(a,d),Dk(a,B()),c;a.finishedWork=e;a.finishedLanes=d;switch(b){case 0:case 1:throw Error(p(345));case 2:Pk(a,tk,uk);break;case 3:Ck(a,d);if((d&130023424)===d&&(b=fk+500-B(),10<b)){if(0!==uc(a,0))break;e=a.suspendedLanes;if((e&d)!==d){R();a.pingedLanes|=a.suspendedLanes&e;break}a.timeoutHandle=Ff(Pk.bind(null,a,tk,uk),b);break}Pk(a,tk,uk);break;case 4:Ck(a,d);if((d&4194240)===
d)break;b=a.eventTimes;for(e=-1;0<d;){var g=31-oc(d);f=1<<g;g=b[g];g>e&&(e=g);d&=~f;}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*lk(d/1960))-d;if(10<d){a.timeoutHandle=Ff(Pk.bind(null,a,tk,uk),d);break}Pk(a,tk,uk);break;case 5:Pk(a,tk,uk);break;default:throw Error(p(329));}}}Dk(a,B());return a.callbackNode===c?Gk.bind(null,a):null}
function Nk(a,b){var c=sk;a.current.memoizedState.isDehydrated&&(Kk(a,b).flags|=256);a=Ik(a,b);2!==a&&(b=tk,tk=c,null!==b&&Fj(b));return a}function Fj(a){null===tk?tk=a:tk.push.apply(tk,a);}
function Ok(a){for(var b=a;;){if(b.flags&16384){var c=b.updateQueue;if(null!==c&&(c=c.stores,null!==c))for(var d=0;d<c.length;d++){var e=c[d],f=e.getSnapshot;e=e.value;try{if(!He(f(),e))return !1}catch(g){return false}}}c=b.child;if(b.subtreeFlags&16384&&null!==c)c.return=b,b=c;else {if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return true;b=b.return;}b.sibling.return=b.return;b=b.sibling;}}return true}
function Ck(a,b){b&=~rk;b&=~qk;a.suspendedLanes|=b;a.pingedLanes&=~b;for(a=a.expirationTimes;0<b;){var c=31-oc(b),d=1<<c;a[c]=-1;b&=~d;}}function Ek(a){if(0!==(K&6))throw Error(p(327));Hk();var b=uc(a,0);if(0===(b&1))return Dk(a,B()),null;var c=Ik(a,b);if(0!==a.tag&&2===c){var d=xc(a);0!==d&&(b=d,c=Nk(a,d));}if(1===c)throw c=pk,Kk(a,0),Ck(a,b),Dk(a,B()),c;if(6===c)throw Error(p(345));a.finishedWork=a.current.alternate;a.finishedLanes=b;Pk(a,tk,uk);Dk(a,B());return null}
function Qk(a,b){var c=K;K|=1;try{return a(b)}finally{K=c,0===K&&(Gj=B()+500,fg&&jg());}}function Rk(a){null!==wk&&0===wk.tag&&0===(K&6)&&Hk();var b=K;K|=1;var c=ok.transition,d=C;try{if(ok.transition=null,C=1,a)return a()}finally{C=d,ok.transition=c,K=b,0===(K&6)&&jg();}}function Hj(){fj=ej.current;E(ej);}
function Kk(a,b){a.finishedWork=null;a.finishedLanes=0;var c=a.timeoutHandle;-1!==c&&(a.timeoutHandle=-1,Gf(c));if(null!==Y)for(c=Y.return;null!==c;){var d=c;wg(d);switch(d.tag){case 1:d=d.type.childContextTypes;null!==d&&void 0!==d&&$f();break;case 3:zh();E(Wf);E(H);Eh();break;case 5:Bh(d);break;case 4:zh();break;case 13:E(L);break;case 19:E(L);break;case 10:ah(d.type._context);break;case 22:case 23:Hj();}c=c.return;}Q=a;Y=a=Pg(a.current,null);Z=fj=b;T=0;pk=null;rk=qk=rh=0;tk=sk=null;if(null!==fh){for(b=
0;b<fh.length;b++)if(c=fh[b],d=c.interleaved,null!==d){c.interleaved=null;var e=d.next,f=c.pending;if(null!==f){var g=f.next;f.next=e;d.next=g;}c.pending=d;}fh=null;}return a}
function Mk(a,b){do{var c=Y;try{$g();Fh.current=Rh;if(Ih){for(var d=M.memoizedState;null!==d;){var e=d.queue;null!==e&&(e.pending=null);d=d.next;}Ih=!1;}Hh=0;O=N=M=null;Jh=!1;Kh=0;nk.current=null;if(null===c||null===c.return){T=1;pk=b;Y=null;break}a:{var f=a,g=c.return,h=c,k=b;b=Z;h.flags|=32768;if(null!==k&&"object"===typeof k&&"function"===typeof k.then){var l=k,m=h,q=m.tag;if(0===(m.mode&1)&&(0===q||11===q||15===q)){var r=m.alternate;r?(m.updateQueue=r.updateQueue,m.memoizedState=r.memoizedState,
m.lanes=r.lanes):(m.updateQueue=null,m.memoizedState=null);}var y=Ui(g);if(null!==y){y.flags&=-257;Vi(y,g,h,f,b);y.mode&1&&Si(f,l,b);b=y;k=l;var n=b.updateQueue;if(null===n){var t=new Set;t.add(k);b.updateQueue=t;}else n.add(k);break a}else {if(0===(b&1)){Si(f,l,b);tj();break a}k=Error(p(426));}}else if(I&&h.mode&1){var J=Ui(g);if(null!==J){0===(J.flags&65536)&&(J.flags|=256);Vi(J,g,h,f,b);Jg(Ji(k,h));break a}}f=k=Ji(k,h);4!==T&&(T=2);null===sk?sk=[f]:sk.push(f);f=g;do{switch(f.tag){case 3:f.flags|=65536;
b&=-b;f.lanes|=b;var x=Ni(f,k,b);ph(f,x);break a;case 1:h=k;var w=f.type,u=f.stateNode;if(0===(f.flags&128)&&("function"===typeof w.getDerivedStateFromError||null!==u&&"function"===typeof u.componentDidCatch&&(null===Ri||!Ri.has(u)))){f.flags|=65536;b&=-b;f.lanes|=b;var F=Qi(f,h,b);ph(f,F);break a}}f=f.return;}while(null!==f)}Sk(c);}catch(na){b=na;Y===c&&null!==c&&(Y=c=c.return);continue}break}while(1)}function Jk(){var a=mk.current;mk.current=Rh;return null===a?Rh:a}
function tj(){if(0===T||3===T||2===T)T=4;null===Q||0===(rh&268435455)&&0===(qk&268435455)||Ck(Q,Z);}function Ik(a,b){var c=K;K|=2;var d=Jk();if(Q!==a||Z!==b)uk=null,Kk(a,b);do try{Tk();break}catch(e){Mk(a,e);}while(1);$g();K=c;mk.current=d;if(null!==Y)throw Error(p(261));Q=null;Z=0;return T}function Tk(){for(;null!==Y;)Uk(Y);}function Lk(){for(;null!==Y&&!cc();)Uk(Y);}function Uk(a){var b=Vk(a.alternate,a,fj);a.memoizedProps=a.pendingProps;null===b?Sk(a):Y=b;nk.current=null;}
function Sk(a){var b=a;do{var c=b.alternate;a=b.return;if(0===(b.flags&32768)){if(c=Ej(c,b,fj),null!==c){Y=c;return}}else {c=Ij(c,b);if(null!==c){c.flags&=32767;Y=c;return}if(null!==a)a.flags|=32768,a.subtreeFlags=0,a.deletions=null;else {T=6;Y=null;return}}b=b.sibling;if(null!==b){Y=b;return}Y=b=a;}while(null!==b);0===T&&(T=5);}function Pk(a,b,c){var d=C,e=ok.transition;try{ok.transition=null,C=1,Wk(a,b,c,d);}finally{ok.transition=e,C=d;}return null}
function Wk(a,b,c,d){do Hk();while(null!==wk);if(0!==(K&6))throw Error(p(327));c=a.finishedWork;var e=a.finishedLanes;if(null===c)return null;a.finishedWork=null;a.finishedLanes=0;if(c===a.current)throw Error(p(177));a.callbackNode=null;a.callbackPriority=0;var f=c.lanes|c.childLanes;Bc(a,f);a===Q&&(Y=Q=null,Z=0);0===(c.subtreeFlags&2064)&&0===(c.flags&2064)||vk||(vk=true,Fk(hc,function(){Hk();return null}));f=0!==(c.flags&15990);if(0!==(c.subtreeFlags&15990)||f){f=ok.transition;ok.transition=null;
var g=C;C=1;var h=K;K|=4;nk.current=null;Oj(a,c);dk(c,a);Oe(Df);dd=!!Cf;Df=Cf=null;a.current=c;hk(c);dc();K=h;C=g;ok.transition=f;}else a.current=c;vk&&(vk=false,wk=a,xk=e);f=a.pendingLanes;0===f&&(Ri=null);mc(c.stateNode);Dk(a,B());if(null!==b)for(d=a.onRecoverableError,c=0;c<b.length;c++)e=b[c],d(e.value,{componentStack:e.stack,digest:e.digest});if(Oi)throw Oi=false,a=Pi,Pi=null,a;0!==(xk&1)&&0!==a.tag&&Hk();f=a.pendingLanes;0!==(f&1)?a===zk?yk++:(yk=0,zk=a):yk=0;jg();return null}
function Hk(){if(null!==wk){var a=Dc(xk),b=ok.transition,c=C;try{ok.transition=null;C=16>a?16:a;if(null===wk)var d=!1;else {a=wk;wk=null;xk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;k<h.length;k++){var l=h[k];for(V=l;null!==V;){var m=V;switch(m.tag){case 0:case 11:case 15:Pj(8,m,f);}var q=m.child;if(null!==q)q.return=m,V=q;else for(;null!==V;){m=V;var r=m.sibling,y=m.return;Sj(m);if(m===
l){V=null;break}if(null!==r){r.return=y;V=r;break}V=y;}}}var n=f.alternate;if(null!==n){var t=n.child;if(null!==t){n.child=null;do{var J=t.sibling;t.sibling=null;t=J;}while(null!==t)}}V=f;}}if(0!==(f.subtreeFlags&2064)&&null!==g)g.return=f,V=g;else b:for(;null!==V;){f=V;if(0!==(f.flags&2048))switch(f.tag){case 0:case 11:case 15:Pj(9,f,f.return);}var x=f.sibling;if(null!==x){x.return=f.return;V=x;break b}V=f.return;}}var w=a.current;for(V=w;null!==V;){g=V;var u=g.child;if(0!==(g.subtreeFlags&2064)&&null!==
u)u.return=g,V=u;else b:for(g=w;null!==V;){h=V;if(0!==(h.flags&2048))try{switch(h.tag){case 0:case 11:case 15:Qj(9,h);}}catch(na){W(h,h.return,na);}if(h===g){V=null;break b}var F=h.sibling;if(null!==F){F.return=h.return;V=F;break b}V=h.return;}}K=e;jg();if(lc&&"function"===typeof lc.onPostCommitFiberRoot)try{lc.onPostCommitFiberRoot(kc,a);}catch(na){}d=!0;}return d}finally{C=c,ok.transition=b;}}return false}function Xk(a,b,c){b=Ji(c,b);b=Ni(a,b,1);a=nh(a,b,1);b=R();null!==a&&(Ac(a,1,b),Dk(a,b));}
function W(a,b,c){if(3===a.tag)Xk(a,a,c);else for(;null!==b;){if(3===b.tag){Xk(b,a,c);break}else if(1===b.tag){var d=b.stateNode;if("function"===typeof b.type.getDerivedStateFromError||"function"===typeof d.componentDidCatch&&(null===Ri||!Ri.has(d))){a=Ji(c,a);a=Qi(b,a,1);b=nh(b,a,1);a=R();null!==b&&(Ac(b,1,a),Dk(b,a));break}}b=b.return;}}
function Ti(a,b,c){var d=a.pingCache;null!==d&&d.delete(b);b=R();a.pingedLanes|=a.suspendedLanes&c;Q===a&&(Z&c)===c&&(4===T||3===T&&(Z&130023424)===Z&&500>B()-fk?Kk(a,0):rk|=c);Dk(a,b);}function Yk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=R();a=ih(a,b);null!==a&&(Ac(a,b,c),Dk(a,c));}function uj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Yk(a,c);}
function bk(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Yk(a,c);}var Vk;
Vk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)dh=true;else {if(0===(a.lanes&c)&&0===(b.flags&128))return dh=false,yj(a,b,c);dh=0!==(a.flags&131072)?true:false;}else dh=false,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;ij(a,b);a=b.pendingProps;var e=Yf(b,H.current);ch(b,c);e=Nh(null,b,d,a,e,c);var f=Sh();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=
null,Zf(d)?(f=true,cg(b)):f=false,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,kh(b),e.updater=Ei,b.stateNode=e,e._reactInternals=b,Ii(b,d,a,c),b=jj(null,b,d,true,f,c)):(b.tag=0,I&&f&&vg(b),Xi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{ij(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Zk(d);a=Ci(d,a);switch(e){case 0:b=cj(null,b,d,a,c);break a;case 1:b=hj(null,b,d,a,c);break a;case 11:b=Yi(null,b,d,a,c);break a;case 14:b=$i(null,b,d,Ci(d.type,a),c);break a}throw Error(p(306,
d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),cj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),hj(a,b,d,e,c);case 3:a:{kj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;lh(a,b);qh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:false,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=
f,b.memoizedState=f,b.flags&256){e=Ji(Error(p(423)),b);b=lj(a,b,d,c,e);break a}else if(d!==e){e=Ji(Error(p(424)),b);b=lj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=true,zg=null,c=Vg(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else {Ig();if(d===e){b=Zi(a,b,c);break a}Xi(a,b,d,c);}b=b.child;}return b;case 5:return Ah(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),
gj(a,b),Xi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return oj(a,b,c);case 4:return yh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Ug(b,null,d,c):Xi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),Yi(a,b,d,e,c);case 7:return Xi(a,b,b.pendingProps,c),b.child;case 8:return Xi(a,b,b.pendingProps.children,c),b.child;case 12:return Xi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;
g=e.value;G(Wg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=Zi(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=mh(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k;}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);bh(f.return,
c,b);h.lanes|=c;break}k=k.next;}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);bh(g,c,b);g=f.sibling;}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return;}f=g;}Xi(a,b,e.children,c);b=b.child;}return b;case 9:return e=b.type,d=b.pendingProps.children,ch(b,c),e=eh(e),d=d(e),b.flags|=1,Xi(a,b,d,c),
b.child;case 14:return d=b.type,e=Ci(d,b.pendingProps),e=Ci(d.type,e),$i(a,b,d,e,c);case 15:return bj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),ij(a,b),b.tag=1,Zf(d)?(a=true,cg(b)):a=false,ch(b,c),Gi(b,d,e),Ii(b,d,e,c),jj(null,b,d,true,a,c);case 19:return xj(a,b,c);case 22:return dj(a,b,c)}throw Error(p(156,b.tag));};function Fk(a,b){return ac(a,b)}
function $k(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null;}function Bg(a,b,c,d){return new $k(a,b,c,d)}function aj(a){a=a.prototype;return !(!a||!a.isReactComponent)}
function Zk(a){if("function"===typeof a)return aj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}
function Pg(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};
c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}
function Rg(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)aj(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ya:return Tg(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return pj(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;
break a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,""));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Tg(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function pj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:false};return a}function Qg(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}
function Sg(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}
function al(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=
null;}function bl(a,b,c,d,e,f,g,h,k){a=new al(a,b,c,h,k);1===b?(b=1,true===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};kh(f);return a}function cl(a,b,c){var d=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return {$$typeof:wa,key:null==d?null:""+d,children:a,containerInfo:b,implementation:c}}
function dl(a){if(!a)return Vf;a=a._reactInternals;a:{if(Vb(a)!==a||1!==a.tag)throw Error(p(170));var b=a;do{switch(b.tag){case 3:b=b.stateNode.context;break a;case 1:if(Zf(b.type)){b=b.stateNode.__reactInternalMemoizedMergedChildContext;break a}}b=b.return;}while(null!==b);throw Error(p(171));}if(1===a.tag){var c=a.type;if(Zf(c))return bg(a,c,b)}return b}
function el(a,b,c,d,e,f,g,h,k){a=bl(c,d,true,a,e,f,g,h,k);a.context=dl(null);c=a.current;d=R();e=yi(c);f=mh(d,e);f.callback=void 0!==b&&null!==b?b:null;nh(c,f,e);a.current.lanes=e;Ac(a,e,d);Dk(a,d);return a}function fl(a,b,c,d){var e=b.current,f=R(),g=yi(e);c=dl(c);null===b.context?b.context=c:b.pendingContext=c;b=mh(f,g);b.payload={element:a};d=void 0===d?null:d;null!==d&&(b.callback=d);a=nh(e,b,g);null!==a&&(gi(a,e,g,f),oh(a,e,g));return g}
function gl(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function hl(a,b){a=a.memoizedState;if(null!==a&&null!==a.dehydrated){var c=a.retryLane;a.retryLane=0!==c&&c<b?c:b;}}function il(a,b){hl(a,b);(a=a.alternate)&&hl(a,b);}function jl(){return null}var kl="function"===typeof reportError?reportError:function(a){console.error(a);};function ll(a){this._internalRoot=a;}
ml.prototype.render=ll.prototype.render=function(a){var b=this._internalRoot;if(null===b)throw Error(p(409));fl(a,b,null,null);};ml.prototype.unmount=ll.prototype.unmount=function(){var a=this._internalRoot;if(null!==a){this._internalRoot=null;var b=a.containerInfo;Rk(function(){fl(null,a,null,null);});b[uf]=null;}};function ml(a){this._internalRoot=a;}
ml.prototype.unstable_scheduleHydration=function(a){if(a){var b=Hc();a={blockedOn:null,target:a,priority:b};for(var c=0;c<Qc.length&&0!==b&&b<Qc[c].priority;c++);Qc.splice(c,0,a);0===c&&Vc(a);}};function nl(a){return !(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType)}function ol(a){return !(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||" react-mount-point-unstable "!==a.nodeValue))}function pl(){}
function ql(a,b,c,d,e){if(e){if("function"===typeof d){var f=d;d=function(){var a=gl(g);f.call(a);};}var g=el(b,d,a,0,null,false,false,"",pl);a._reactRootContainer=g;a[uf]=g.current;sf(8===a.nodeType?a.parentNode:a);Rk();return g}for(;e=a.lastChild;)a.removeChild(e);if("function"===typeof d){var h=d;d=function(){var a=gl(k);h.call(a);};}var k=bl(a,0,false,null,null,false,false,"",pl);a._reactRootContainer=k;a[uf]=k.current;sf(8===a.nodeType?a.parentNode:a);Rk(function(){fl(b,k,c,d);});return k}
function rl(a,b,c,d,e){var f=c._reactRootContainer;if(f){var g=f;if("function"===typeof e){var h=e;e=function(){var a=gl(g);h.call(a);};}fl(b,g,a,e);}else g=ql(c,b,a,e,d);return gl(g)}Ec=function(a){switch(a.tag){case 3:var b=a.stateNode;if(b.current.memoizedState.isDehydrated){var c=tc(b.pendingLanes);0!==c&&(Cc(b,c|1),Dk(b,B()),0===(K&6)&&(Gj=B()+500,jg()));}break;case 13:Rk(function(){var b=ih(a,1);if(null!==b){var c=R();gi(b,a,1,c);}}),il(a,1);}};
Fc=function(a){if(13===a.tag){var b=ih(a,134217728);if(null!==b){var c=R();gi(b,a,134217728,c);}il(a,134217728);}};Gc=function(a){if(13===a.tag){var b=yi(a),c=ih(a,b);if(null!==c){var d=R();gi(c,a,b,d);}il(a,b);}};Hc=function(){return C};Ic=function(a,b){var c=C;try{return C=a,b()}finally{C=c;}};
yb=function(a,b,c){switch(b){case "input":bb(a,c);b=c.name;if("radio"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll("input[name="+JSON.stringify(""+b)+'][type="radio"]');for(b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=Db(d);if(!e)throw Error(p(90));Wa(d);bb(d,e);}}}break;case "textarea":ib(a,c);break;case "select":b=c.value,null!=b&&fb(a,!!c.multiple,b,false);}};Gb=Qk;Hb=Rk;
var sl={usingClientEntryPoint:false,Events:[Cb,ue,Db,Eb,Fb,Qk]},tl={findFiberByHostInstance:Wc,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"};
var ul={bundleType:tl.bundleType,version:tl.version,rendererPackageName:tl.rendererPackageName,rendererConfig:tl.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:ua.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){a=Zb(a);return null===a?null:a.stateNode},findFiberByHostInstance:tl.findFiberByHostInstance||
jl,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if("undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var vl=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!vl.isDisabled&&vl.supportsFiber)try{kc=vl.inject(ul),lc=vl;}catch(a){}}reactDom_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=sl;
reactDom_production_min.createPortal=function(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!nl(b))throw Error(p(200));return cl(a,b,null,c)};reactDom_production_min.createRoot=function(a,b){if(!nl(a))throw Error(p(299));var c=false,d="",e=kl;null!==b&&void 0!==b&&(true===b.unstable_strictMode&&(c=true),void 0!==b.identifierPrefix&&(d=b.identifierPrefix),void 0!==b.onRecoverableError&&(e=b.onRecoverableError));b=bl(a,1,false,null,null,c,false,d,e);a[uf]=b.current;sf(8===a.nodeType?a.parentNode:a);return new ll(b)};
reactDom_production_min.findDOMNode=function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternals;if(void 0===b){if("function"===typeof a.render)throw Error(p(188));a=Object.keys(a).join(",");throw Error(p(268,a));}a=Zb(b);a=null===a?null:a.stateNode;return a};reactDom_production_min.flushSync=function(a){return Rk(a)};reactDom_production_min.hydrate=function(a,b,c){if(!ol(b))throw Error(p(200));return rl(null,a,b,true,c)};
reactDom_production_min.hydrateRoot=function(a,b,c){if(!nl(a))throw Error(p(405));var d=null!=c&&c.hydratedSources||null,e=false,f="",g=kl;null!==c&&void 0!==c&&(true===c.unstable_strictMode&&(e=true),void 0!==c.identifierPrefix&&(f=c.identifierPrefix),void 0!==c.onRecoverableError&&(g=c.onRecoverableError));b=el(b,null,a,1,null!=c?c:null,e,false,f,g);a[uf]=b.current;sf(a);if(d)for(a=0;a<d.length;a++)c=d[a],e=c._getVersion,e=e(c._source),null==b.mutableSourceEagerHydrationData?b.mutableSourceEagerHydrationData=[c,e]:b.mutableSourceEagerHydrationData.push(c,
e);return new ml(b)};reactDom_production_min.render=function(a,b,c){if(!ol(b))throw Error(p(200));return rl(null,a,b,false,c)};reactDom_production_min.unmountComponentAtNode=function(a){if(!ol(a))throw Error(p(40));return a._reactRootContainer?(Rk(function(){rl(null,null,a,!1,function(){a._reactRootContainer=null;a[uf]=null;});}),true):false};reactDom_production_min.unstable_batchedUpdates=Qk;
reactDom_production_min.unstable_renderSubtreeIntoContainer=function(a,b,c,d){if(!ol(c))throw Error(p(200));if(null==a||void 0===a._reactInternals)throw Error(p(38));return rl(a,b,c,false,d)};reactDom_production_min.version="18.3.1-next-f1338f8080-20240426";
return reactDom_production_min;
}
var hasRequiredReactDom;
function requireReactDom () {
if (hasRequiredReactDom) return reactDom.exports;
hasRequiredReactDom = 1;
function checkDCE() {
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
if (
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'
) {
return;
}
try {
// Verify that the code above has been dead code eliminated (DCE'd).
__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
} catch (err) {
// DevTools shouldn't crash React, no matter what.
// We should still report in case we break this code.
console.error(err);
}
}
{
// DCE check should happen before ReactDOM bundle executes so that
// DevTools can report bad minification during injection.
checkDCE();
reactDom.exports = requireReactDom_production_min();
}
return reactDom.exports;
}
var hasRequiredClient;
function requireClient () {
if (hasRequiredClient) return client;
hasRequiredClient = 1;
var m = requireReactDom();
{
client.createRoot = m.createRoot;
client.hydrateRoot = m.hydrateRoot;
}
return client;
}
var clientExports = requireClient();
var ReactDOM$1 = /*@__PURE__*/getDefaultExportFromCjs(clientExports);
/**
* WARNING: Don't import this directly. It's imported by the code generated by
* `@mui/interal-babel-plugin-minify-errors`. Make sure to always use string literals in `Error`
* constructors to ensure the plugin works as expected. Supported patterns include:
* throw new Error('My message');
* throw new Error(`My message: ${foo}`);
* throw new Error(`My message: ${foo}` + 'another string');
* ...
* @param {number} code
*/
function formatMuiErrorMessage(code, ...args) {
const url = new URL(`https://mui.com/production-error/?code=${code}`);
args.forEach(arg => url.searchParams.append('args[]', arg));
return `Minified MUI error #${code}; visit ${url} for the full message.`;
}
var THEME_ID = '$$material';
function _extends() {
return _extends = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, _extends.apply(null, arguments);
}
/*
Based off glamor's StyleSheet, thanks Sunil ❤️
high performance StyleSheet for css-in-js systems
- uses multiple style tags behind the scenes for millions of rules
- uses `insertRule` for appending in production for *much* faster performance
// usage
import { StyleSheet } from '@emotion/sheet'
let styleSheet = new StyleSheet({ key: '', container: document.head })
styleSheet.insert('#box { border: 1px solid red; }')
- appends a css rule into the stylesheet
styleSheet.flush()
- empties the stylesheet of all its contents
*/
function sheetForTag(tag) {
if (tag.sheet) {
return tag.sheet;
} // this weirdness brought to you by firefox
/* istanbul ignore next */
for (var i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].ownerNode === tag) {
return document.styleSheets[i];
}
} // this function should always return with a value
// TS can't understand it though so we make it stop complaining here
return undefined;
}
function createStyleElement(options) {
var tag = document.createElement('style');
tag.setAttribute('data-emotion', options.key);
if (options.nonce !== undefined) {
tag.setAttribute('nonce', options.nonce);
}
tag.appendChild(document.createTextNode(''));
tag.setAttribute('data-s', '');
return tag;
}
var StyleSheet = /*#__PURE__*/function () {
// Using Node instead of HTMLElement since container may be a ShadowRoot
function StyleSheet(options) {
var _this = this;
this._insertTag = function (tag) {
var before;
if (_this.tags.length === 0) {
if (_this.insertionPoint) {
before = _this.insertionPoint.nextSibling;
} else if (_this.prepend) {
before = _this.container.firstChild;
} else {
before = _this.before;
}
} else {
before = _this.tags[_this.tags.length - 1].nextSibling;
}
_this.container.insertBefore(tag, before);
_this.tags.push(tag);
};
this.isSpeedy = options.speedy === undefined ? true : options.speedy;
this.tags = [];
this.ctr = 0;
this.nonce = options.nonce; // key is the value of the data-emotion attribute, it's used to identify different sheets
this.key = options.key;
this.container = options.container;
this.prepend = options.prepend;
this.insertionPoint = options.insertionPoint;
this.before = null;
}
var _proto = StyleSheet.prototype;
_proto.hydrate = function hydrate(nodes) {
nodes.forEach(this._insertTag);
};
_proto.insert = function insert(rule) {
// the max length is how many rules we have per style tag, it's 65000 in speedy mode
// it's 1 in dev because we insert source maps that map a single rule to a location
// and you can only have one source map per style tag
if (this.ctr % (this.isSpeedy ? 65000 : 1) === 0) {
this._insertTag(createStyleElement(this));
}
var tag = this.tags[this.tags.length - 1];
if (this.isSpeedy) {
var sheet = sheetForTag(tag);
try {
// this is the ultrafast version, works across browsers
// the big drawback is that the css won't be editable in devtools
sheet.insertRule(rule, sheet.cssRules.length);
} catch (e) {
}
} else {
tag.appendChild(document.createTextNode(rule));
}
this.ctr++;
};
_proto.flush = function flush() {
this.tags.forEach(function (tag) {
var _tag$parentNode;
return (_tag$parentNode = tag.parentNode) == null ? void 0 : _tag$parentNode.removeChild(tag);
});
this.tags = [];
this.ctr = 0;
};
return StyleSheet;
}();
var MS = '-ms-';
var MOZ = '-moz-';
var WEBKIT = '-webkit-';
var COMMENT = 'comm';
var RULESET = 'rule';
var DECLARATION = 'decl';
var IMPORT = '@import';
var KEYFRAMES = '@keyframes';
var LAYER = '@layer';
/**
* @param {number}
* @return {number}
*/
var abs = Math.abs;
/**
* @param {number}
* @return {string}
*/
var from = String.fromCharCode;
/**
* @param {object}
* @return {object}
*/
var assign = Object.assign;
/**
* @param {string} value
* @param {number} length
* @return {number}
*/
function hash$2 (value, length) {
return charat(value, 0) ^ 45 ? (((((((length << 2) ^ charat(value, 0)) << 2) ^ charat(value, 1)) << 2) ^ charat(value, 2)) << 2) ^ charat(value, 3) : 0
}
/**
* @param {string} value
* @return {string}
*/
function trim (value) {
return value.trim()
}
/**
* @param {string} value
* @param {RegExp} pattern
* @return {string?}
*/
function match (value, pattern) {
return (value = pattern.exec(value)) ? value[0] : value
}
/**
* @param {string} value
* @param {(string|RegExp)} pattern
* @param {string} replacement
* @return {string}
*/
function replace (value, pattern, replacement) {
return value.replace(pattern, replacement)
}
/**
* @param {string} value
* @param {string} search
* @return {number}
*/
function indexof (value, search) {
return value.indexOf(search)
}
/**
* @param {string} value
* @param {number} index
* @return {number}
*/
function charat (value, index) {
return value.charCodeAt(index) | 0
}
/**
* @param {string} value
* @param {number} begin
* @param {number} end
* @return {string}
*/
function substr (value, begin, end) {
return value.slice(begin, end)
}
/**
* @param {string} value
* @return {number}
*/
function strlen (value) {
return value.length
}
/**
* @param {any[]} value
* @return {number}
*/
function sizeof (value) {
return value.length
}
/**
* @param {any} value
* @param {any[]} array
* @return {any}
*/
function append (value, array) {
return array.push(value), value
}
/**
* @param {string[]} array
* @param {function} callback
* @return {string}
*/
function combine (array, callback) {
return array.map(callback).join('')
}
var line = 1;
var column = 1;
var length = 0;
var position = 0;
var character = 0;
var characters = '';
/**
* @param {string} value
* @param {object | null} root
* @param {object | null} parent
* @param {string} type
* @param {string[] | string} props
* @param {object[] | string} children
* @param {number} length
*/
function node (value, root, parent, type, props, children, length) {
return {value: value, root: root, parent: parent, type: type, props: props, children: children, line: line, column: column, length: length, return: ''}
}
/**
* @param {object} root
* @param {object} props
* @return {object}
*/
function copy (root, props) {
return assign(node('', null, null, '', null, null, 0), root, {length: -root.length}, props)
}
/**
* @return {number}
*/
function char () {
return character
}
/**
* @return {number}
*/
function prev () {
character = position > 0 ? charat(characters, --position) : 0;
if (column--, character === 10)
column = 1, line--;
return character
}
/**
* @return {number}
*/
function next () {
character = position < length ? charat(characters, position++) : 0;
if (column++, character === 10)
column = 1, line++;
return character
}
/**
* @return {number}
*/
function peek () {
return charat(characters, position)
}
/**
* @return {number}
*/
function caret () {
return position
}
/**
* @param {number} begin
* @param {number} end
* @return {string}
*/
function slice (begin, end) {
return substr(characters, begin, end)
}
/**
* @param {number} type
* @return {number}
*/
function token (type) {
switch (type) {
// \0 \t \n \r \s whitespace token
case 0: case 9: case 10: case 13: case 32:
return 5
// ! + , / > @ ~ isolate token
case 33: case 43: case 44: case 47: case 62: case 64: case 126:
// ; { } breakpoint token
case 59: case 123: case 125:
return 4
// : accompanied token
case 58:
return 3
// " ' ( [ opening delimit token
case 34: case 39: case 40: case 91:
return 2
// ) ] closing delimit token
case 41: case 93:
return 1
}
return 0
}
/**
* @param {string} value
* @return {any[]}
*/
function alloc (value) {
return line = column = 1, length = strlen(characters = value), position = 0, []
}
/**
* @param {any} value
* @return {any}
*/
function dealloc (value) {
return characters = '', value
}
/**
* @param {number} type
* @return {string}
*/
function delimit (type) {
return trim(slice(position - 1, delimiter(type === 91 ? type + 2 : type === 40 ? type + 1 : type)))
}
/**
* @param {number} type
* @return {string}
*/
function whitespace (type) {
while (character = peek())
if (character < 33)
next();
else
break
return token(type) > 2 || token(character) > 3 ? '' : ' '
}
/**
* @param {number} index
* @param {number} count
* @return {string}
*/
function escaping (index, count) {
while (--count && next())
// not 0-9 A-F a-f
if (character < 48 || character > 102 || (character > 57 && character < 65) || (character > 70 && character < 97))
break
return slice(index, caret() + (count < 6 && peek() == 32 && next() == 32))
}
/**
* @param {number} type
* @return {number}
*/
function delimiter (type) {
while (next())
switch (character) {
// ] ) " '
case type:
return position
// " '
case 34: case 39:
if (type !== 34 && type !== 39)
delimiter(character);
break
// (
case 40:
if (type === 41)
delimiter(type);
break
// \
case 92:
next();
break
}
return position
}
/**
* @param {number} type
* @param {number} index
* @return {number}
*/
function commenter (type, index) {
while (next())
// //
if (type + character === 47 + 10)
break
// /*
else if (type + character === 42 + 42 && peek() === 47)
break
return '/*' + slice(index, position - 1) + '*' + from(type === 47 ? type : next())
}
/**
* @param {number} index
* @return {string}
*/
function identifier (index) {
while (!token(peek()))
next();
return slice(index, position)
}
/**
* @param {string} value
* @return {object[]}
*/
function compile (value) {
return dealloc(parse('', null, null, null, [''], value = alloc(value), 0, [0], value))
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {string[]} rule
* @param {string[]} rules
* @param {string[]} rulesets
* @param {number[]} pseudo
* @param {number[]} points
* @param {string[]} declarations
* @return {object}
*/
function parse (value, root, parent, rule, rules, rulesets, pseudo, points, declarations) {
var index = 0;
var offset = 0;
var length = pseudo;
var atrule = 0;
var property = 0;
var previous = 0;
var variable = 1;
var scanning = 1;
var ampersand = 1;
var character = 0;
var type = '';
var props = rules;
var children = rulesets;
var reference = rule;
var characters = type;
while (scanning)
switch (previous = character, character = next()) {
// (
case 40:
if (previous != 108 && charat(characters, length - 1) == 58) {
if (indexof(characters += replace(delimit(character), '&', '&\f'), '&\f') != -1)
ampersand = -1;
break
}
// " ' [
case 34: case 39: case 91:
characters += delimit(character);
break
// \t \n \r \s
case 9: case 10: case 13: case 32:
characters += whitespace(previous);
break
// \
case 92:
characters += escaping(caret() - 1, 7);
continue
// /
case 47:
switch (peek()) {
case 42: case 47:
append(comment(commenter(next(), caret()), root, parent), declarations);
break
default:
characters += '/';
}
break
// {
case 123 * variable:
points[index++] = strlen(characters) * ampersand;
// } ; \0
case 125 * variable: case 59: case 0:
switch (character) {
// \0 }
case 0: case 125: scanning = 0;
// ;
case 59 + offset: if (ampersand == -1) characters = replace(characters, /\f/g, '');
if (property > 0 && (strlen(characters) - length))
append(property > 32 ? declaration(characters + ';', rule, parent, length - 1) : declaration(replace(characters, ' ', '') + ';', rule, parent, length - 2), declarations);
break
// @ ;
case 59: characters += ';';
// { rule/at-rule
default:
append(reference = ruleset(characters, root, parent, index, offset, rules, points, type, props = [], children = [], length), rulesets);
if (character === 123)
if (offset === 0)
parse(characters, root, reference, reference, props, rulesets, length, points, children);
else
switch (atrule === 99 && charat(characters, 3) === 110 ? 100 : atrule) {
// d l m s
case 100: case 108: case 109: case 115:
parse(value, reference, reference, rule && append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length), children), rules, children, length, points, rule ? props : children);
break
default:
parse(characters, reference, reference, reference, [''], children, 0, points, children);
}
}
index = offset = property = 0, variable = ampersand = 1, type = characters = '', length = pseudo;
break
// :
case 58:
length = 1 + strlen(characters), property = previous;
default:
if (variable < 1)
if (character == 123)
--variable;
else if (character == 125 && variable++ == 0 && prev() == 125)
continue
switch (characters += from(character), character * variable) {
// &
case 38:
ampersand = offset > 0 ? 1 : (characters += '\f', -1);
break
// ,
case 44:
points[index++] = (strlen(characters) - 1) * ampersand, ampersand = 1;
break
// @
case 64:
// -
if (peek() === 45)
characters += delimit(next());
atrule = peek(), offset = length = strlen(type = characters += identifier(caret())), character++;
break
// -
case 45:
if (previous === 45 && strlen(characters) == 2)
variable = 0;
}
}
return rulesets
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {number} index
* @param {number} offset
* @param {string[]} rules
* @param {number[]} points
* @param {string} type
* @param {string[]} props
* @param {string[]} children
* @param {number} length
* @return {object}
*/
function ruleset (value, root, parent, index, offset, rules, points, type, props, children, length) {
var post = offset - 1;
var rule = offset === 0 ? rules : [''];
var size = sizeof(rule);
for (var i = 0, j = 0, k = 0; i < index; ++i)
for (var x = 0, y = substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x)
if (z = trim(j > 0 ? rule[x] + ' ' + y : replace(y, /&\f/g, rule[x])))
props[k++] = z;
return node(value, root, parent, offset === 0 ? RULESET : type, props, children, length)
}
/**
* @param {number} value
* @param {object} root
* @param {object?} parent
* @return {object}
*/
function comment (value, root, parent) {
return node(value, root, parent, COMMENT, from(char()), substr(value, 2, -2), 0)
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {number} length
* @return {object}
*/
function declaration (value, root, parent, length) {
return node(value, root, parent, DECLARATION, substr(value, 0, length), substr(value, length + 1, -1), length)
}
/**
* @param {object[]} children
* @param {function} callback
* @return {string}
*/
function serialize (children, callback) {
var output = '';
var length = sizeof(children);
for (var i = 0; i < length; i++)
output += callback(children[i], i, children, callback) || '';
return output
}
/**
* @param {object} element
* @param {number} index
* @param {object[]} children
* @param {function} callback
* @return {string}
*/
function stringify (element, index, children, callback) {
switch (element.type) {
case LAYER: if (element.children.length) break
case IMPORT: case DECLARATION: return element.return = element.return || element.value
case COMMENT: return ''
case KEYFRAMES: return element.return = element.value + '{' + serialize(element.children, callback) + '}'
case RULESET: element.value = element.props.join(',');
}
return strlen(children = serialize(element.children, callback)) ? element.return = element.value + '{' + children + '}' : ''
}
/**
* @param {function[]} collection
* @return {function}
*/
function middleware (collection) {
var length = sizeof(collection);
return function (element, index, children, callback) {
var output = '';
for (var i = 0; i < length; i++)
output += collection[i](element, index, children, callback) || '';
return output
}
}
/**
* @param {function} callback
* @return {function}
*/
function rulesheet (callback) {
return function (element) {
if (!element.root)
if (element = element.return)
callback(element);
}
}
function memoize$1(fn) {
var cache = Object.create(null);
return function (arg) {
if (cache[arg] === undefined) cache[arg] = fn(arg);
return cache[arg];
};
}
var identifierWithPointTracking$1 = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (token(character)) {
break;
}
next();
}
return slice(begin, position);
};
var toRules$1 = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (token(character)) {
case 0:
// &\f
if (character === 38 && peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking$1(position - 1, points, index);
break;
case 2:
parsed[index] += delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += from(character);
}
} while (character = next());
return parsed;
};
var getRules$1 = function getRules(value, points) {
return dealloc(toRules$1(alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements$1 = /* #__PURE__ */new WeakMap();
var compat$1 = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value;
var parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements$1.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements$1.set(element, true);
var points = [];
var rules = getRules$1(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel$1 = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
/* eslint-disable no-fallthrough */
function prefix$1(value, length) {
switch (hash$2(value, length)) {
// color-adjust
case 5103:
return WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return WEBKIT + value + MOZ + value + MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return WEBKIT + value + MS + value + value;
// order
case 6165:
return WEBKIT + value + MS + 'flex-' + value + value;
// align-items
case 5187:
return WEBKIT + value + replace(value, /(\w+).+(:[^]+)/, WEBKIT + 'box-$1$2' + MS + 'flex-$1$2') + value;
// align-self
case 5443:
return WEBKIT + value + MS + 'flex-item-' + replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return WEBKIT + value + MS + 'flex-line-pack' + replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return WEBKIT + value + MS + replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return WEBKIT + value + MS + replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return WEBKIT + 'box-' + replace(value, '-grow', '') + WEBKIT + value + MS + replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return WEBKIT + replace(value, /([^-])(transform)/g, '$1' + WEBKIT + '$2') + value;
// cursor
case 6187:
return replace(replace(replace(value, /(zoom-|grab)/, WEBKIT + '$1'), /(image-set)/, WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return replace(value, /(image-set\([^]*)/, WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return replace(replace(value, /(.+:)(flex-)?(.*)/, WEBKIT + 'box-pack:$3' + MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return replace(value, /(.+)-inline(.+)/, WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (strlen(value) - 1 - length > 6) switch (charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return replace(value, /(.+:)(.+)-([^]+)/, '$1' + WEBKIT + '$2-$3' + '$1' + MOZ + (charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~indexof(value, 'stretch') ? prefix$1(replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (charat(value, strlen(value) - 3 - (~indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return replace(value, ':', ':' + WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + WEBKIT + (charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + WEBKIT + '$2$3' + '$1' + MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (charat(value, length + 11)) {
// vertical-l(r)
case 114:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return WEBKIT + value + MS + value + value;
}
return value;
}
var prefixer$1 = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case DECLARATION:
element["return"] = prefix$1(element.value, element.length);
break;
case KEYFRAMES:
return serialize([copy(element, {
value: replace(element.value, '@', '@' + WEBKIT)
})], callback);
case RULESET:
if (element.length) return combine(element.props, function (value) {
switch (match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return serialize([copy(element, {
props: [replace(value, /:(read-\w+)/, ':' + MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return serialize([copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + WEBKIT + 'input-$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + MOZ + '$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var defaultStylisPlugins$1 = [prefixer$1];
var createCache$1 = function createCache(options) {
var key = options.key;
if (key === 'css') {
var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration
// document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
// note this very very intentionally targets all style elements regardless of the key to ensure
// that creating a cache works inside of render of a React component
Array.prototype.forEach.call(ssrStyles, function (node) {
// we want to only move elements which have a space in the data-emotion attribute value
// because that indicates that it is an Emotion 11 server-side rendered style elements
// while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector
// Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)
// so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles
// will not result in the Emotion 10 styles being destroyed
var dataEmotionAttribute = node.getAttribute('data-emotion');
if (dataEmotionAttribute.indexOf(' ') === -1) {
return;
}
document.head.appendChild(node);
node.setAttribute('data-s', '');
});
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins$1;
var inserted = {};
var container;
var nodesToHydrate = [];
{
container = options.container || document.head;
Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which
// means that the style elements we're looking at are only Emotion 11 server-rendered style elements
document.querySelectorAll("style[data-emotion^=\"" + key + " \"]"), function (node) {
var attrib = node.getAttribute("data-emotion").split(' ');
for (var i = 1; i < attrib.length; i++) {
inserted[attrib[i]] = true;
}
nodesToHydrate.push(node);
});
}
var _insert;
var omnipresentPlugins = [compat$1, removeLabel$1];
{
var currentSheet;
var finalizingPlugins = [stringify, rulesheet(function (rule) {
currentSheet.insert(rule);
})];
var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis = function stylis(styles) {
return serialize(compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
}
var cache = {
key: key,
sheet: new StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
var reactIs = {exports: {}};
var reactIs_production_min = {};
/**
* @license React
* 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 hasRequiredReactIs_production_min;
function requireReactIs_production_min () {
if (hasRequiredReactIs_production_min) return reactIs_production_min;
hasRequiredReactIs_production_min = 1;
var b=Symbol.for("react.element"),c=Symbol.for("react.portal"),d=Symbol.for("react.fragment"),e=Symbol.for("react.strict_mode"),f=Symbol.for("react.profiler"),g=Symbol.for("react.provider"),h=Symbol.for("react.context"),k=Symbol.for("react.server_context"),l=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),n=Symbol.for("react.suspense_list"),p=Symbol.for("react.memo"),q=Symbol.for("react.lazy"),t=Symbol.for("react.offscreen"),u;u=Symbol.for("react.module.reference");
function v(a){if("object"===typeof a&&null!==a){var r=a.$$typeof;switch(r){case b:switch(a=a.type,a){case d:case f:case e:case m:case n:return a;default:switch(a=a&&a.$$typeof,a){case k:case h:case l:case q:case p:case g:return a;default:return r}}case c:return r}}}reactIs_production_min.ContextConsumer=h;reactIs_production_min.ContextProvider=g;reactIs_production_min.Element=b;reactIs_production_min.ForwardRef=l;reactIs_production_min.Fragment=d;reactIs_production_min.Lazy=q;reactIs_production_min.Memo=p;reactIs_production_min.Portal=c;reactIs_production_min.Profiler=f;reactIs_production_min.StrictMode=e;reactIs_production_min.Suspense=m;
reactIs_production_min.SuspenseList=n;reactIs_production_min.isAsyncMode=function(){return false};reactIs_production_min.isConcurrentMode=function(){return false};reactIs_production_min.isContextConsumer=function(a){return v(a)===h};reactIs_production_min.isContextProvider=function(a){return v(a)===g};reactIs_production_min.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===b};reactIs_production_min.isForwardRef=function(a){return v(a)===l};reactIs_production_min.isFragment=function(a){return v(a)===d};reactIs_production_min.isLazy=function(a){return v(a)===q};reactIs_production_min.isMemo=function(a){return v(a)===p};
reactIs_production_min.isPortal=function(a){return v(a)===c};reactIs_production_min.isProfiler=function(a){return v(a)===f};reactIs_production_min.isStrictMode=function(a){return v(a)===e};reactIs_production_min.isSuspense=function(a){return v(a)===m};reactIs_production_min.isSuspenseList=function(a){return v(a)===n};
reactIs_production_min.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===d||a===f||a===e||a===m||a===n||a===t||"object"===typeof a&&null!==a&&(a.$$typeof===q||a.$$typeof===p||a.$$typeof===g||a.$$typeof===h||a.$$typeof===l||a.$$typeof===u||void 0!==a.getModuleId)?true:false};reactIs_production_min.typeOf=v;
return reactIs_production_min;
}
var hasRequiredReactIs;
function requireReactIs () {
if (hasRequiredReactIs) return reactIs.exports;
hasRequiredReactIs = 1;
{
reactIs.exports = requireReactIs_production_min();
}
return reactIs.exports;
}
var hoistNonReactStatics_cjs;
var hasRequiredHoistNonReactStatics_cjs;
function requireHoistNonReactStatics_cjs () {
if (hasRequiredHoistNonReactStatics_cjs) return hoistNonReactStatics_cjs;
hasRequiredHoistNonReactStatics_cjs = 1;
var reactIs = requireReactIs();
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var REACT_STATICS = {
childContextTypes: true,
contextType: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromError: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var FORWARD_REF_STATICS = {
'$$typeof': true,
render: true,
defaultProps: true,
displayName: true,
propTypes: true
};
var MEMO_STATICS = {
'$$typeof': true,
compare: true,
defaultProps: true,
displayName: true,
propTypes: true,
type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;
TYPE_STATICS[reactIs.Memo] = MEMO_STATICS;
function getStatics(component) {
// React v16.11 and below
if (reactIs.isMemo(component)) {
return MEMO_STATICS;
} // React v16.12 and above
return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') {
// don't hoist over string (html) components
if (objectPrototype) {
var inheritedComponent = getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype) {
hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
}
var keys = getOwnPropertyNames(sourceComponent);
if (getOwnPropertySymbols) {
keys = keys.concat(getOwnPropertySymbols(sourceComponent));
}
var targetStatics = getStatics(targetComponent);
var sourceStatics = getStatics(sourceComponent);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
try {
// Avoid failures from read-only properties
defineProperty(targetComponent, key, descriptor);
} catch (e) {}
}
}
}
return targetComponent;
}
hoistNonReactStatics_cjs = hoistNonReactStatics;
return hoistNonReactStatics_cjs;
}
requireHoistNonReactStatics_cjs();
var isBrowser = true;
function getRegisteredStyles(registered, registeredStyles, classNames) {
var rawClassName = '';
classNames.split(' ').forEach(function (className) {
if (registered[className] !== undefined) {
registeredStyles.push(registered[className] + ";");
} else if (className) {
rawClassName += className + " ";
}
});
return rawClassName;
}
var registerStyles = function registerStyles(cache, serialized, isStringTag) {
var className = cache.key + "-" + serialized.name;
if ( // we only need to add the styles to the registered cache if the
// class name could be used further down
// the tree but if it's a string tag, we know it won't
// so we don't have to add it to registered cache.
// this improves memory usage since we can avoid storing the whole style string
(isStringTag === false || // we need to always store it if we're in compat mode and
// in node since emotion-server relies on whether a style is in
// the registered cache to know whether a style is global or not
// also, note that this check will be dead code eliminated in the browser
isBrowser === false ) && cache.registered[className] === undefined) {
cache.registered[className] = serialized.styles;
}
};
var insertStyles = function insertStyles(cache, serialized, isStringTag) {
registerStyles(cache, serialized, isStringTag);
var className = cache.key + "-" + serialized.name;
if (cache.inserted[serialized.name] === undefined) {
var current = serialized;
do {
cache.insert(serialized === current ? "." + className : '', current, cache.sheet, true);
current = current.next;
} while (current !== undefined);
}
};
/* eslint-disable */
// Inspired by https://github.com/garycourt/murmurhash-js
// Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86
function murmur2(str) {
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
// const m = 0x5bd1e995;
// const r = 24;
// Initialize the hash
var h = 0; // Mix 4 bytes at a time into the hash
var k,
i = 0,
len = str.length;
for (; len >= 4; ++i, len -= 4) {
k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;
k =
/* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16);
k ^=
/* k >>> r: */
k >>> 24;
h =
/* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
} // Handle the last few bytes of the input array
switch (len) {
case 3:
h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
case 2:
h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
case 1:
h ^= str.charCodeAt(i) & 0xff;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
} // Do a few final mixes of the hash to ensure the last few
// bytes are well-incorporated.
h ^= h >>> 13;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
return ((h ^ h >>> 15) >>> 0).toString(36);
}
var unitlessKeys = {
animationIterationCount: 1,
aspectRatio: 1,
borderImageOutset: 1,
borderImageSlice: 1,
borderImageWidth: 1,
boxFlex: 1,
boxFlexGroup: 1,
boxOrdinalGroup: 1,
columnCount: 1,
columns: 1,
flex: 1,
flexGrow: 1,
flexPositive: 1,
flexShrink: 1,
flexNegative: 1,
flexOrder: 1,
gridRow: 1,
gridRowEnd: 1,
gridRowSpan: 1,
gridRowStart: 1,
gridColumn: 1,
gridColumnEnd: 1,
gridColumnSpan: 1,
gridColumnStart: 1,
msGridRow: 1,
msGridRowSpan: 1,
msGridColumn: 1,
msGridColumnSpan: 1,
fontWeight: 1,
lineHeight: 1,
opacity: 1,
order: 1,
orphans: 1,
scale: 1,
tabSize: 1,
widows: 1,
zIndex: 1,
zoom: 1,
WebkitLineClamp: 1,
// SVG-related properties
fillOpacity: 1,
floodOpacity: 1,
stopOpacity: 1,
strokeDasharray: 1,
strokeDashoffset: 1,
strokeMiterlimit: 1,
strokeOpacity: 1,
strokeWidth: 1
};
var hyphenateRegex = /[A-Z]|^ms/g;
var animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g;
var isCustomProperty = function isCustomProperty(property) {
return property.charCodeAt(1) === 45;
};
var isProcessableValue = function isProcessableValue(value) {
return value != null && typeof value !== 'boolean';
};
var processStyleName = /* #__PURE__ */memoize$1(function (styleName) {
return isCustomProperty(styleName) ? styleName : styleName.replace(hyphenateRegex, '-$&').toLowerCase();
});
var processStyleValue = function processStyleValue(key, value) {
switch (key) {
case 'animation':
case 'animationName':
{
if (typeof value === 'string') {
return value.replace(animationRegex, function (match, p1, p2) {
cursor = {
name: p1,
styles: p2,
next: cursor
};
return p1;
});
}
}
}
if (unitlessKeys[key] !== 1 && !isCustomProperty(key) && typeof value === 'number' && value !== 0) {
return value + 'px';
}
return value;
};
function handleInterpolation(mergedProps, registered, interpolation) {
if (interpolation == null) {
return '';
}
var componentSelector = interpolation;
if (componentSelector.__emotion_styles !== undefined) {
return componentSelector;
}
switch (typeof interpolation) {
case 'boolean':
{
return '';
}
case 'object':
{
var keyframes = interpolation;
if (keyframes.anim === 1) {
cursor = {
name: keyframes.name,
styles: keyframes.styles,
next: cursor
};
return keyframes.name;
}
var serializedStyles = interpolation;
if (serializedStyles.styles !== undefined) {
var next = serializedStyles.next;
if (next !== undefined) {
// not the most efficient thing ever but this is a pretty rare case
// and there will be very few iterations of this generally
while (next !== undefined) {
cursor = {
name: next.name,
styles: next.styles,
next: cursor
};
next = next.next;
}
}
var styles = serializedStyles.styles + ";";
return styles;
}
return createStringFromObject(mergedProps, registered, interpolation);
}
case 'function':
{
if (mergedProps !== undefined) {
var previousCursor = cursor;
var result = interpolation(mergedProps);
cursor = previousCursor;
return handleInterpolation(mergedProps, registered, result);
}
break;
}
} // finalize string values (regular strings and functions interpolated into css calls)
var asString = interpolation;
if (registered == null) {
return asString;
}
var cached = registered[asString];
return cached !== undefined ? cached : asString;
}
function createStringFromObject(mergedProps, registered, obj) {
var string = '';
if (Array.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
string += handleInterpolation(mergedProps, registered, obj[i]) + ";";
}
} else {
for (var key in obj) {
var value = obj[key];
if (typeof value !== 'object') {
var asString = value;
if (registered != null && registered[asString] !== undefined) {
string += key + "{" + registered[asString] + "}";
} else if (isProcessableValue(asString)) {
string += processStyleName(key) + ":" + processStyleValue(key, asString) + ";";
}
} else {
if (Array.isArray(value) && typeof value[0] === 'string' && (registered == null || registered[value[0]] === undefined)) {
for (var _i = 0; _i < value.length; _i++) {
if (isProcessableValue(value[_i])) {
string += processStyleName(key) + ":" + processStyleValue(key, value[_i]) + ";";
}
}
} else {
var interpolated = handleInterpolation(mergedProps, registered, value);
switch (key) {
case 'animation':
case 'animationName':
{
string += processStyleName(key) + ":" + interpolated + ";";
break;
}
default:
{
string += key + "{" + interpolated + "}";
}
}
}
}
}
}
return string;
}
var labelPattern = /label:\s*([^\s;{]+)\s*(;|$)/g; // this is the cursor for keyframes
// keyframes are stored on the SerializedStyles object as a linked list
var cursor;
function serializeStyles(args, registered, mergedProps) {
if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null && args[0].styles !== undefined) {
return args[0];
}
var stringMode = true;
var styles = '';
cursor = undefined;
var strings = args[0];
if (strings == null || strings.raw === undefined) {
stringMode = false;
styles += handleInterpolation(mergedProps, registered, strings);
} else {
var asTemplateStringsArr = strings;
styles += asTemplateStringsArr[0];
} // we start at 1 since we've already handled the first arg
for (var i = 1; i < args.length; i++) {
styles += handleInterpolation(mergedProps, registered, args[i]);
if (stringMode) {
var templateStringsArr = strings;
styles += templateStringsArr[i];
}
} // using a global regex with .exec is stateful so lastIndex has to be reset each time
labelPattern.lastIndex = 0;
var identifierName = '';
var match; // https://esbench.com/bench/5b809c2cf2949800a0f61fb5
while ((match = labelPattern.exec(styles)) !== null) {
identifierName += '-' + match[1];
}
var name = murmur2(styles) + identifierName;
return {
name: name,
styles: styles,
next: cursor
};
}
var syncFallback = function syncFallback(create) {
return create();
};
var useInsertionEffect = React$1['useInsertion' + 'Effect'] ? React$1['useInsertion' + 'Effect'] : false;
var useInsertionEffectAlwaysWithSyncFallback = useInsertionEffect || syncFallback;
var useInsertionEffectWithLayoutFallback = useInsertionEffect || reactExports.useLayoutEffect;
var EmotionCacheContext = /* #__PURE__ */reactExports.createContext( // we're doing this to avoid preconstruct's dead code elimination in this one case
// because this module is primarily intended for the browser and node
// but it's also required in react native and similar environments sometimes
// and we could have a special build just for that
// but this is much easier and the native packages
// might use a different theme context in the future anyway
typeof HTMLElement !== 'undefined' ? /* #__PURE__ */createCache$1({
key: 'css'
}) : null);
var CacheProvider = EmotionCacheContext.Provider;
var withEmotionCache = function withEmotionCache(func) {
return /*#__PURE__*/reactExports.forwardRef(function (props, ref) {
// the cache will never be null in the browser
var cache = reactExports.useContext(EmotionCacheContext);
return func(props, cache, ref);
});
};
var ThemeContext$1 = /* #__PURE__ */reactExports.createContext({});
var hasOwn = {}.hasOwnProperty;
var typePropName = '__EMOTION_TYPE_PLEASE_DO_NOT_USE__';
var createEmotionProps = function createEmotionProps(type, props) {
var newProps = {};
for (var _key in props) {
if (hasOwn.call(props, _key)) {
newProps[_key] = props[_key];
}
}
newProps[typePropName] = type; // Runtime labeling is an opt-in feature because:
return newProps;
};
var Insertion$1 = function Insertion(_ref) {
var cache = _ref.cache,
serialized = _ref.serialized,
isStringTag = _ref.isStringTag;
registerStyles(cache, serialized, isStringTag);
useInsertionEffectAlwaysWithSyncFallback(function () {
return insertStyles(cache, serialized, isStringTag);
});
return null;
};
var Emotion = /* #__PURE__ */withEmotionCache(function (props, cache, ref) {
var cssProp = props.css; // so that using `css` from `emotion` and passing the result to the css prop works
// not passing the registered cache to serializeStyles because it would
// make certain babel optimisations not possible
if (typeof cssProp === 'string' && cache.registered[cssProp] !== undefined) {
cssProp = cache.registered[cssProp];
}
var WrappedComponent = props[typePropName];
var registeredStyles = [cssProp];
var className = '';
if (typeof props.className === 'string') {
className = getRegisteredStyles(cache.registered, registeredStyles, props.className);
} else if (props.className != null) {
className = props.className + " ";
}
var serialized = serializeStyles(registeredStyles, undefined, reactExports.useContext(ThemeContext$1));
className += cache.key + "-" + serialized.name;
var newProps = {};
for (var _key2 in props) {
if (hasOwn.call(props, _key2) && _key2 !== 'css' && _key2 !== typePropName && (true )) {
newProps[_key2] = props[_key2];
}
}
newProps.className = className;
if (ref) {
newProps.ref = ref;
}
return /*#__PURE__*/reactExports.createElement(reactExports.Fragment, null, /*#__PURE__*/reactExports.createElement(Insertion$1, {
cache: cache,
serialized: serialized,
isStringTag: typeof WrappedComponent === 'string'
}), /*#__PURE__*/reactExports.createElement(WrappedComponent, newProps));
});
var Emotion$1 = Emotion;
var jsx = function jsx(type, props) {
// eslint-disable-next-line prefer-rest-params
var args = arguments;
if (props == null || !hasOwn.call(props, 'css')) {
return reactExports.createElement.apply(undefined, args);
}
var argsLength = args.length;
var createElementArgArray = new Array(argsLength);
createElementArgArray[0] = Emotion$1;
createElementArgArray[1] = createEmotionProps(type, props);
for (var i = 2; i < argsLength; i++) {
createElementArgArray[i] = args[i];
}
return reactExports.createElement.apply(null, createElementArgArray);
};
(function (_jsx) {
var JSX;
(function (_JSX) {})(JSX || (JSX = _jsx.JSX || (_jsx.JSX = {})));
})(jsx || (jsx = {}));
// initial render from browser, insertBefore context.sheet.tags[0] or if a style hasn't been inserted there yet, appendChild
// initial client-side render from SSR, use place of hydrating tag
var Global = /* #__PURE__ */withEmotionCache(function (props, cache) {
var styles = props.styles;
var serialized = serializeStyles([styles], undefined, reactExports.useContext(ThemeContext$1));
// but it is based on a constant that will never change at runtime
// it's effectively like having two implementations and switching them out
// so it's not actually breaking anything
var sheetRef = reactExports.useRef();
useInsertionEffectWithLayoutFallback(function () {
var key = cache.key + "-global"; // use case of https://github.com/emotion-js/emotion/issues/2675
var sheet = new cache.sheet.constructor({
key: key,
nonce: cache.sheet.nonce,
container: cache.sheet.container,
speedy: cache.sheet.isSpeedy
});
var rehydrating = false;
var node = document.querySelector("style[data-emotion=\"" + key + " " + serialized.name + "\"]");
if (cache.sheet.tags.length) {
sheet.before = cache.sheet.tags[0];
}
if (node !== null) {
rehydrating = true; // clear the hash so this node won't be recognizable as rehydratable by other <Global/>s
node.setAttribute('data-emotion', key);
sheet.hydrate([node]);
}
sheetRef.current = [sheet, rehydrating];
return function () {
sheet.flush();
};
}, [cache]);
useInsertionEffectWithLayoutFallback(function () {
var sheetRefCurrent = sheetRef.current;
var sheet = sheetRefCurrent[0],
rehydrating = sheetRefCurrent[1];
if (rehydrating) {
sheetRefCurrent[1] = false;
return;
}
if (serialized.next !== undefined) {
// insert keyframes
insertStyles(cache, serialized.next, true);
}
if (sheet.tags.length) {
// if this doesn't exist then it will be null so the style element will be appended
var element = sheet.tags[sheet.tags.length - 1].nextElementSibling;
sheet.before = element;
sheet.flush();
}
cache.insert("", serialized, sheet, false);
}, [cache, serialized.name]);
return null;
});
function css() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return serializeStyles(args);
}
function keyframes() {
var insertable = css.apply(void 0, arguments);
var name = "animation-" + insertable.name;
return {
name: name,
styles: "@keyframes " + name + "{" + insertable.styles + "}",
anim: 1,
toString: function toString() {
return "_EMO_" + this.name + "_" + this.styles + "_EMO_";
}
};
}
// eslint-disable-next-line no-undef
var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|disableRemotePlayback|download|draggable|encType|enterKeyHint|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23
var isPropValid = /* #__PURE__ */memoize$1(function (prop) {
return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111
/* o */
&& prop.charCodeAt(1) === 110
/* n */
&& prop.charCodeAt(2) < 91;
}
/* Z+1 */
);
var testOmitPropsOnStringTag = isPropValid;
var testOmitPropsOnComponent = function testOmitPropsOnComponent(key) {
return key !== 'theme';
};
var getDefaultShouldForwardProp = function getDefaultShouldForwardProp(tag) {
return typeof tag === 'string' && // 96 is one less than the char code
// for "a" so this is checking that
// it's a lowercase character
tag.charCodeAt(0) > 96 ? testOmitPropsOnStringTag : testOmitPropsOnComponent;
};
var composeShouldForwardProps = function composeShouldForwardProps(tag, options, isReal) {
var shouldForwardProp;
if (options) {
var optionsShouldForwardProp = options.shouldForwardProp;
shouldForwardProp = tag.__emotion_forwardProp && optionsShouldForwardProp ? function (propName) {
return tag.__emotion_forwardProp(propName) && optionsShouldForwardProp(propName);
} : optionsShouldForwardProp;
}
if (typeof shouldForwardProp !== 'function' && isReal) {
shouldForwardProp = tag.__emotion_forwardProp;
}
return shouldForwardProp;
};
var Insertion = function Insertion(_ref) {
var cache = _ref.cache,
serialized = _ref.serialized,
isStringTag = _ref.isStringTag;
registerStyles(cache, serialized, isStringTag);
useInsertionEffectAlwaysWithSyncFallback(function () {
return insertStyles(cache, serialized, isStringTag);
});
return null;
};
var createStyled$1 = function createStyled(tag, options) {
var isReal = tag.__emotion_real === tag;
var baseTag = isReal && tag.__emotion_base || tag;
var identifierName;
var targetClassName;
if (options !== undefined) {
identifierName = options.label;
targetClassName = options.target;
}
var shouldForwardProp = composeShouldForwardProps(tag, options, isReal);
var defaultShouldForwardProp = shouldForwardProp || getDefaultShouldForwardProp(baseTag);
var shouldUseAs = !defaultShouldForwardProp('as');
return function () {
// eslint-disable-next-line prefer-rest-params
var args = arguments;
var styles = isReal && tag.__emotion_styles !== undefined ? tag.__emotion_styles.slice(0) : [];
if (identifierName !== undefined) {
styles.push("label:" + identifierName + ";");
}
if (args[0] == null || args[0].raw === undefined) {
// eslint-disable-next-line prefer-spread
styles.push.apply(styles, args);
} else {
var templateStringsArr = args[0];
styles.push(templateStringsArr[0]);
var len = args.length;
var i = 1;
for (; i < len; i++) {
styles.push(args[i], templateStringsArr[i]);
}
}
var Styled = withEmotionCache(function (props, cache, ref) {
var FinalTag = shouldUseAs && props.as || baseTag;
var className = '';
var classInterpolations = [];
var mergedProps = props;
if (props.theme == null) {
mergedProps = {};
for (var key in props) {
mergedProps[key] = props[key];
}
mergedProps.theme = reactExports.useContext(ThemeContext$1);
}
if (typeof props.className === 'string') {
className = getRegisteredStyles(cache.registered, classInterpolations, props.className);
} else if (props.className != null) {
className = props.className + " ";
}
var serialized = serializeStyles(styles.concat(classInterpolations), cache.registered, mergedProps);
className += cache.key + "-" + serialized.name;
if (targetClassName !== undefined) {
className += " " + targetClassName;
}
var finalShouldForwardProp = shouldUseAs && shouldForwardProp === undefined ? getDefaultShouldForwardProp(FinalTag) : defaultShouldForwardProp;
var newProps = {};
for (var _key in props) {
if (shouldUseAs && _key === 'as') continue;
if (finalShouldForwardProp(_key)) {
newProps[_key] = props[_key];
}
}
newProps.className = className;
if (ref) {
newProps.ref = ref;
}
return /*#__PURE__*/reactExports.createElement(reactExports.Fragment, null, /*#__PURE__*/reactExports.createElement(Insertion, {
cache: cache,
serialized: serialized,
isStringTag: typeof FinalTag === 'string'
}), /*#__PURE__*/reactExports.createElement(FinalTag, newProps));
});
Styled.displayName = identifierName !== undefined ? identifierName : "Styled(" + (typeof baseTag === 'string' ? baseTag : baseTag.displayName || baseTag.name || 'Component') + ")";
Styled.defaultProps = tag.defaultProps;
Styled.__emotion_real = Styled;
Styled.__emotion_base = baseTag;
Styled.__emotion_styles = styles;
Styled.__emotion_forwardProp = shouldForwardProp;
Object.defineProperty(Styled, 'toString', {
value: function value() {
return "." + targetClassName;
}
});
Styled.withComponent = function (nextTag, nextOptions) {
var newStyled = createStyled(nextTag, _extends({}, options, nextOptions, {
shouldForwardProp: composeShouldForwardProps(Styled, nextOptions, true)
}));
return newStyled.apply(void 0, styles);
};
return Styled;
};
};
var tags = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG
'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan'];
// bind it to avoid mutating the original function
var styled$2 = createStyled$1.bind(null);
tags.forEach(function (tagName) {
styled$2[tagName] = styled$2(tagName);
});
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (token(character)) {
break;
}
next();
}
return slice(begin, position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (token(character)) {
case 0:
// &\f
if (character === 38 && peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(position - 1, points, index);
break;
case 2:
parsed[index] += delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += from(character);
}
} while (character = next());
return parsed;
};
var getRules = function getRules(value, points) {
return dealloc(toRules(alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value,
parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
/* eslint-disable no-fallthrough */
function prefix(value, length) {
switch (hash$2(value, length)) {
// color-adjust
case 5103:
return WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return WEBKIT + value + MOZ + value + MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return WEBKIT + value + MS + value + value;
// order
case 6165:
return WEBKIT + value + MS + 'flex-' + value + value;
// align-items
case 5187:
return WEBKIT + value + replace(value, /(\w+).+(:[^]+)/, WEBKIT + 'box-$1$2' + MS + 'flex-$1$2') + value;
// align-self
case 5443:
return WEBKIT + value + MS + 'flex-item-' + replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return WEBKIT + value + MS + 'flex-line-pack' + replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return WEBKIT + value + MS + replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return WEBKIT + value + MS + replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return WEBKIT + 'box-' + replace(value, '-grow', '') + WEBKIT + value + MS + replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return WEBKIT + replace(value, /([^-])(transform)/g, '$1' + WEBKIT + '$2') + value;
// cursor
case 6187:
return replace(replace(replace(value, /(zoom-|grab)/, WEBKIT + '$1'), /(image-set)/, WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return replace(value, /(image-set\([^]*)/, WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return replace(replace(value, /(.+:)(flex-)?(.*)/, WEBKIT + 'box-pack:$3' + MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return replace(value, /(.+)-inline(.+)/, WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (strlen(value) - 1 - length > 6) switch (charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return replace(value, /(.+:)(.+)-([^]+)/, '$1' + WEBKIT + '$2-$3' + '$1' + MOZ + (charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~indexof(value, 'stretch') ? prefix(replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (charat(value, strlen(value) - 3 - (~indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return replace(value, ':', ':' + WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + WEBKIT + (charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + WEBKIT + '$2$3' + '$1' + MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (charat(value, length + 11)) {
// vertical-l(r)
case 114:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return WEBKIT + value + MS + value + value;
}
return value;
}
var prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case DECLARATION:
element["return"] = prefix(element.value, element.length);
break;
case KEYFRAMES:
return serialize([copy(element, {
value: replace(element.value, '@', '@' + WEBKIT)
})], callback);
case RULESET:
if (element.length) return combine(element.props, function (value) {
switch (match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return serialize([copy(element, {
props: [replace(value, /:(read-\w+)/, ':' + MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return serialize([copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + WEBKIT + 'input-$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, ':' + MOZ + '$1')]
}), copy(element, {
props: [replace(value, /:(plac\w+)/, MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var defaultStylisPlugins = [prefixer];
var createCache = function
/*: EmotionCache */
createCache(options
/*: Options */
) {
var key = options.key;
if (key === 'css') {
var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration
// document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
// note this very very intentionally targets all style elements regardless of the key to ensure
// that creating a cache works inside of render of a React component
Array.prototype.forEach.call(ssrStyles, function (node
/*: HTMLStyleElement */
) {
// we want to only move elements which have a space in the data-emotion attribute value
// because that indicates that it is an Emotion 11 server-side rendered style elements
// while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector
// Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)
// so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles
// will not result in the Emotion 10 styles being destroyed
var dataEmotionAttribute = node.getAttribute('data-emotion');
if (dataEmotionAttribute.indexOf(' ') === -1) {
return;
}
document.head.appendChild(node);
node.setAttribute('data-s', '');
});
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
var inserted = {};
var container;
/* : Node */
var nodesToHydrate = [];
{
container = options.container || document.head;
Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which
// means that the style elements we're looking at are only Emotion 11 server-rendered style elements
document.querySelectorAll("style[data-emotion^=\"" + key + " \"]"), function (node
/*: HTMLStyleElement */
) {
var attrib = node.getAttribute("data-emotion").split(' ');
for (var i = 1; i < attrib.length; i++) {
inserted[attrib[i]] = true;
}
nodesToHydrate.push(node);
});
}
var _insert;
/*: (
selector: string,
serialized: SerializedStyles,
sheet: StyleSheet,
shouldCache: boolean
) => string | void */
var omnipresentPlugins = [compat, removeLabel];
{
var currentSheet;
var finalizingPlugins = [stringify, rulesheet(function (rule) {
currentSheet.insert(rule);
})];
var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis = function stylis(styles) {
return serialize(compile(styles), serializer);
};
_insert = function
/*: void */
insert(selector
/*: string */
, serialized
/*: SerializedStyles */
, sheet
/*: StyleSheet */
, shouldCache
/*: boolean */
) {
currentSheet = sheet;
stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
}
var cache
/*: EmotionCache */
= {
key: key,
sheet: new StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
var jsxRuntime = {exports: {}};
var reactJsxRuntime_production_min = {};
/**
* @license React
* react-jsx-runtime.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 hasRequiredReactJsxRuntime_production_min;
function requireReactJsxRuntime_production_min () {
if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min;
hasRequiredReactJsxRuntime_production_min = 1;
var f=requireReact(),k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:true,ref:true,__self:true,__source:true};
function q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=""+g);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a) void 0===d[b]&&(d[b]=a[b]);return {$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}reactJsxRuntime_production_min.Fragment=l;reactJsxRuntime_production_min.jsx=q;reactJsxRuntime_production_min.jsxs=q;
return reactJsxRuntime_production_min;
}
var hasRequiredJsxRuntime;
function requireJsxRuntime () {
if (hasRequiredJsxRuntime) return jsxRuntime.exports;
hasRequiredJsxRuntime = 1;
{
jsxRuntime.exports = requireReactJsxRuntime_production_min();
}
return jsxRuntime.exports;
}
var jsxRuntimeExports = requireJsxRuntime();
const cacheMap = new Map();
// We might be able to remove this when this issue is fixed:
// https://github.com/emotion-js/emotion/issues/2790
const createEmotionCache = (options, CustomSheet) => {
const cache = createCache(options);
// Do the same as https://github.com/emotion-js/emotion/blob/main/packages/cache/src/index.js#L238-L245
cache.sheet = new CustomSheet({
key: cache.key,
nonce: cache.sheet.nonce,
container: cache.sheet.container,
speedy: cache.sheet.isSpeedy,
prepend: cache.sheet.prepend,
insertionPoint: cache.sheet.insertionPoint
});
return cache;
};
let insertionPoint;
if (typeof document === 'object') {
// Use `insertionPoint` over `prepend`(deprecated) because it can be controlled for GlobalStyles injection order
// For more information, see https://github.com/mui/material-ui/issues/44597
insertionPoint = document.querySelector('[name="emotion-insertion-point"]');
if (!insertionPoint) {
insertionPoint = document.createElement('meta');
insertionPoint.setAttribute('name', 'emotion-insertion-point');
insertionPoint.setAttribute('content', '');
const head = document.querySelector('head');
if (head) {
head.prepend(insertionPoint);
}
}
}
function getCache(injectFirst, enableCssLayer) {
if (injectFirst || enableCssLayer) {
/**
* This is for client-side apps only.
* A custom sheet is required to make the GlobalStyles API injected above the insertion point.
* This is because the [sheet](https://github.com/emotion-js/emotion/blob/main/packages/react/src/global.js#L94-L99) does not consume the options.
*/
class MyStyleSheet extends StyleSheet {
insert(rule, options) {
if (this.key && this.key.endsWith('global')) {
this.before = insertionPoint;
}
return super.insert(rule, options);
}
}
const emotionCache = createEmotionCache({
key: 'css',
insertionPoint: injectFirst ? insertionPoint : undefined
}, MyStyleSheet);
if (enableCssLayer) {
const prevInsert = emotionCache.insert;
emotionCache.insert = (...args) => {
if (!args[1].styles.match(/^@layer\s+[^{]*$/)) {
// avoid nested @layer
args[1].styles = `@layer mui {${args[1].styles}}`;
}
return prevInsert(...args);
};
}
return emotionCache;
}
return undefined;
}
function StyledEngineProvider(props) {
const {
injectFirst,
enableCssLayer,
children
} = props;
const cache = reactExports.useMemo(() => {
const cacheKey = `${injectFirst}-${enableCssLayer}`;
if (typeof document === 'object' && cacheMap.has(cacheKey)) {
return cacheMap.get(cacheKey);
}
const fresh = getCache(injectFirst, enableCssLayer);
cacheMap.set(cacheKey, fresh);
return fresh;
}, [injectFirst, enableCssLayer]);
return cache ? /*#__PURE__*/jsxRuntimeExports.jsx(CacheProvider, {
value: cache,
children: children
}) : children;
}
function isEmpty$2(obj) {
return obj === undefined || obj === null || Object.keys(obj).length === 0;
}
function GlobalStyles$2(props) {
const {
styles,
defaultTheme = {}
} = props;
const globalStyles = typeof styles === 'function' ? themeInput => styles(isEmpty$2(themeInput) ? defaultTheme : themeInput) : styles;
return /*#__PURE__*/jsxRuntimeExports.jsx(Global, {
styles: globalStyles
});
}
/**
* @mui/styled-engine v6.5.0
*
* @license MIT
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable no-underscore-dangle */
function styled$1(tag, options) {
const stylesFactory = styled$2(tag, options);
return stylesFactory;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
function internal_mutateStyles(tag, processor) {
// Emotion attaches all the styles as `__emotion_styles`.
// Ref: https://github.com/emotion-js/emotion/blob/16d971d0da229596d6bcc39d282ba9753c9ee7cf/packages/styled/src/base.js#L186
if (Array.isArray(tag.__emotion_styles)) {
tag.__emotion_styles = processor(tag.__emotion_styles);
}
}
// Emotion only accepts an array, but we want to avoid allocations
const wrapper = [];
// eslint-disable-next-line @typescript-eslint/naming-convention
function internal_serializeStyles(styles) {
wrapper[0] = styles;
return serializeStyles(wrapper);
}
var reactIsExports = requireReactIs();
// https://github.com/sindresorhus/is-plain-obj/blob/main/index.js
function isPlainObject(item) {
if (typeof item !== 'object' || item === null) {
return false;
}
const prototype = Object.getPrototypeOf(item);
return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in item) && !(Symbol.iterator in item);
}
function deepClone(source) {
if (/*#__PURE__*/reactExports.isValidElement(source) || reactIsExports.isValidElementType(source) || !isPlainObject(source)) {
return source;
}
const output = {};
Object.keys(source).forEach(key => {
output[key] = deepClone(source[key]);
});
return output;
}
/**
* Merge objects deeply.
* It will shallow copy React elements.
*
* If `options.clone` is set to `false` the source object will be merged directly into the target object.
*
* @example
* ```ts
* deepmerge({ a: { b: 1 }, d: 2 }, { a: { c: 2 }, d: 4 });
* // => { a: { b: 1, c: 2 }, d: 4 }
* ````
*
* @param target The target object.
* @param source The source object.
* @param options The merge options.
* @param options.clone Set to `false` to merge the source object directly into the target object.
* @returns The merged object.
*/
function deepmerge(target, source, options = {
clone: true
}) {
const output = options.clone ? {
...target
} : target;
if (isPlainObject(target) && isPlainObject(source)) {
Object.keys(source).forEach(key => {
if (/*#__PURE__*/reactExports.isValidElement(source[key]) || reactIsExports.isValidElementType(source[key])) {
output[key] = source[key];
} else if (isPlainObject(source[key]) &&
// Avoid prototype pollution
Object.prototype.hasOwnProperty.call(target, key) && isPlainObject(target[key])) {
// Since `output` is a clone of `target` and we have narrowed `target` in this block we can cast to the same type.
output[key] = deepmerge(target[key], source[key], options);
} else if (options.clone) {
output[key] = isPlainObject(source[key]) ? deepClone(source[key]) : source[key];
} else {
output[key] = source[key];
}
});
}
return output;
}
// Sorted ASC by size. That's important.
// It can't be configured as it's used statically for propTypes.
const sortBreakpointsValues = values => {
const breakpointsAsArray = Object.keys(values).map(key => ({
key,
val: values[key]
})) || [];
// Sort in ascending order
breakpointsAsArray.sort((breakpoint1, breakpoint2) => breakpoint1.val - breakpoint2.val);
return breakpointsAsArray.reduce((acc, obj) => {
return {
...acc,
[obj.key]: obj.val
};
}, {});
};
// Keep in mind that @media is inclusive by the CSS specification.
function createBreakpoints(breakpoints) {
const {
// The breakpoint **start** at this value.
// For instance with the first breakpoint xs: [xs, sm).
values = {
xs: 0,
// phone
sm: 600,
// tablet
md: 900,
// small laptop
lg: 1200,
// desktop
xl: 1536 // large screen
},
unit = 'px',
step = 5,
...other
} = breakpoints;
const sortedValues = sortBreakpointsValues(values);
const keys = Object.keys(sortedValues);
function up(key) {
const value = typeof values[key] === 'number' ? values[key] : key;
return `@media (min-width:${value}${unit})`;
}
function down(key) {
const value = typeof values[key] === 'number' ? values[key] : key;
return `@media (max-width:${value - step / 100}${unit})`;
}
function between(start, end) {
const endIndex = keys.indexOf(end);
return `@media (min-width:${typeof values[start] === 'number' ? values[start] : start}${unit}) and ` + `(max-width:${(endIndex !== -1 && typeof values[keys[endIndex]] === 'number' ? values[keys[endIndex]] : end) - step / 100}${unit})`;
}
function only(key) {
if (keys.indexOf(key) + 1 < keys.length) {
return between(key, keys[keys.indexOf(key) + 1]);
}
return up(key);
}
function not(key) {
// handle first and last key separately, for better readability
const keyIndex = keys.indexOf(key);
if (keyIndex === 0) {
return up(keys[1]);
}
if (keyIndex === keys.length - 1) {
return down(keys[keyIndex]);
}
return between(key, keys[keys.indexOf(key) + 1]).replace('@media', '@media not all and');
}
return {
keys,
values: sortedValues,
up,
down,
between,
only,
not,
unit,
...other
};
}
/**
* For using in `sx` prop to sort the breakpoint from low to high.
* Note: this function does not work and will not support multiple units.
* e.g. input: { '@container (min-width:300px)': '1rem', '@container (min-width:40rem)': '2rem' }
* output: { '@container (min-width:40rem)': '2rem', '@container (min-width:300px)': '1rem' } // since 40 < 300 eventhough 40rem > 300px
*/
function sortContainerQueries(theme, css) {
if (!theme.containerQueries) {
return css;
}
const sorted = Object.keys(css).filter(key => key.startsWith('@container')).sort((a, b) => {
const regex = /min-width:\s*([0-9.]+)/;
return +(a.match(regex)?.[1] || 0) - +(b.match(regex)?.[1] || 0);
});
if (!sorted.length) {
return css;
}
return sorted.reduce((acc, key) => {
const value = css[key];
delete acc[key];
acc[key] = value;
return acc;
}, {
...css
});
}
function isCqShorthand(breakpointKeys, value) {
return value === '@' || value.startsWith('@') && (breakpointKeys.some(key => value.startsWith(`@${key}`)) || !!value.match(/^@\d/));
}
function getContainerQuery(theme, shorthand) {
const matches = shorthand.match(/^@([^/]+)?\/?(.+)?$/);
if (!matches) {
return null;
}
const [, containerQuery, containerName] = matches;
const value = Number.isNaN(+containerQuery) ? containerQuery || 0 : +containerQuery;
return theme.containerQueries(containerName).up(value);
}
function cssContainerQueries(themeInput) {
const toContainerQuery = (mediaQuery, name) => mediaQuery.replace('@media', name ? `@container ${name}` : '@container');
function attachCq(node, name) {
node.up = (...args) => toContainerQuery(themeInput.breakpoints.up(...args), name);
node.down = (...args) => toContainerQuery(themeInput.breakpoints.down(...args), name);
node.between = (...args) => toContainerQuery(themeInput.breakpoints.between(...args), name);
node.only = (...args) => toContainerQuery(themeInput.breakpoints.only(...args), name);
node.not = (...args) => {
const result = toContainerQuery(themeInput.breakpoints.not(...args), name);
if (result.includes('not all and')) {
// `@container` does not work with `not all and`, so need to invert the logic
return result.replace('not all and ', '').replace('min-width:', 'width<').replace('max-width:', 'width>').replace('and', 'or');
}
return result;
};
}
const node = {};
const containerQueries = name => {
attachCq(node, name);
return node;
};
attachCq(containerQueries);
return {
...themeInput,
containerQueries
};
}
const shape = {
borderRadius: 4
};
function merge(acc, item) {
if (!item) {
return acc;
}
return deepmerge(acc, item, {
clone: false // No need to clone deep, it's way faster.
});
}
// The breakpoint **start** at this value.
// For instance with the first breakpoint xs: [xs, sm[.
const values$1 = {
xs: 0,
// phone
sm: 600,
// tablet
md: 900,
// small laptop
lg: 1200,
// desktop
xl: 1536 // large screen
};
const 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: key => `@media (min-width:${values$1[key]}px)`
};
const defaultContainerQueries = {
containerQueries: containerName => ({
up: key => {
let result = typeof key === 'number' ? key : values$1[key] || key;
if (typeof result === 'number') {
result = `${result}px`;
}
return containerName ? `@container ${containerName} (min-width:${result})` : `@container (min-width:${result})`;
}
})
};
function handleBreakpoints(props, propValue, styleFromPropValue) {
const theme = props.theme || {};
if (Array.isArray(propValue)) {
const themeBreakpoints = theme.breakpoints || defaultBreakpoints;
return propValue.reduce((acc, item, index) => {
acc[themeBreakpoints.up(themeBreakpoints.keys[index])] = styleFromPropValue(propValue[index]);
return acc;
}, {});
}
if (typeof propValue === 'object') {
const themeBreakpoints = theme.breakpoints || defaultBreakpoints;
return Object.keys(propValue).reduce((acc, breakpoint) => {
if (isCqShorthand(themeBreakpoints.keys, breakpoint)) {
const containerKey = getContainerQuery(theme.containerQueries ? theme : defaultContainerQueries, breakpoint);
if (containerKey) {
acc[containerKey] = styleFromPropValue(propValue[breakpoint], breakpoint);
}
}
// key is breakpoint
else if (Object.keys(themeBreakpoints.values || values$1).includes(breakpoint)) {
const mediaKey = themeBreakpoints.up(breakpoint);
acc[mediaKey] = styleFromPropValue(propValue[breakpoint], breakpoint);
} else {
const cssKey = breakpoint;
acc[cssKey] = propValue[cssKey];
}
return acc;
}, {});
}
const output = styleFromPropValue(propValue);
return output;
}
function createEmptyBreakpointObject(breakpointsInput = {}) {
const breakpointsInOrder = breakpointsInput.keys?.reduce((acc, key) => {
const breakpointStyleKey = breakpointsInput.up(key);
acc[breakpointStyleKey] = {};
return acc;
}, {});
return breakpointsInOrder || {};
}
function removeUnusedBreakpoints(breakpointKeys, style) {
return breakpointKeys.reduce((acc, key) => {
const breakpointOutput = acc[key];
const isBreakpointUnused = !breakpointOutput || Object.keys(breakpointOutput).length === 0;
if (isBreakpointUnused) {
delete acc[key];
}
return acc;
}, style);
}
// compute base for responsive values; e.g.,
// [1,2,3] => {xs: true, sm: true, md: true}
// {xs: 1, sm: 2, md: 3} => {xs: true, sm: true, md: true}
function computeBreakpointsBase(breakpointValues, themeBreakpoints) {
// fixed value
if (typeof breakpointValues !== 'object') {
return {};
}
const base = {};
const breakpointsKeys = Object.keys(themeBreakpoints);
if (Array.isArray(breakpointValues)) {
breakpointsKeys.forEach((breakpoint, i) => {
if (i < breakpointValues.length) {
base[breakpoint] = true;
}
});
} else {
breakpointsKeys.forEach(breakpoint => {
if (breakpointValues[breakpoint] != null) {
base[breakpoint] = true;
}
});
}
return base;
}
function resolveBreakpointValues({
values: breakpointValues,
breakpoints: themeBreakpoints,
base: customBase
}) {
const base = customBase || computeBreakpointsBase(breakpointValues, themeBreakpoints);
const keys = Object.keys(base);
if (keys.length === 0) {
return breakpointValues;
}
let previous;
return keys.reduce((acc, breakpoint, i) => {
if (Array.isArray(breakpointValues)) {
acc[breakpoint] = breakpointValues[i] != null ? breakpointValues[i] : breakpointValues[previous];
previous = i;
} else if (typeof breakpointValues === 'object') {
acc[breakpoint] = breakpointValues[breakpoint] != null ? breakpointValues[breakpoint] : breakpointValues[previous];
previous = breakpoint;
} else {
acc[breakpoint] = breakpointValues;
}
return acc;
}, {});
}
// It should to be noted that this function isn't equivalent to `text-transform: capitalize`.
//
// A strict capitalization should uppercase the first letter of each word in the sentence.
// We only handle the first word.
function capitalize(string) {
if (typeof string !== 'string') {
throw new Error(formatMuiErrorMessage(7));
}
return string.charAt(0).toUpperCase() + string.slice(1);
}
function getPath$1(obj, path, checkVars = true) {
if (!path || typeof path !== 'string') {
return null;
}
// Check if CSS variables are used
if (obj && obj.vars && checkVars) {
const val = `vars.${path}`.split('.').reduce((acc, item) => acc && acc[item] ? acc[item] : null, obj);
if (val != null) {
return val;
}
}
return path.split('.').reduce((acc, item) => {
if (acc && acc[item] != null) {
return acc[item];
}
return null;
}, obj);
}
function getStyleValue$1(themeMapping, transform, propValueFinal, userValue = propValueFinal) {
let value;
if (typeof themeMapping === 'function') {
value = themeMapping(propValueFinal);
} else if (Array.isArray(themeMapping)) {
value = themeMapping[propValueFinal] || userValue;
} else {
value = getPath$1(themeMapping, propValueFinal) || userValue;
}
if (transform) {
value = transform(value, userValue, themeMapping);
}
return value;
}
function style$1(options) {
const {
prop,
cssProperty = options.prop,
themeKey,
transform
} = options;
// false positive
// eslint-disable-next-line react/function-component-definition
const fn = props => {
if (props[prop] == null) {
return null;
}
const propValue = props[prop];
const theme = props.theme;
const themeMapping = getPath$1(theme, themeKey) || {};
const styleFromPropValue = propValueFinal => {
let value = getStyleValue$1(themeMapping, transform, propValueFinal);
if (propValueFinal === value && typeof propValueFinal === 'string') {
// Haven't found value
value = getStyleValue$1(themeMapping, transform, `${prop}${propValueFinal === 'default' ? '' : capitalize(propValueFinal)}`, propValueFinal);
}
if (cssProperty === false) {
return value;
}
return {
[cssProperty]: value
};
};
return handleBreakpoints(props, propValue, styleFromPropValue);
};
fn.propTypes = {};
fn.filterProps = [prop];
return fn;
}
function memoize(fn) {
const cache = {};
return arg => {
if (cache[arg] === undefined) {
cache[arg] = fn(arg);
}
return cache[arg];
};
}
const properties = {
m: 'margin',
p: 'padding'
};
const directions = {
t: 'Top',
r: 'Right',
b: 'Bottom',
l: 'Left',
x: ['Left', 'Right'],
y: ['Top', 'Bottom']
};
const aliases = {
marginX: 'mx',
marginY: 'my',
paddingX: 'px',
paddingY: 'py'
};
// memoize() impact:
// From 300,000 ops/sec
// To 350,000 ops/sec
const getCssProperties = memoize(prop => {
// It's not a shorthand notation.
if (prop.length > 2) {
if (aliases[prop]) {
prop = aliases[prop];
} else {
return [prop];
}
}
const [a, b] = prop.split('');
const property = properties[a];
const direction = directions[b] || '';
return Array.isArray(direction) ? direction.map(dir => property + dir) : [property + direction];
});
const marginKeys = ['m', 'mt', 'mr', 'mb', 'ml', 'mx', 'my', 'margin', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'marginX', 'marginY', 'marginInline', 'marginInlineStart', 'marginInlineEnd', 'marginBlock', 'marginBlockStart', 'marginBlockEnd'];
const paddingKeys = ['p', 'pt', 'pr', 'pb', 'pl', 'px', 'py', 'padding', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'paddingX', 'paddingY', 'paddingInline', 'paddingInlineStart', 'paddingInlineEnd', 'paddingBlock', 'paddingBlockStart', 'paddingBlockEnd'];
[...marginKeys, ...paddingKeys];
function createUnaryUnit(theme, themeKey, defaultValue, propName) {
const themeSpacing = getPath$1(theme, themeKey, true) ?? defaultValue;
if (typeof themeSpacing === 'number' || typeof themeSpacing === 'string') {
return val => {
if (typeof val === 'string') {
return val;
}
if (typeof themeSpacing === 'string') {
return `calc(${val} * ${themeSpacing})`;
}
return themeSpacing * val;
};
}
if (Array.isArray(themeSpacing)) {
return val => {
if (typeof val === 'string') {
return val;
}
const abs = Math.abs(val);
const transformed = themeSpacing[abs];
if (val >= 0) {
return transformed;
}
if (typeof transformed === 'number') {
return -transformed;
}
return `-${transformed}`;
};
}
if (typeof themeSpacing === 'function') {
return themeSpacing;
}
return () => undefined;
}
function createUnarySpacing(theme) {
return createUnaryUnit(theme, 'spacing', 8);
}
function getValue$2(transformer, propValue) {
if (typeof propValue === 'string' || propValue == null) {
return propValue;
}
return transformer(propValue);
}
function getStyleFromPropValue(cssProperties, transformer) {
return propValue => cssProperties.reduce((acc, cssProperty) => {
acc[cssProperty] = getValue$2(transformer, propValue);
return acc;
}, {});
}
function resolveCssProperty(props, keys, prop, transformer) {
// Using a hash computation over an array iteration could be faster, but with only 28 items,
// it's doesn't worth the bundle size.
if (!keys.includes(prop)) {
return null;
}
const cssProperties = getCssProperties(prop);
const styleFromPropValue = getStyleFromPropValue(cssProperties, transformer);
const propValue = props[prop];
return handleBreakpoints(props, propValue, styleFromPropValue);
}
function style(props, keys) {
const transformer = createUnarySpacing(props.theme);
return Object.keys(props).map(prop => resolveCssProperty(props, keys, prop, transformer)).reduce(merge, {});
}
function margin(props) {
return style(props, marginKeys);
}
margin.propTypes = {};
margin.filterProps = marginKeys;
function padding(props) {
return style(props, paddingKeys);
}
padding.propTypes = {};
padding.filterProps = paddingKeys;
// The different signatures imply different meaning for their arguments that can't be expressed structurally.
// We express the difference with variable names.
function createSpacing(spacingInput = 8,
// Material Design layouts are visually balanced. Most measurements align to an 8dp grid, which aligns both spacing and the overall layout.
// Smaller components, such as icons, can align to a 4dp grid.
// https://m2.material.io/design/layout/understanding-layout.html
transform = createUnarySpacing({
spacing: spacingInput
})) {
// Already transformed.
if (spacingInput.mui) {
return spacingInput;
}
const spacing = (...argsInput) => {
const args = argsInput.length === 0 ? [1] : argsInput;
return args.map(argument => {
const output = transform(argument);
return typeof output === 'number' ? `${output}px` : output;
}).join(' ');
};
spacing.mui = true;
return spacing;
}
function compose(...styles) {
const handlers = styles.reduce((acc, style) => {
style.filterProps.forEach(prop => {
acc[prop] = style;
});
return acc;
}, {});
// false positive
// eslint-disable-next-line react/function-component-definition
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((acc, style) => acc.concat(style.filterProps), []);
return fn;
}
function borderTransform(value) {
if (typeof value !== 'number') {
return value;
}
return `${value}px solid`;
}
function createBorderStyle(prop, transform) {
return style$1({
prop,
themeKey: 'borders',
transform
});
}
const border = createBorderStyle('border', borderTransform);
const borderTop = createBorderStyle('borderTop', borderTransform);
const borderRight = createBorderStyle('borderRight', borderTransform);
const borderBottom = createBorderStyle('borderBottom', borderTransform);
const borderLeft = createBorderStyle('borderLeft', borderTransform);
const borderColor = createBorderStyle('borderColor');
const borderTopColor = createBorderStyle('borderTopColor');
const borderRightColor = createBorderStyle('borderRightColor');
const borderBottomColor = createBorderStyle('borderBottomColor');
const borderLeftColor = createBorderStyle('borderLeftColor');
const outline = createBorderStyle('outline', borderTransform);
const outlineColor = createBorderStyle('outlineColor');
// false positive
// eslint-disable-next-line react/function-component-definition
const borderRadius$1 = props => {
if (props.borderRadius !== undefined && props.borderRadius !== null) {
const transformer = createUnaryUnit(props.theme, 'shape.borderRadius', 4);
const styleFromPropValue = propValue => ({
borderRadius: getValue$2(transformer, propValue)
});
return handleBreakpoints(props, props.borderRadius, styleFromPropValue);
}
return null;
};
borderRadius$1.propTypes = {};
borderRadius$1.filterProps = ['borderRadius'];
compose(border, borderTop, borderRight, borderBottom, borderLeft, borderColor, borderTopColor, borderRightColor, borderBottomColor, borderLeftColor, borderRadius$1, outline, outlineColor);
// false positive
// eslint-disable-next-line react/function-component-definition
const gap = props => {
if (props.gap !== undefined && props.gap !== null) {
const transformer = createUnaryUnit(props.theme, 'spacing', 8);
const styleFromPropValue = propValue => ({
gap: getValue$2(transformer, propValue)
});
return handleBreakpoints(props, props.gap, styleFromPropValue);
}
return null;
};
gap.propTypes = {};
gap.filterProps = ['gap'];
// false positive
// eslint-disable-next-line react/function-component-definition
const columnGap = props => {
if (props.columnGap !== undefined && props.columnGap !== null) {
const transformer = createUnaryUnit(props.theme, 'spacing', 8);
const styleFromPropValue = propValue => ({
columnGap: getValue$2(transformer, propValue)
});
return handleBreakpoints(props, props.columnGap, styleFromPropValue);
}
return null;
};
columnGap.propTypes = {};
columnGap.filterProps = ['columnGap'];
// false positive
// eslint-disable-next-line react/function-component-definition
const rowGap = props => {
if (props.rowGap !== undefined && props.rowGap !== null) {
const transformer = createUnaryUnit(props.theme, 'spacing', 8);
const styleFromPropValue = propValue => ({
rowGap: getValue$2(transformer, propValue)
});
return handleBreakpoints(props, props.rowGap, styleFromPropValue);
}
return null;
};
rowGap.propTypes = {};
rowGap.filterProps = ['rowGap'];
const gridColumn = style$1({
prop: 'gridColumn'
});
const gridRow = style$1({
prop: 'gridRow'
});
const gridAutoFlow = style$1({
prop: 'gridAutoFlow'
});
const gridAutoColumns = style$1({
prop: 'gridAutoColumns'
});
const gridAutoRows = style$1({
prop: 'gridAutoRows'
});
const gridTemplateColumns = style$1({
prop: 'gridTemplateColumns'
});
const gridTemplateRows = style$1({
prop: 'gridTemplateRows'
});
const gridTemplateAreas = style$1({
prop: 'gridTemplateAreas'
});
const gridArea = style$1({
prop: 'gridArea'
});
compose(gap, columnGap, rowGap, gridColumn, gridRow, gridAutoFlow, gridAutoColumns, gridAutoRows, gridTemplateColumns, gridTemplateRows, gridTemplateAreas, gridArea);
function paletteTransform(value, userValue) {
if (userValue === 'grey') {
return userValue;
}
return value;
}
const color = style$1({
prop: 'color',
themeKey: 'palette',
transform: paletteTransform
});
const bgcolor = style$1({
prop: 'bgcolor',
cssProperty: 'backgroundColor',
themeKey: 'palette',
transform: paletteTransform
});
const backgroundColor = style$1({
prop: 'backgroundColor',
themeKey: 'palette',
transform: paletteTransform
});
compose(color, bgcolor, backgroundColor);
function sizingTransform(value) {
return value <= 1 && value !== 0 ? `${value * 100}%` : value;
}
const width = style$1({
prop: 'width',
transform: sizingTransform
});
const maxWidth = props => {
if (props.maxWidth !== undefined && props.maxWidth !== null) {
const styleFromPropValue = propValue => {
const breakpoint = props.theme?.breakpoints?.values?.[propValue] || values$1[propValue];
if (!breakpoint) {
return {
maxWidth: sizingTransform(propValue)
};
}
if (props.theme?.breakpoints?.unit !== 'px') {
return {
maxWidth: `${breakpoint}${props.theme.breakpoints.unit}`
};
}
return {
maxWidth: breakpoint
};
};
return handleBreakpoints(props, props.maxWidth, styleFromPropValue);
}
return null;
};
maxWidth.filterProps = ['maxWidth'];
const minWidth = style$1({
prop: 'minWidth',
transform: sizingTransform
});
const height = style$1({
prop: 'height',
transform: sizingTransform
});
const maxHeight = style$1({
prop: 'maxHeight',
transform: sizingTransform
});
const minHeight = style$1({
prop: 'minHeight',
transform: sizingTransform
});
style$1({
prop: 'size',
cssProperty: 'width',
transform: sizingTransform
});
style$1({
prop: 'size',
cssProperty: 'height',
transform: sizingTransform
});
const boxSizing = style$1({
prop: 'boxSizing'
});
compose(width, maxWidth, minWidth, height, maxHeight, minHeight, boxSizing);
const defaultSxConfig = {
// borders
border: {
themeKey: 'borders',
transform: borderTransform
},
borderTop: {
themeKey: 'borders',
transform: borderTransform
},
borderRight: {
themeKey: 'borders',
transform: borderTransform
},
borderBottom: {
themeKey: 'borders',
transform: borderTransform
},
borderLeft: {
themeKey: 'borders',
transform: borderTransform
},
borderColor: {
themeKey: 'palette'
},
borderTopColor: {
themeKey: 'palette'
},
borderRightColor: {
themeKey: 'palette'
},
borderBottomColor: {
themeKey: 'palette'
},
borderLeftColor: {
themeKey: 'palette'
},
outline: {
themeKey: 'borders',
transform: borderTransform
},
outlineColor: {
themeKey: 'palette'
},
borderRadius: {
themeKey: 'shape.borderRadius',
style: borderRadius$1
},
// palette
color: {
themeKey: 'palette',
transform: paletteTransform
},
bgcolor: {
themeKey: 'palette',
cssProperty: 'backgroundColor',
transform: paletteTransform
},
backgroundColor: {
themeKey: 'palette',
transform: paletteTransform
},
// spacing
p: {
style: padding
},
pt: {
style: padding
},
pr: {
style: padding
},
pb: {
style: padding
},
pl: {
style: padding
},
px: {
style: padding
},
py: {
style: padding
},
padding: {
style: padding
},
paddingTop: {
style: padding
},
paddingRight: {
style: padding
},
paddingBottom: {
style: padding
},
paddingLeft: {
style: padding
},
paddingX: {
style: padding
},
paddingY: {
style: padding
},
paddingInline: {
style: padding
},
paddingInlineStart: {
style: padding
},
paddingInlineEnd: {
style: padding
},
paddingBlock: {
style: padding
},
paddingBlockStart: {
style: padding
},
paddingBlockEnd: {
style: padding
},
m: {
style: margin
},
mt: {
style: margin
},
mr: {
style: margin
},
mb: {
style: margin
},
ml: {
style: margin
},
mx: {
style: margin
},
my: {
style: margin
},
margin: {
style: margin
},
marginTop: {
style: margin
},
marginRight: {
style: margin
},
marginBottom: {
style: margin
},
marginLeft: {
style: margin
},
marginX: {
style: margin
},
marginY: {
style: margin
},
marginInline: {
style: margin
},
marginInlineStart: {
style: margin
},
marginInlineEnd: {
style: margin
},
marginBlock: {
style: margin
},
marginBlockStart: {
style: margin
},
marginBlockEnd: {
style: margin
},
// display
displayPrint: {
cssProperty: false,
transform: value => ({
'@media print': {
display: value
}
})
},
display: {},
overflow: {},
textOverflow: {},
visibility: {},
whiteSpace: {},
// flexbox
flexBasis: {},
flexDirection: {},
flexWrap: {},
justifyContent: {},
alignItems: {},
alignContent: {},
order: {},
flex: {},
flexGrow: {},
flexShrink: {},
alignSelf: {},
justifyItems: {},
justifySelf: {},
// grid
gap: {
style: gap
},
rowGap: {
style: rowGap
},
columnGap: {
style: columnGap
},
gridColumn: {},
gridRow: {},
gridAutoFlow: {},
gridAutoColumns: {},
gridAutoRows: {},
gridTemplateColumns: {},
gridTemplateRows: {},
gridTemplateAreas: {},
gridArea: {},
// positions
position: {},
zIndex: {
themeKey: 'zIndex'
},
top: {},
right: {},
bottom: {},
left: {},
// shadows
boxShadow: {
themeKey: 'shadows'
},
// sizing
width: {
transform: sizingTransform
},
maxWidth: {
style: maxWidth
},
minWidth: {
transform: sizingTransform
},
height: {
transform: sizingTransform
},
maxHeight: {
transform: sizingTransform
},
minHeight: {
transform: sizingTransform
},
boxSizing: {},
// typography
font: {
themeKey: 'font'
},
fontFamily: {
themeKey: 'typography'
},
fontSize: {
themeKey: 'typography'
},
fontStyle: {
themeKey: 'typography'
},
fontWeight: {
themeKey: 'typography'
},
letterSpacing: {},
textTransform: {},
lineHeight: {},
textAlign: {},
typography: {
cssProperty: false,
themeKey: 'typography'
}
};
function objectsHaveSameKeys(...objects) {
const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), []);
const union = new Set(allKeys);
return objects.every(object => union.size === Object.keys(object).length);
}
function callIfFn(maybeFn, arg) {
return typeof maybeFn === 'function' ? maybeFn(arg) : maybeFn;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
function unstable_createStyleFunctionSx() {
function getThemeValue(prop, val, theme, config) {
const props = {
[prop]: val,
theme
};
const options = config[prop];
if (!options) {
return {
[prop]: val
};
}
const {
cssProperty = prop,
themeKey,
transform,
style
} = options;
if (val == null) {
return null;
}
// TODO v6: remove, see https://github.com/mui/material-ui/pull/38123
if (themeKey === 'typography' && val === 'inherit') {
return {
[prop]: val
};
}
const themeMapping = getPath$1(theme, themeKey) || {};
if (style) {
return style(props);
}
const styleFromPropValue = propValueFinal => {
let value = getStyleValue$1(themeMapping, transform, propValueFinal);
if (propValueFinal === value && typeof propValueFinal === 'string') {
// Haven't found value
value = getStyleValue$1(themeMapping, transform, `${prop}${propValueFinal === 'default' ? '' : capitalize(propValueFinal)}`, propValueFinal);
}
if (cssProperty === false) {
return value;
}
return {
[cssProperty]: value
};
};
return handleBreakpoints(props, val, styleFromPropValue);
}
function styleFunctionSx(props) {
const {
sx,
theme = {},
nested
} = props || {};
if (!sx) {
return null; // Emotion & styled-components will neglect null
}
const config = theme.unstable_sxConfig ?? defaultSxConfig;
/*
* Receive `sxInput` as object or callback
* and then recursively check keys & values to create media query object styles.
* (the result will be used in `styled`)
*/
function traverse(sxInput) {
let sxObject = sxInput;
if (typeof sxInput === 'function') {
sxObject = sxInput(theme);
} else if (typeof sxInput !== 'object') {
// value
return sxInput;
}
if (!sxObject) {
return null;
}
const emptyBreakpoints = createEmptyBreakpointObject(theme.breakpoints);
const breakpointsKeys = Object.keys(emptyBreakpoints);
let css = emptyBreakpoints;
Object.keys(sxObject).forEach(styleKey => {
const value = callIfFn(sxObject[styleKey], theme);
if (value !== null && value !== undefined) {
if (typeof value === 'object') {
if (config[styleKey]) {
css = merge(css, getThemeValue(styleKey, value, theme, config));
} else {
const breakpointsValues = handleBreakpoints({
theme
}, value, x => ({
[styleKey]: x
}));
if (objectsHaveSameKeys(breakpointsValues, value)) {
css[styleKey] = styleFunctionSx({
sx: value,
theme,
nested: true
});
} else {
css = merge(css, breakpointsValues);
}
}
} else {
css = merge(css, getThemeValue(styleKey, value, theme, config));
}
}
});
if (!nested && theme.modularCssLayers) {
return {
'@layer sx': sortContainerQueries(theme, removeUnusedBreakpoints(breakpointsKeys, css))
};
}
return sortContainerQueries(theme, removeUnusedBreakpoints(breakpointsKeys, css));
}
return Array.isArray(sx) ? sx.map(traverse) : traverse(sx);
}
return styleFunctionSx;
}
const styleFunctionSx = unstable_createStyleFunctionSx();
styleFunctionSx.filterProps = ['sx'];
/**
* A universal utility to style components with multiple color modes. Always use it from the theme object.
* It works with:
* - [Basic theme](https://mui.com/material-ui/customization/dark-mode/)
* - [CSS theme variables](https://mui.com/material-ui/customization/css-theme-variables/overview/)
* - Zero-runtime engine
*
* Tips: Use an array over object spread and place `theme.applyStyles()` last.
*
* With the styled function:
* ✅ [{ background: '#e5e5e5' }, theme.applyStyles('dark', { background: '#1c1c1c' })]
* 🚫 { background: '#e5e5e5', ...theme.applyStyles('dark', { background: '#1c1c1c' })}
*
* With the sx prop:
* ✅ [{ background: '#e5e5e5' }, theme => theme.applyStyles('dark', { background: '#1c1c1c' })]
* 🚫 { background: '#e5e5e5', ...theme => theme.applyStyles('dark', { background: '#1c1c1c' })}
*
* @example
* 1. using with `styled`:
* ```jsx
* const Component = styled('div')(({ theme }) => [
* { background: '#e5e5e5' },
* theme.applyStyles('dark', {
* background: '#1c1c1c',
* color: '#fff',
* }),
* ]);
* ```
*
* @example
* 2. using with `sx` prop:
* ```jsx
* <Box sx={[
* { background: '#e5e5e5' },
* theme => theme.applyStyles('dark', {
* background: '#1c1c1c',
* color: '#fff',
* }),
* ]}
* />
* ```
*
* @example
* 3. theming a component:
* ```jsx
* extendTheme({
* components: {
* MuiButton: {
* styleOverrides: {
* root: ({ theme }) => [
* { background: '#e5e5e5' },
* theme.applyStyles('dark', {
* background: '#1c1c1c',
* color: '#fff',
* }),
* ],
* },
* }
* }
* })
*```
*/
function applyStyles$2(key, styles) {
// @ts-expect-error this is 'any' type
const theme = this;
if (theme.vars) {
if (!theme.colorSchemes?.[key] || typeof theme.getColorSchemeSelector !== 'function') {
return {};
}
// If CssVarsProvider is used as a provider, returns '*:where({selector}) &'
let selector = theme.getColorSchemeSelector(key);
if (selector === '&') {
return styles;
}
if (selector.includes('data-') || selector.includes('.')) {
// '*' is required as a workaround for Emotion issue (https://github.com/emotion-js/emotion/issues/2836)
selector = `*:where(${selector.replace(/\s*&$/, '')}) &`;
}
return {
[selector]: styles
};
}
if (theme.palette.mode === key) {
return styles;
}
return {};
}
function createTheme$1(options = {}, ...args) {
const {
breakpoints: breakpointsInput = {},
palette: paletteInput = {},
spacing: spacingInput,
shape: shapeInput = {},
...other
} = options;
const breakpoints = createBreakpoints(breakpointsInput);
const spacing = createSpacing(spacingInput);
let muiTheme = deepmerge({
breakpoints,
direction: 'ltr',
components: {},
// Inject component definitions.
palette: {
mode: 'light',
...paletteInput
},
spacing,
shape: {
...shape,
...shapeInput
}
}, other);
muiTheme = cssContainerQueries(muiTheme);
muiTheme.applyStyles = applyStyles$2;
muiTheme = args.reduce((acc, argument) => deepmerge(acc, argument), muiTheme);
muiTheme.unstable_sxConfig = {
...defaultSxConfig,
...other?.unstable_sxConfig
};
muiTheme.unstable_sx = function sx(props) {
return styleFunctionSx({
sx: props,
theme: this
});
};
return muiTheme;
}
function isObjectEmpty$2(obj) {
return Object.keys(obj).length === 0;
}
function useTheme$4(defaultTheme = null) {
const contextTheme = reactExports.useContext(ThemeContext$1);
return !contextTheme || isObjectEmpty$2(contextTheme) ? defaultTheme : contextTheme;
}
const systemDefaultTheme$1 = createTheme$1();
function useTheme$3(defaultTheme = systemDefaultTheme$1) {
return useTheme$4(defaultTheme);
}
function wrapGlobalLayer(styles) {
const serialized = internal_serializeStyles(styles);
if (styles !== serialized && serialized.styles) {
if (!serialized.styles.match(/^@layer\s+[^{]*$/)) {
// If the styles are not already wrapped in a layer, wrap them in a global layer.
serialized.styles = `@layer global{${serialized.styles}}`;
}
return serialized;
}
return styles;
}
function GlobalStyles$1({
styles,
themeId,
defaultTheme = {}
}) {
const upperTheme = useTheme$3(defaultTheme);
const resolvedTheme = themeId ? upperTheme[themeId] || upperTheme : upperTheme;
let globalStyles = typeof styles === 'function' ? styles(resolvedTheme) : styles;
if (resolvedTheme.modularCssLayers) {
if (Array.isArray(globalStyles)) {
globalStyles = globalStyles.map(styleArg => {
if (typeof styleArg === 'function') {
return wrapGlobalLayer(styleArg(resolvedTheme));
}
return wrapGlobalLayer(styleArg);
});
} else {
globalStyles = wrapGlobalLayer(globalStyles);
}
}
return /*#__PURE__*/jsxRuntimeExports.jsx(GlobalStyles$2, {
styles: globalStyles
});
}
const splitProps = props => {
const result = {
systemProps: {},
otherProps: {}
};
const config = props?.theme?.unstable_sxConfig ?? defaultSxConfig;
Object.keys(props).forEach(prop => {
if (config[prop]) {
result.systemProps[prop] = props[prop];
} else {
result.otherProps[prop] = props[prop];
}
});
return result;
};
function extendSxProp$1(props) {
const {
sx: inSx,
...other
} = props;
const {
systemProps,
otherProps
} = splitProps(other);
let finalSx;
if (Array.isArray(inSx)) {
finalSx = [systemProps, ...inSx];
} else if (typeof inSx === 'function') {
finalSx = (...args) => {
const result = inSx(...args);
if (!isPlainObject(result)) {
return systemProps;
}
return {
...systemProps,
...result
};
};
} else {
finalSx = {
...systemProps,
...inSx
};
}
return {
...otherProps,
sx: finalSx
};
}
const defaultGenerator = componentName => componentName;
const createClassNameGenerator = () => {
let generate = defaultGenerator;
return {
configure(generator) {
generate = generator;
},
generate(componentName) {
return generate(componentName);
},
reset() {
generate = defaultGenerator;
}
};
};
const ClassNameGenerator = createClassNameGenerator();
function r$1(e){var t,f,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r$1(e[t]))&&(n&&(n+=" "),n+=f);}else for(f in e)e[f]&&(n&&(n+=" "),n+=f);return n}function clsx(){for(var e,t,f=0,n="",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r$1(e))&&(n&&(n+=" "),n+=t);return n}
function createBox(options = {}) {
const {
themeId,
defaultTheme,
defaultClassName = 'MuiBox-root',
generateClassName
} = options;
const BoxRoot = styled$1('div', {
shouldForwardProp: prop => prop !== 'theme' && prop !== 'sx' && prop !== 'as'
})(styleFunctionSx);
const Box = /*#__PURE__*/reactExports.forwardRef(function Box(inProps, ref) {
const theme = useTheme$3(defaultTheme);
const {
className,
component = 'div',
...other
} = extendSxProp$1(inProps);
return /*#__PURE__*/jsxRuntimeExports.jsx(BoxRoot, {
as: component,
ref: ref,
className: clsx(className, generateClassName ? generateClassName(defaultClassName) : defaultClassName),
theme: themeId ? theme[themeId] || theme : theme,
...other
});
});
return Box;
}
const globalStateClasses = {
active: 'active',
checked: 'checked',
completed: 'completed',
disabled: 'disabled',
error: 'error',
expanded: 'expanded',
focused: 'focused',
focusVisible: 'focusVisible',
open: 'open',
readOnly: 'readOnly',
required: 'required',
selected: 'selected'
};
function generateUtilityClass(componentName, slot, globalStatePrefix = 'Mui') {
const globalStateClass = globalStateClasses[slot];
return globalStateClass ? `${globalStatePrefix}-${globalStateClass}` : `${ClassNameGenerator.generate(componentName)}-${slot}`;
}
function generateUtilityClasses(componentName, slots, globalStatePrefix = 'Mui') {
const result = {};
slots.forEach(slot => {
result[slot] = generateUtilityClass(componentName, slot, globalStatePrefix);
});
return result;
}
function preprocessStyles(input) {
const {
variants,
...style
} = input;
const result = {
variants,
style: internal_serializeStyles(style),
isProcessed: true
};
// Not supported on styled-components
if (result.style === style) {
return result;
}
if (variants) {
variants.forEach(variant => {
if (typeof variant.style !== 'function') {
variant.style = internal_serializeStyles(variant.style);
}
});
}
return result;
}
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-labels */
/* eslint-disable no-lone-blocks */
const systemDefaultTheme = createTheme$1();
// Update /system/styled/#api in case if this changes
function shouldForwardProp(prop) {
return prop !== 'ownerState' && prop !== 'theme' && prop !== 'sx' && prop !== 'as';
}
function shallowLayer(serialized, layerName) {
if (layerName && serialized && typeof serialized === 'object' && serialized.styles && !serialized.styles.startsWith('@layer') // only add the layer if it is not already there.
) {
serialized.styles = `@layer ${layerName}{${String(serialized.styles)}}`;
}
return serialized;
}
function defaultOverridesResolver(slot) {
if (!slot) {
return null;
}
return (_props, styles) => styles[slot];
}
function attachTheme(props, themeId, defaultTheme) {
props.theme = isObjectEmpty$1(props.theme) ? defaultTheme : props.theme[themeId] || props.theme;
}
function processStyle(props, style, layerName) {
/*
* Style types:
* - null/undefined
* - string
* - CSS style object: { [cssKey]: [cssValue], variants }
* - Processed style object: { style, variants, isProcessed: true }
* - Array of any of the above
*/
const resolvedStyle = typeof style === 'function' ? style(props) : style;
if (Array.isArray(resolvedStyle)) {
return resolvedStyle.flatMap(subStyle => processStyle(props, subStyle, layerName));
}
if (Array.isArray(resolvedStyle?.variants)) {
let rootStyle;
if (resolvedStyle.isProcessed) {
rootStyle = layerName ? shallowLayer(resolvedStyle.style, layerName) : resolvedStyle.style;
} else {
const {
variants,
...otherStyles
} = resolvedStyle;
rootStyle = layerName ? shallowLayer(internal_serializeStyles(otherStyles), layerName) : otherStyles;
}
return processStyleVariants(props, resolvedStyle.variants, [rootStyle], layerName);
}
if (resolvedStyle?.isProcessed) {
return layerName ? shallowLayer(internal_serializeStyles(resolvedStyle.style), layerName) : resolvedStyle.style;
}
return layerName ? shallowLayer(internal_serializeStyles(resolvedStyle), layerName) : resolvedStyle;
}
function processStyleVariants(props, variants, results = [], layerName = undefined) {
let mergedState; // We might not need it, initialized lazily
variantLoop: for (let i = 0; i < variants.length; i += 1) {
const variant = variants[i];
if (typeof variant.props === 'function') {
mergedState ??= {
...props,
...props.ownerState,
ownerState: props.ownerState
};
if (!variant.props(mergedState)) {
continue;
}
} else {
for (const key in variant.props) {
if (props[key] !== variant.props[key] && props.ownerState?.[key] !== variant.props[key]) {
continue variantLoop;
}
}
}
if (typeof variant.style === 'function') {
mergedState ??= {
...props,
...props.ownerState,
ownerState: props.ownerState
};
results.push(layerName ? shallowLayer(internal_serializeStyles(variant.style(mergedState)), layerName) : variant.style(mergedState));
} else {
results.push(layerName ? shallowLayer(internal_serializeStyles(variant.style), layerName) : variant.style);
}
}
return results;
}
function createStyled(input = {}) {
const {
themeId,
defaultTheme = systemDefaultTheme,
rootShouldForwardProp = shouldForwardProp,
slotShouldForwardProp = shouldForwardProp
} = input;
function styleAttachTheme(props) {
attachTheme(props, themeId, defaultTheme);
}
const styled = (tag, inputOptions = {}) => {
// If `tag` is already a styled component, filter out the `sx` style function
// to prevent unnecessary styles generated by the composite components.
internal_mutateStyles(tag, styles => styles.filter(style => style !== styleFunctionSx));
const {
name: componentName,
slot: componentSlot,
skipVariantsResolver: inputSkipVariantsResolver,
skipSx: inputSkipSx,
// TODO v6: remove `lowercaseFirstLetter()` in the next major release
// For more details: https://github.com/mui/material-ui/pull/37908
overridesResolver = defaultOverridesResolver(lowercaseFirstLetter(componentSlot)),
...options
} = inputOptions;
const layerName = componentName && componentName.startsWith('Mui') || !!componentSlot ? 'components' : 'custom';
// if skipVariantsResolver option is defined, take the value, otherwise, true for root and false for other slots.
const skipVariantsResolver = inputSkipVariantsResolver !== undefined ? inputSkipVariantsResolver :
// TODO v6: remove `Root` in the next major release
// For more details: https://github.com/mui/material-ui/pull/37908
componentSlot && componentSlot !== 'Root' && componentSlot !== 'root' || false;
const skipSx = inputSkipSx || false;
let shouldForwardPropOption = shouldForwardProp;
// TODO v6: remove `Root` in the next major release
// For more details: https://github.com/mui/material-ui/pull/37908
if (componentSlot === 'Root' || componentSlot === 'root') {
shouldForwardPropOption = rootShouldForwardProp;
} else if (componentSlot) {
// any other slot specified
shouldForwardPropOption = slotShouldForwardProp;
} else if (isStringTag(tag)) {
// for string (html) tag, preserve the behavior in emotion & styled-components.
shouldForwardPropOption = undefined;
}
const defaultStyledResolver = styled$1(tag, {
shouldForwardProp: shouldForwardPropOption,
label: generateStyledLabel(),
...options
});
const transformStyle = style => {
// - On the server Emotion doesn't use React.forwardRef for creating components, so the created
// component stays as a function. This condition makes sure that we do not interpolate functions
// which are basically components used as a selectors.
// - `style` could be a styled component from a babel plugin for component selectors, This condition
// makes sure that we do not interpolate them.
if (style.__emotion_real === style) {
return style;
}
if (typeof style === 'function') {
return function styleFunctionProcessor(props) {
return processStyle(props, style, props.theme.modularCssLayers ? layerName : undefined);
};
}
if (isPlainObject(style)) {
const serialized = preprocessStyles(style);
return function styleObjectProcessor(props) {
if (!serialized.variants) {
return props.theme.modularCssLayers ? shallowLayer(serialized.style, layerName) : serialized.style;
}
return processStyle(props, serialized, props.theme.modularCssLayers ? layerName : undefined);
};
}
return style;
};
const muiStyledResolver = (...expressionsInput) => {
const expressionsHead = [];
const expressionsBody = expressionsInput.map(transformStyle);
const expressionsTail = [];
// Preprocess `props` to set the scoped theme value.
// This must run before any other expression.
expressionsHead.push(styleAttachTheme);
if (componentName && overridesResolver) {
expressionsTail.push(function styleThemeOverrides(props) {
const theme = props.theme;
const styleOverrides = theme.components?.[componentName]?.styleOverrides;
if (!styleOverrides) {
return null;
}
const resolvedStyleOverrides = {};
// TODO: v7 remove iteration and use `resolveStyleArg(styleOverrides[slot])` directly
// eslint-disable-next-line guard-for-in
for (const slotKey in styleOverrides) {
resolvedStyleOverrides[slotKey] = processStyle(props, styleOverrides[slotKey], props.theme.modularCssLayers ? 'theme' : undefined);
}
return overridesResolver(props, resolvedStyleOverrides);
});
}
if (componentName && !skipVariantsResolver) {
expressionsTail.push(function styleThemeVariants(props) {
const theme = props.theme;
const themeVariants = theme?.components?.[componentName]?.variants;
if (!themeVariants) {
return null;
}
return processStyleVariants(props, themeVariants, [], props.theme.modularCssLayers ? 'theme' : undefined);
});
}
if (!skipSx) {
expressionsTail.push(styleFunctionSx);
}
// This function can be called as a tagged template, so the first argument would contain
// CSS `string[]` values.
if (Array.isArray(expressionsBody[0])) {
const inputStrings = expressionsBody.shift();
// We need to add placeholders in the tagged template for the custom functions we have
// possibly added (attachTheme, overrides, variants, and sx).
const placeholdersHead = new Array(expressionsHead.length).fill('');
const placeholdersTail = new Array(expressionsTail.length).fill('');
let outputStrings;
// prettier-ignore
{
outputStrings = [...placeholdersHead, ...inputStrings, ...placeholdersTail];
outputStrings.raw = [...placeholdersHead, ...inputStrings.raw, ...placeholdersTail];
}
// The only case where we put something before `attachTheme`
expressionsHead.unshift(outputStrings);
}
const expressions = [...expressionsHead, ...expressionsBody, ...expressionsTail];
const Component = defaultStyledResolver(...expressions);
if (tag.muiName) {
Component.muiName = tag.muiName;
}
return Component;
};
if (defaultStyledResolver.withConfig) {
muiStyledResolver.withConfig = defaultStyledResolver.withConfig;
}
return muiStyledResolver;
};
return styled;
}
function generateStyledLabel(componentName, componentSlot) {
let label;
return label;
}
function isObjectEmpty$1(object) {
// eslint-disable-next-line
for (const _ in object) {
return false;
}
return true;
}
// https://github.com/emotion-js/emotion/blob/26ded6109fcd8ca9875cc2ce4564fee678a3f3c5/packages/styled/src/utils.js#L40
function isStringTag(tag) {
return typeof tag === 'string' &&
// 96 is one less than the char code
// for "a" so this is checking that
// it's a lowercase character
tag.charCodeAt(0) > 96;
}
function lowercaseFirstLetter(string) {
if (!string) {
return string;
}
return string.charAt(0).toLowerCase() + string.slice(1);
}
/**
* Add keys, values of `defaultProps` that does not exist in `props`
* @param defaultProps
* @param props
* @returns resolved props
*/
function resolveProps(defaultProps, props) {
const output = {
...props
};
for (const key in defaultProps) {
if (Object.prototype.hasOwnProperty.call(defaultProps, key)) {
const propName = key;
if (propName === 'components' || propName === 'slots') {
output[propName] = {
...defaultProps[propName],
...output[propName]
};
} else if (propName === 'componentsProps' || propName === 'slotProps') {
const defaultSlotProps = defaultProps[propName];
const slotProps = props[propName];
if (!slotProps) {
output[propName] = defaultSlotProps || {};
} else if (!defaultSlotProps) {
output[propName] = slotProps;
} else {
output[propName] = {
...slotProps
};
for (const slotKey in defaultSlotProps) {
if (Object.prototype.hasOwnProperty.call(defaultSlotProps, slotKey)) {
const slotPropName = slotKey;
output[propName][slotPropName] = resolveProps(defaultSlotProps[slotPropName], slotProps[slotPropName]);
}
}
}
} else if (output[propName] === undefined) {
output[propName] = defaultProps[propName];
}
}
}
return output;
}
/**
* A version of `React.useLayoutEffect` that does not show a warning when server-side rendering.
* This is useful for effects that are only needed for client-side rendering but not for SSR.
*
* Before you use this hook, make sure to read https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85
* and confirm it doesn't apply to your use-case.
*/
const useEnhancedEffect = typeof window !== 'undefined' ? reactExports.useLayoutEffect : reactExports.useEffect;
function clamp(val, min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER) {
return Math.max(min, Math.min(val, max));
}
/**
* 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 clampWrapper(value, min = 0, max = 1) {
return clamp(value, min, 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.slice(1);
const re = new RegExp(`.{1,${color.length >= 6 ? 2 : 1}}`, 'g');
let colors = color.match(re);
if (colors && colors[0].length === 1) {
colors = colors.map(n => n + n);
}
return colors ? `rgb${colors.length === 4 ? 'a' : ''}(${colors.map((n, index) => {
return index < 3 ? parseInt(n, 16) : Math.round(parseInt(n, 16) / 255 * 1000) / 1000;
}).join(', ')})` : '';
}
/**
* 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(), color()
* @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));
}
const marker = color.indexOf('(');
const type = color.substring(0, marker);
if (!['rgb', 'rgba', 'hsl', 'hsla', 'color'].includes(type)) {
throw new Error(formatMuiErrorMessage(9, color));
}
let values = color.substring(marker + 1, color.length - 1);
let colorSpace;
if (type === 'color') {
values = values.split(' ');
colorSpace = values.shift();
if (values.length === 4 && values[3].charAt(0) === '/') {
values[3] = values[3].slice(1);
}
if (!['srgb', 'display-p3', 'a98-rgb', 'prophoto-rgb', 'rec-2020'].includes(colorSpace)) {
throw new Error(formatMuiErrorMessage(10, colorSpace));
}
} else {
values = values.split(',');
}
values = values.map(value => parseFloat(value));
return {
type,
values,
colorSpace
};
}
/**
* Returns a channel created from the input color.
*
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @returns {string} - The channel for the color, that can be used in rgba or hsla colors
*/
const colorChannel = color => {
const decomposedColor = decomposeColor(color);
return decomposedColor.values.slice(0, 3).map((val, idx) => decomposedColor.type.includes('hsl') && idx !== 0 ? `${val}%` : val).join(' ');
};
const private_safeColorChannel = (color, warning) => {
try {
return colorChannel(color);
} catch (error) {
return color;
}
};
/**
* 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', 'color'
* @param {array} color.values - [n,n,n] or [n,n,n,n]
* @returns {string} A CSS color string
*/
function recomposeColor(color) {
const {
type,
colorSpace
} = color;
let {
values
} = color;
if (type.includes('rgb')) {
// Only convert the first 3 values to int (i.e. not alpha)
values = values.map((n, i) => i < 3 ? parseInt(n, 10) : n);
} else if (type.includes('hsl')) {
values[1] = `${values[1]}%`;
values[2] = `${values[2]}%`;
}
if (type.includes('color')) {
values = `${colorSpace} ${values.join(' ')}`;
} else {
values = `${values.join(', ')}`;
}
return `${type}(${values})`;
}
/**
* 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);
const {
values
} = color;
const h = values[0];
const s = values[1] / 100;
const l = values[2] / 100;
const a = s * Math.min(l, 1 - l);
const f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
let type = 'rgb';
const 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,
values: rgb
});
}
/**
* 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(), color()
* @returns {number} The relative brightness of the color in the range 0 - 1
*/
function getLuminance(color) {
color = decomposeColor(color);
let rgb = color.type === 'hsl' || color.type === 'hsla' ? decomposeColor(hslToRgb(color)).values : color.values;
rgb = rgb.map(val => {
if (color.type !== 'color') {
val /= 255; // normalized
}
return val <= 0.03928 ? val / 12.92 : ((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));
}
/**
* 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) {
const lumA = getLuminance(foreground);
const lumB = getLuminance(background);
return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);
}
/**
* Sets the absolute transparency of a color.
* Any existing alpha values are overwritten.
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param {number} value - value to set the alpha channel to in the range 0 - 1
* @returns {string} A CSS color string. Hex input values are returned as rgb
*/
function alpha(color, value) {
color = decomposeColor(color);
value = clampWrapper(value);
if (color.type === 'rgb' || color.type === 'hsl') {
color.type += 'a';
}
if (color.type === 'color') {
color.values[3] = `/${value}`;
} else {
color.values[3] = value;
}
return recomposeColor(color);
}
function private_safeAlpha(color, value, warning) {
try {
return alpha(color, value);
} catch (error) {
return color;
}
}
/**
* Darkens a color.
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @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 = clampWrapper(coefficient);
if (color.type.includes('hsl')) {
color.values[2] *= 1 - coefficient;
} else if (color.type.includes('rgb') || color.type.includes('color')) {
for (let i = 0; i < 3; i += 1) {
color.values[i] *= 1 - coefficient;
}
}
return recomposeColor(color);
}
function private_safeDarken(color, coefficient, warning) {
try {
return darken(color, coefficient);
} catch (error) {
return color;
}
}
/**
* Lightens a color.
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @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 = clampWrapper(coefficient);
if (color.type.includes('hsl')) {
color.values[2] += (100 - color.values[2]) * coefficient;
} else if (color.type.includes('rgb')) {
for (let i = 0; i < 3; i += 1) {
color.values[i] += (255 - color.values[i]) * coefficient;
}
} else if (color.type.includes('color')) {
for (let i = 0; i < 3; i += 1) {
color.values[i] += (1 - color.values[i]) * coefficient;
}
}
return recomposeColor(color);
}
function private_safeLighten(color, coefficient, warning) {
try {
return lighten(color, coefficient);
} catch (error) {
return color;
}
}
/**
* Darken or lighten a color, depending on its luminance.
* Light colors are darkened, dark colors are lightened.
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
* @param {number} coefficient=0.15 - multiplier in the range 0 - 1
* @returns {string} A CSS color string. Hex input values are returned as rgb
*/
function emphasize(color, coefficient = 0.15) {
return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);
}
function private_safeEmphasize(color, coefficient, warning) {
try {
return emphasize(color, coefficient);
} catch (error) {
return color;
}
}
/**
* Safe chained function.
*
* Will only create a new function if needed,
* otherwise will pass back existing functions or null.
*/
function createChainedFunction(...funcs) {
return funcs.reduce((acc, func) => {
if (func == null) {
return acc;
}
return function chainedFunction(...args) {
acc.apply(this, args);
func.apply(this, args);
};
}, () => {});
}
// Corresponds to 10 frames at 60 Hz.
// A few bytes payload overhead when lodash/debounce is ~3 kB and debounce ~300 B.
function debounce$1(func, wait = 166) {
let timeout;
function debounced(...args) {
const later = () => {
// @ts-ignore
func.apply(this, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
}
debounced.clear = () => {
clearTimeout(timeout);
};
return debounced;
}
function isMuiElement(element, muiNames) {
return /*#__PURE__*/reactExports.isValidElement(element) && muiNames.indexOf(
// For server components `muiName` is avaialble in element.type._payload.value.muiName
// relevant info - https://github.com/facebook/react/blob/2807d781a08db8e9873687fccc25c0f12b4fb3d4/packages/react/src/ReactLazy.js#L45
// eslint-disable-next-line no-underscore-dangle
element.type.muiName ?? element.type?._payload?.value?.muiName) !== -1;
}
function ownerDocument(node) {
return node && node.ownerDocument || document;
}
function ownerWindow(node) {
const doc = ownerDocument(node);
return doc.defaultView || window;
}
/**
* TODO v5: consider making it private
*
* passes {value} to {ref}
*
* WARNING: Be sure to only call this inside a callback that is passed as a ref.
* Otherwise, make sure to cleanup the previous {ref} if it changes. See
* https://github.com/mui/material-ui/issues/13539
*
* Useful if you want to expose the ref of an inner component to the public API
* while still using it inside the component.
* @param ref A ref callback or ref object. If anything falsy, this is a no-op.
*/
function setRef(ref, value) {
if (typeof ref === 'function') {
ref(value);
} else if (ref) {
ref.current = value;
}
}
let globalId = 0;
// TODO React 17: Remove `useGlobalId` once React 17 support is removed
function useGlobalId(idOverride) {
const [defaultId, setDefaultId] = reactExports.useState(idOverride);
const id = idOverride || defaultId;
reactExports.useEffect(() => {
if (defaultId == null) {
// Fallback to this default id when possible.
// Use the incrementing value for client-side rendering only.
// We can't use it server-side.
// If you want to use random values please consider the Birthday Problem: https://en.wikipedia.org/wiki/Birthday_problem
globalId += 1;
setDefaultId(`mui-${globalId}`);
}
}, [defaultId]);
return id;
}
// See https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379 for why
const safeReact = {
...React$1
};
const maybeReactUseId = safeReact.useId;
/**
*
* @example <div id={useId()} />
* @param idOverride
* @returns {string}
*/
function useId(idOverride) {
// React.useId() is only available from React 17.0.0.
if (maybeReactUseId !== undefined) {
const reactId = maybeReactUseId();
return idOverride ?? reactId;
}
// TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler
// eslint-disable-next-line react-hooks/rules-of-hooks -- `React.useId` is invariant at runtime.
return useGlobalId(idOverride);
}
function useControlled({
controlled,
default: defaultProp,
name,
state = 'value'
}) {
// isControlled is ignored in the hook dependency lists as it should never change.
const {
current: isControlled
} = reactExports.useRef(controlled !== undefined);
const [valueState, setValue] = reactExports.useState(defaultProp);
const value = isControlled ? controlled : valueState;
const setValueIfUncontrolled = reactExports.useCallback(newValue => {
if (!isControlled) {
setValue(newValue);
}
}, []);
return [value, setValueIfUncontrolled];
}
/**
* Inspired by https://github.com/facebook/react/issues/14099#issuecomment-440013892
* See RFC in https://github.com/reactjs/rfcs/pull/220
*/
function useEventCallback(fn) {
const ref = reactExports.useRef(fn);
useEnhancedEffect(() => {
ref.current = fn;
});
return reactExports.useRef((...args) =>
// @ts-expect-error hide `this`
(0, ref.current)(...args)).current;
}
/**
* Merges refs into a single memoized callback ref or `null`.
*
* ```tsx
* const rootRef = React.useRef<Instance>(null);
* const refFork = useForkRef(rootRef, props.ref);
*
* return (
* <Root {...props} ref={refFork} />
* );
* ```
*
* @param {Array<React.Ref<Instance> | undefined>} refs The ref array.
* @returns {React.RefCallback<Instance> | null} The new ref callback.
*/
function useForkRef(...refs) {
const cleanupRef = reactExports.useRef(undefined);
const refEffect = reactExports.useCallback(instance => {
const cleanups = refs.map(ref => {
if (ref == null) {
return null;
}
if (typeof ref === 'function') {
const refCallback = ref;
const refCleanup = refCallback(instance);
return typeof refCleanup === 'function' ? refCleanup : () => {
refCallback(null);
};
}
ref.current = instance;
return () => {
ref.current = null;
};
});
return () => {
cleanups.forEach(refCleanup => refCleanup?.());
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, refs);
return reactExports.useMemo(() => {
if (refs.every(ref => ref == null)) {
return null;
}
return value => {
if (cleanupRef.current) {
cleanupRef.current();
cleanupRef.current = undefined;
}
if (value != null) {
cleanupRef.current = refEffect(value);
}
};
// TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler -- intentionally ignoring that the dependency array must be an array literal
// eslint-disable-next-line react-hooks/exhaustive-deps
}, refs);
}
const UNINITIALIZED = {};
/**
* A React.useRef() that is initialized lazily with a function. Note that it accepts an optional
* initialization argument, so the initialization function doesn't need to be an inline closure.
*
* @usage
* const ref = useLazyRef(sortColumns, columns)
*/
function useLazyRef(init, initArg) {
const ref = reactExports.useRef(UNINITIALIZED);
if (ref.current === UNINITIALIZED) {
ref.current = init(initArg);
}
return ref;
}
const EMPTY = [];
/**
* A React.useEffect equivalent that runs once, when the component is mounted.
*/
function useOnMount(fn) {
// TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler -- no need to put `fn` in the dependency array
/* eslint-disable react-hooks/exhaustive-deps */
reactExports.useEffect(fn, EMPTY);
/* eslint-enable react-hooks/exhaustive-deps */
}
class Timeout {
static create() {
return new Timeout();
}
currentId = null;
/**
* Executes `fn` after `delay`, clearing any previously scheduled call.
*/
start(delay, fn) {
this.clear();
this.currentId = setTimeout(() => {
this.currentId = null;
fn();
}, delay);
}
clear = () => {
if (this.currentId !== null) {
clearTimeout(this.currentId);
this.currentId = null;
}
};
disposeEffect = () => {
return this.clear;
};
}
function useTimeout() {
const timeout = useLazyRef(Timeout.create).current;
useOnMount(timeout.disposeEffect);
return timeout;
}
/**
* Returns a boolean indicating if the event's target has :focus-visible
*/
function isFocusVisible(element) {
try {
return element.matches(':focus-visible');
} catch (error) {
}
return false;
}
// A change of the browser zoom change the scrollbar size.
// Credit https://github.com/twbs/bootstrap/blob/488fd8afc535ca3a6ad4dc581f5e89217b6a36ac/js/src/util/scrollbar.js#L14-L18
function getScrollbarSize$1(win = window) {
// https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth#usage_notes
const documentWidth = win.document.documentElement.clientWidth;
return win.innerWidth - documentWidth;
}
const usePreviousProps = value => {
const ref = reactExports.useRef({});
reactExports.useEffect(() => {
ref.current = value;
});
return ref.current;
};
/* eslint no-restricted-syntax: 0, prefer-template: 0, guard-for-in: 0
---
These rules are preventing the performance optimizations below.
*/
/**
* Compose classes from multiple sources.
*
* @example
* ```tsx
* const slots = {
* root: ['root', 'primary'],
* label: ['label'],
* };
*
* const getUtilityClass = (slot) => `MuiButton-${slot}`;
*
* const classes = {
* root: 'my-root-class',
* };
*
* const output = composeClasses(slots, getUtilityClass, classes);
* // {
* // root: 'MuiButton-root MuiButton-primary my-root-class',
* // label: 'MuiButton-label',
* // }
* ```
*
* @param slots a list of classes for each possible slot
* @param getUtilityClass a function to resolve the class based on the slot name
* @param classes the input classes from props
* @returns the resolved classes for all slots
*/
function composeClasses(slots, getUtilityClass, classes = undefined) {
const output = {};
for (const slotName in slots) {
const slot = slots[slotName];
let buffer = '';
let start = true;
for (let i = 0; i < slot.length; i += 1) {
const value = slot[i];
if (value) {
buffer += (start === true ? '' : ' ') + getUtilityClass(value);
start = false;
if (classes && classes[value]) {
buffer += ' ' + classes[value];
}
}
}
output[slotName] = buffer;
}
return output;
}
/**
* Determines if a given element is a DOM element name (i.e. not a React component).
*/
function isHostComponent$1(element) {
return typeof element === 'string';
}
/**
* Type of the ownerState based on the type of an element it applies to.
* This resolves to the provided OwnerState for React components and `undefined` for host components.
* Falls back to `OwnerState | undefined` when the exact type can't be determined in development time.
*/
/**
* Appends the ownerState object to the props, merging with the existing one if necessary.
*
* @param elementType Type of the element that owns the `existingProps`. If the element is a DOM node or undefined, `ownerState` is not applied.
* @param otherProps Props of the element.
* @param ownerState
*/
function appendOwnerState(elementType, otherProps, ownerState) {
if (elementType === undefined || isHostComponent$1(elementType)) {
return otherProps;
}
return {
...otherProps,
ownerState: {
...otherProps.ownerState,
...ownerState
}
};
}
/**
* Extracts event handlers from a given object.
* A prop is considered an event handler if it is a function and its name starts with `on`.
*
* @param object An object to extract event handlers from.
* @param excludeKeys An array of keys to exclude from the returned object.
*/
function extractEventHandlers(object, excludeKeys = []) {
if (object === undefined) {
return {};
}
const result = {};
Object.keys(object).filter(prop => prop.match(/^on[A-Z]/) && typeof object[prop] === 'function' && !excludeKeys.includes(prop)).forEach(prop => {
result[prop] = object[prop];
});
return result;
}
/**
* Removes event handlers from the given object.
* A field is considered an event handler if it is a function with a name beginning with `on`.
*
* @param object Object to remove event handlers from.
* @returns Object with event handlers removed.
*/
function omitEventHandlers(object) {
if (object === undefined) {
return {};
}
const result = {};
Object.keys(object).filter(prop => !(prop.match(/^on[A-Z]/) && typeof object[prop] === 'function')).forEach(prop => {
result[prop] = object[prop];
});
return result;
}
/**
* Merges the slot component internal props (usually coming from a hook)
* with the externally provided ones.
*
* The merge order is (the latter overrides the former):
* 1. The internal props (specified as a getter function to work with get*Props hook result)
* 2. Additional props (specified internally on a Base UI component)
* 3. External props specified on the owner component. These should only be used on a root slot.
* 4. External props specified in the `slotProps.*` prop.
* 5. The `className` prop - combined from all the above.
* @param parameters
* @returns
*/
function mergeSlotProps$1(parameters) {
const {
getSlotProps,
additionalProps,
externalSlotProps,
externalForwardedProps,
className
} = parameters;
if (!getSlotProps) {
// The simpler case - getSlotProps is not defined, so no internal event handlers are defined,
// so we can simply merge all the props without having to worry about extracting event handlers.
const joinedClasses = clsx(additionalProps?.className, className, externalForwardedProps?.className, externalSlotProps?.className);
const mergedStyle = {
...additionalProps?.style,
...externalForwardedProps?.style,
...externalSlotProps?.style
};
const props = {
...additionalProps,
...externalForwardedProps,
...externalSlotProps
};
if (joinedClasses.length > 0) {
props.className = joinedClasses;
}
if (Object.keys(mergedStyle).length > 0) {
props.style = mergedStyle;
}
return {
props,
internalRef: undefined
};
}
// In this case, getSlotProps is responsible for calling the external event handlers.
// We don't need to include them in the merged props because of this.
const eventHandlers = extractEventHandlers({
...externalForwardedProps,
...externalSlotProps
});
const componentsPropsWithoutEventHandlers = omitEventHandlers(externalSlotProps);
const otherPropsWithoutEventHandlers = omitEventHandlers(externalForwardedProps);
const internalSlotProps = getSlotProps(eventHandlers);
// The order of classes is important here.
// Emotion (that we use in libraries consuming Base UI) depends on this order
// to properly override style. It requires the most important classes to be last
// (see https://github.com/mui/material-ui/pull/33205) for the related discussion.
const joinedClasses = clsx(internalSlotProps?.className, additionalProps?.className, className, externalForwardedProps?.className, externalSlotProps?.className);
const mergedStyle = {
...internalSlotProps?.style,
...additionalProps?.style,
...externalForwardedProps?.style,
...externalSlotProps?.style
};
const props = {
...internalSlotProps,
...additionalProps,
...otherPropsWithoutEventHandlers,
...componentsPropsWithoutEventHandlers
};
if (joinedClasses.length > 0) {
props.className = joinedClasses;
}
if (Object.keys(mergedStyle).length > 0) {
props.style = mergedStyle;
}
return {
props,
internalRef: internalSlotProps.ref
};
}
/**
* If `componentProps` is a function, calls it with the provided `ownerState`.
* Otherwise, just returns `componentProps`.
*/
function resolveComponentProps(componentProps, ownerState, slotState) {
if (typeof componentProps === 'function') {
return componentProps(ownerState, slotState);
}
return componentProps;
}
/**
* @ignore - do not document.
* Builds the props to be passed into the slot of an unstyled component.
* It merges the internal props of the component with the ones supplied by the user, allowing to customize the behavior.
* If the slot component is not a host component, it also merges in the `ownerState`.
*
* @param parameters.getSlotProps - A function that returns the props to be passed to the slot component.
*/
function useSlotProps(parameters) {
const {
elementType,
externalSlotProps,
ownerState,
skipResolvingSlotProps = false,
...other
} = parameters;
const resolvedComponentsProps = skipResolvingSlotProps ? {} : resolveComponentProps(externalSlotProps, ownerState);
const {
props: mergedProps,
internalRef
} = mergeSlotProps$1({
...other,
externalSlotProps: resolvedComponentsProps
});
const ref = useForkRef(internalRef, resolvedComponentsProps?.ref, parameters.additionalProps?.ref);
const props = appendOwnerState(elementType, {
...mergedProps,
ref
}, ownerState);
return props;
}
/**
* Returns the ref of a React element handling differences between React 19 and older versions.
* It will throw runtime error if the element is not a valid React element.
*
* @param element React.ReactElement
* @returns React.Ref<any> | null
*/
function getReactElementRef(element) {
// 'ref' is passed as prop in React 19, whereas 'ref' is directly attached to children in older versions
if (parseInt(reactExports.version, 10) >= 19) {
return element?.props?.ref || null;
}
// @ts-expect-error element.ref is not included in the ReactElement type
// https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/70189
return element?.ref || null;
}
const ThemeContext = /*#__PURE__*/reactExports.createContext(null);
function useTheme$2() {
const theme = reactExports.useContext(ThemeContext);
return theme;
}
const hasSymbol = typeof Symbol === 'function' && Symbol.for;
var nested = hasSymbol ? Symbol.for('mui.nested') : '__THEME_NESTED__';
function mergeOuterLocalTheme(outerTheme, localTheme) {
if (typeof localTheme === 'function') {
const mergedTheme = localTheme(outerTheme);
return mergedTheme;
}
return {
...outerTheme,
...localTheme
};
}
/**
* This component takes a `theme` prop.
* It makes the `theme` available down the React tree thanks to React context.
* This component should preferably be used at **the root of your component tree**.
*/
function ThemeProvider$2(props) {
const {
children,
theme: localTheme
} = props;
const outerTheme = useTheme$2();
const theme = reactExports.useMemo(() => {
const output = outerTheme === null ? {
...localTheme
} : mergeOuterLocalTheme(outerTheme, localTheme);
if (output != null) {
output[nested] = outerTheme !== null;
}
return output;
}, [localTheme, outerTheme]);
return /*#__PURE__*/jsxRuntimeExports.jsx(ThemeContext.Provider, {
value: theme,
children: children
});
}
const RtlContext = /*#__PURE__*/reactExports.createContext();
function RtlProvider({
value,
...props
}) {
return /*#__PURE__*/jsxRuntimeExports.jsx(RtlContext.Provider, {
value: value ?? true,
...props
});
}
const useRtl = () => {
const value = reactExports.useContext(RtlContext);
return value ?? false;
};
const PropsContext = /*#__PURE__*/reactExports.createContext(undefined);
function DefaultPropsProvider({
value,
children
}) {
return /*#__PURE__*/jsxRuntimeExports.jsx(PropsContext.Provider, {
value: value,
children: children
});
}
function getThemeProps(params) {
const {
theme,
name,
props
} = params;
if (!theme || !theme.components || !theme.components[name]) {
return props;
}
const config = theme.components[name];
if (config.defaultProps) {
// compatible with v5 signature
return resolveProps(config.defaultProps, props);
}
if (!config.styleOverrides && !config.variants) {
// v6 signature, no property 'defaultProps'
return resolveProps(config, props);
}
return props;
}
function useDefaultProps$1({
props,
name
}) {
const ctx = reactExports.useContext(PropsContext);
return getThemeProps({
props,
name,
theme: {
components: ctx
}
});
}
function useLayerOrder(theme) {
const upperTheme = useTheme$4();
const id = useId() || '';
const {
modularCssLayers
} = theme;
let layerOrder = 'mui.global, mui.components, mui.theme, mui.custom, mui.sx';
if (!modularCssLayers || upperTheme !== null) {
// skip this hook if upper theme exists.
layerOrder = '';
} else if (typeof modularCssLayers === 'string') {
layerOrder = modularCssLayers.replace(/mui(?!\.)/g, layerOrder);
} else {
layerOrder = `@layer ${layerOrder};`;
}
useEnhancedEffect(() => {
const head = document.querySelector('head');
if (!head) {
return;
}
const firstChild = head.firstChild;
if (layerOrder) {
// Only insert if first child doesn't have data-mui-layer-order attribute
if (firstChild && firstChild.hasAttribute?.('data-mui-layer-order') && firstChild.getAttribute('data-mui-layer-order') === id) {
return;
}
const styleElement = document.createElement('style');
styleElement.setAttribute('data-mui-layer-order', id);
styleElement.textContent = layerOrder;
head.prepend(styleElement);
} else {
head.querySelector(`style[data-mui-layer-order="${id}"]`)?.remove();
}
}, [layerOrder, id]);
if (!layerOrder) {
return null;
}
return /*#__PURE__*/jsxRuntimeExports.jsx(GlobalStyles$1, {
styles: layerOrder
});
}
const EMPTY_THEME = {};
function useThemeScoping(themeId, upperTheme, localTheme, isPrivate = false) {
return reactExports.useMemo(() => {
const resolvedTheme = themeId ? upperTheme[themeId] || upperTheme : upperTheme;
if (typeof localTheme === 'function') {
const mergedTheme = localTheme(resolvedTheme);
const result = themeId ? {
...upperTheme,
[themeId]: mergedTheme
} : mergedTheme;
// must return a function for the private theme to NOT merge with the upper theme.
// see the test case "use provided theme from a callback" in ThemeProvider.test.js
if (isPrivate) {
return () => result;
}
return result;
}
return themeId ? {
...upperTheme,
[themeId]: localTheme
} : {
...upperTheme,
...localTheme
};
}, [themeId, upperTheme, localTheme, isPrivate]);
}
/**
* This component makes the `theme` available down the React tree.
* It should preferably be used at **the root of your component tree**.
*
* <ThemeProvider theme={theme}> // existing use case
* <ThemeProvider theme={{ id: theme }}> // theme scoping
*/
function ThemeProvider$1(props) {
const {
children,
theme: localTheme,
themeId
} = props;
const upperTheme = useTheme$4(EMPTY_THEME);
const upperPrivateTheme = useTheme$2() || EMPTY_THEME;
const engineTheme = useThemeScoping(themeId, upperTheme, localTheme);
const privateTheme = useThemeScoping(themeId, upperPrivateTheme, localTheme, true);
const rtlValue = (themeId ? engineTheme[themeId] : engineTheme).direction === 'rtl';
const layerOrder = useLayerOrder(engineTheme);
return /*#__PURE__*/jsxRuntimeExports.jsx(ThemeProvider$2, {
theme: privateTheme,
children: /*#__PURE__*/jsxRuntimeExports.jsx(ThemeContext$1.Provider, {
value: engineTheme,
children: /*#__PURE__*/jsxRuntimeExports.jsx(RtlProvider, {
value: rtlValue,
children: /*#__PURE__*/jsxRuntimeExports.jsxs(DefaultPropsProvider, {
value: themeId ? engineTheme[themeId].components : engineTheme.components,
children: [layerOrder, children]
})
})
})
});
}
/* eslint-disable @typescript-eslint/naming-convention */
// We need to pass an argument as `{ theme }` for PigmentCSS, but we don't want to
// allocate more objects.
const arg = {
theme: undefined
};
/**
* Memoize style function on theme.
* Intended to be used in styled() calls that only need access to the theme.
*/
function unstable_memoTheme(styleFn) {
let lastValue;
let lastTheme;
return function styleMemoized(props) {
let value = lastValue;
if (value === undefined || props.theme !== lastTheme) {
arg.theme = props.theme;
value = preprocessStyles(styleFn(arg));
lastValue = value;
lastTheme = props.theme;
}
return value;
};
}
/**
* Split this component for RSC import
*/
const DEFAULT_MODE_STORAGE_KEY = 'mode';
const DEFAULT_COLOR_SCHEME_STORAGE_KEY = 'color-scheme';
const DEFAULT_ATTRIBUTE = 'data-color-scheme';
function InitColorSchemeScript(options) {
const {
defaultMode = 'system',
defaultLightColorScheme = 'light',
defaultDarkColorScheme = 'dark',
modeStorageKey = DEFAULT_MODE_STORAGE_KEY,
colorSchemeStorageKey = DEFAULT_COLOR_SCHEME_STORAGE_KEY,
attribute: initialAttribute = DEFAULT_ATTRIBUTE,
colorSchemeNode = 'document.documentElement',
nonce
} = options || {};
let setter = '';
let attribute = initialAttribute;
if (initialAttribute === 'class') {
attribute = '.%s';
}
if (initialAttribute === 'data') {
attribute = '[data-%s]';
}
if (attribute.startsWith('.')) {
const selector = attribute.substring(1);
setter += `${colorSchemeNode}.classList.remove('${selector}'.replace('%s', light), '${selector}'.replace('%s', dark));
${colorSchemeNode}.classList.add('${selector}'.replace('%s', colorScheme));`;
}
const matches = attribute.match(/\[([^\]]+)\]/); // case [data-color-scheme=%s] or [data-color-scheme]
if (matches) {
const [attr, value] = matches[1].split('=');
if (!value) {
setter += `${colorSchemeNode}.removeAttribute('${attr}'.replace('%s', light));
${colorSchemeNode}.removeAttribute('${attr}'.replace('%s', dark));`;
}
setter += `
${colorSchemeNode}.setAttribute('${attr}'.replace('%s', colorScheme), ${value ? `${value}.replace('%s', colorScheme)` : '""'});`;
} else {
setter += `${colorSchemeNode}.setAttribute('${attribute}', colorScheme);`;
}
return /*#__PURE__*/jsxRuntimeExports.jsx("script", {
suppressHydrationWarning: true,
nonce: typeof window === 'undefined' ? nonce : ''
// eslint-disable-next-line react/no-danger
,
dangerouslySetInnerHTML: {
__html: `(function() {
try {
let colorScheme = '';
const mode = localStorage.getItem('${modeStorageKey}') || '${defaultMode}';
const dark = localStorage.getItem('${colorSchemeStorageKey}-dark') || '${defaultDarkColorScheme}';
const light = localStorage.getItem('${colorSchemeStorageKey}-light') || '${defaultLightColorScheme}';
if (mode === 'system') {
// handle system mode
const mql = window.matchMedia('(prefers-color-scheme: dark)');
if (mql.matches) {
colorScheme = dark
} else {
colorScheme = light
}
}
if (mode === 'light') {
colorScheme = light;
}
if (mode === 'dark') {
colorScheme = dark;
}
if (colorScheme) {
${setter}
}
} catch(e){}})();`
}
}, "mui-color-scheme-init");
}
function noop$4() {}
const localStorageManager = ({
key,
storageWindow
}) => {
if (!storageWindow && typeof window !== 'undefined') {
storageWindow = window;
}
return {
get(defaultValue) {
if (typeof window === 'undefined') {
return undefined;
}
if (!storageWindow) {
return defaultValue;
}
let value;
try {
value = storageWindow.localStorage.getItem(key);
} catch {
// Unsupported
}
return value || defaultValue;
},
set: value => {
if (storageWindow) {
try {
storageWindow.localStorage.setItem(key, value);
} catch {
// Unsupported
}
}
},
subscribe: handler => {
if (!storageWindow) {
return noop$4;
}
const listener = event => {
const value = event.newValue;
if (event.key === key) {
handler(value);
}
};
storageWindow.addEventListener('storage', listener);
return () => {
storageWindow.removeEventListener('storage', listener);
};
}
};
};
function noop$3() {}
function getSystemMode(mode) {
if (typeof window !== 'undefined' && typeof window.matchMedia === 'function' && mode === 'system') {
const mql = window.matchMedia('(prefers-color-scheme: dark)');
if (mql.matches) {
return 'dark';
}
return 'light';
}
return undefined;
}
function processState(state, callback) {
if (state.mode === 'light' || state.mode === 'system' && state.systemMode === 'light') {
return callback('light');
}
if (state.mode === 'dark' || state.mode === 'system' && state.systemMode === 'dark') {
return callback('dark');
}
return undefined;
}
function getColorScheme(state) {
return processState(state, mode => {
if (mode === 'light') {
return state.lightColorScheme;
}
if (mode === 'dark') {
return state.darkColorScheme;
}
return undefined;
});
}
function useCurrentColorScheme(options) {
const {
defaultMode = 'light',
defaultLightColorScheme,
defaultDarkColorScheme,
supportedColorSchemes = [],
modeStorageKey = DEFAULT_MODE_STORAGE_KEY,
colorSchemeStorageKey = DEFAULT_COLOR_SCHEME_STORAGE_KEY,
storageWindow = typeof window === 'undefined' ? undefined : window,
storageManager = localStorageManager,
noSsr = false
} = options;
const joinedColorSchemes = supportedColorSchemes.join(',');
const isMultiSchemes = supportedColorSchemes.length > 1;
const modeStorage = reactExports.useMemo(() => storageManager?.({
key: modeStorageKey,
storageWindow
}), [storageManager, modeStorageKey, storageWindow]);
const lightStorage = reactExports.useMemo(() => storageManager?.({
key: `${colorSchemeStorageKey}-light`,
storageWindow
}), [storageManager, colorSchemeStorageKey, storageWindow]);
const darkStorage = reactExports.useMemo(() => storageManager?.({
key: `${colorSchemeStorageKey}-dark`,
storageWindow
}), [storageManager, colorSchemeStorageKey, storageWindow]);
const [state, setState] = reactExports.useState(() => {
const initialMode = modeStorage?.get(defaultMode) || defaultMode;
const lightColorScheme = lightStorage?.get(defaultLightColorScheme) || defaultLightColorScheme;
const darkColorScheme = darkStorage?.get(defaultDarkColorScheme) || defaultDarkColorScheme;
return {
mode: initialMode,
systemMode: getSystemMode(initialMode),
lightColorScheme,
darkColorScheme
};
});
const [isClient, setIsClient] = reactExports.useState(noSsr || !isMultiSchemes);
reactExports.useEffect(() => {
setIsClient(true); // to rerender the component after hydration
}, []);
const colorScheme = getColorScheme(state);
const setMode = reactExports.useCallback(mode => {
setState(currentState => {
if (mode === currentState.mode) {
// do nothing if mode does not change
return currentState;
}
const newMode = mode ?? defaultMode;
modeStorage?.set(newMode);
return {
...currentState,
mode: newMode,
systemMode: getSystemMode(newMode)
};
});
}, [modeStorage, defaultMode]);
const setColorScheme = reactExports.useCallback(value => {
if (!value) {
setState(currentState => {
lightStorage?.set(defaultLightColorScheme);
darkStorage?.set(defaultDarkColorScheme);
return {
...currentState,
lightColorScheme: defaultLightColorScheme,
darkColorScheme: defaultDarkColorScheme
};
});
} else if (typeof value === 'string') {
if (value && !joinedColorSchemes.includes(value)) {
console.error(`\`${value}\` does not exist in \`theme.colorSchemes\`.`);
} else {
setState(currentState => {
const newState = {
...currentState
};
processState(currentState, mode => {
if (mode === 'light') {
lightStorage?.set(value);
newState.lightColorScheme = value;
}
if (mode === 'dark') {
darkStorage?.set(value);
newState.darkColorScheme = value;
}
});
return newState;
});
}
} else {
setState(currentState => {
const newState = {
...currentState
};
const newLightColorScheme = value.light === null ? defaultLightColorScheme : value.light;
const newDarkColorScheme = value.dark === null ? defaultDarkColorScheme : value.dark;
if (newLightColorScheme) {
if (!joinedColorSchemes.includes(newLightColorScheme)) {
console.error(`\`${newLightColorScheme}\` does not exist in \`theme.colorSchemes\`.`);
} else {
newState.lightColorScheme = newLightColorScheme;
lightStorage?.set(newLightColorScheme);
}
}
if (newDarkColorScheme) {
if (!joinedColorSchemes.includes(newDarkColorScheme)) {
console.error(`\`${newDarkColorScheme}\` does not exist in \`theme.colorSchemes\`.`);
} else {
newState.darkColorScheme = newDarkColorScheme;
darkStorage?.set(newDarkColorScheme);
}
}
return newState;
});
}
}, [joinedColorSchemes, lightStorage, darkStorage, defaultLightColorScheme, defaultDarkColorScheme]);
const handleMediaQuery = reactExports.useCallback(event => {
if (state.mode === 'system') {
setState(currentState => {
const systemMode = event?.matches ? 'dark' : 'light';
// Early exit, nothing changed.
if (currentState.systemMode === systemMode) {
return currentState;
}
return {
...currentState,
systemMode
};
});
}
}, [state.mode]);
// Ref hack to avoid adding handleMediaQuery as a dep
const mediaListener = reactExports.useRef(handleMediaQuery);
mediaListener.current = handleMediaQuery;
reactExports.useEffect(() => {
if (typeof window.matchMedia !== 'function' || !isMultiSchemes) {
return undefined;
}
const handler = (...args) => mediaListener.current(...args);
// Always listen to System preference
const media = window.matchMedia('(prefers-color-scheme: dark)');
// Intentionally use deprecated listener methods to support iOS & old browsers
media.addListener(handler);
handler(media);
return () => {
media.removeListener(handler);
};
}, [isMultiSchemes]);
// Handle when localStorage has changed
reactExports.useEffect(() => {
if (isMultiSchemes) {
const unsubscribeMode = modeStorage?.subscribe(value => {
if (!value || ['light', 'dark', 'system'].includes(value)) {
setMode(value || defaultMode);
}
}) || noop$3;
const unsubscribeLight = lightStorage?.subscribe(value => {
if (!value || joinedColorSchemes.match(value)) {
setColorScheme({
light: value
});
}
}) || noop$3;
const unsubscribeDark = darkStorage?.subscribe(value => {
if (!value || joinedColorSchemes.match(value)) {
setColorScheme({
dark: value
});
}
}) || noop$3;
return () => {
unsubscribeMode();
unsubscribeLight();
unsubscribeDark();
};
}
return undefined;
}, [setColorScheme, setMode, joinedColorSchemes, defaultMode, storageWindow, isMultiSchemes, modeStorage, lightStorage, darkStorage]);
return {
...state,
mode: isClient ? state.mode : undefined,
systemMode: isClient ? state.systemMode : undefined,
colorScheme: isClient ? colorScheme : undefined,
setMode,
setColorScheme
};
}
const DISABLE_CSS_TRANSITION = '*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}';
function createCssVarsProvider(options) {
const {
themeId,
/**
* This `theme` object needs to follow a certain structure to
* be used correctly by the finel `CssVarsProvider`. It should have a
* `colorSchemes` key with the light and dark (and any other) palette.
* It should also ideally have a vars object created using `prepareCssVars`.
*/
theme: defaultTheme = {},
modeStorageKey: defaultModeStorageKey = DEFAULT_MODE_STORAGE_KEY,
colorSchemeStorageKey: defaultColorSchemeStorageKey = DEFAULT_COLOR_SCHEME_STORAGE_KEY,
disableTransitionOnChange: designSystemTransitionOnChange = false,
defaultColorScheme,
resolveTheme
} = options;
const defaultContext = {
allColorSchemes: [],
colorScheme: undefined,
darkColorScheme: undefined,
lightColorScheme: undefined,
mode: undefined,
setColorScheme: () => {},
setMode: () => {},
systemMode: undefined
};
const ColorSchemeContext = /*#__PURE__*/reactExports.createContext(undefined);
const useColorScheme = () => reactExports.useContext(ColorSchemeContext) || defaultContext;
const defaultColorSchemes = {};
const defaultComponents = {};
function CssVarsProvider(props) {
const {
children,
theme: themeProp,
modeStorageKey = defaultModeStorageKey,
colorSchemeStorageKey = defaultColorSchemeStorageKey,
disableTransitionOnChange = designSystemTransitionOnChange,
storageManager,
storageWindow = typeof window === 'undefined' ? undefined : window,
documentNode = typeof document === 'undefined' ? undefined : document,
colorSchemeNode = typeof document === 'undefined' ? undefined : document.documentElement,
disableNestedContext = false,
disableStyleSheetGeneration = false,
defaultMode: initialMode = 'system',
noSsr
} = props;
const hasMounted = reactExports.useRef(false);
const upperTheme = useTheme$2();
const ctx = reactExports.useContext(ColorSchemeContext);
const nested = !!ctx && !disableNestedContext;
const initialTheme = reactExports.useMemo(() => {
if (themeProp) {
return themeProp;
}
return typeof defaultTheme === 'function' ? defaultTheme() : defaultTheme;
}, [themeProp]);
const scopedTheme = initialTheme[themeId];
const restThemeProp = scopedTheme || initialTheme;
const {
colorSchemes = defaultColorSchemes,
components = defaultComponents,
cssVarPrefix
} = restThemeProp;
const joinedColorSchemes = Object.keys(colorSchemes).filter(k => !!colorSchemes[k]).join(',');
const allColorSchemes = reactExports.useMemo(() => joinedColorSchemes.split(','), [joinedColorSchemes]);
const defaultLightColorScheme = typeof defaultColorScheme === 'string' ? defaultColorScheme : defaultColorScheme.light;
const defaultDarkColorScheme = typeof defaultColorScheme === 'string' ? defaultColorScheme : defaultColorScheme.dark;
const defaultMode = colorSchemes[defaultLightColorScheme] && colorSchemes[defaultDarkColorScheme] ? initialMode : colorSchemes[restThemeProp.defaultColorScheme]?.palette?.mode || restThemeProp.palette?.mode;
// 1. Get the data about the `mode`, `colorScheme`, and setter functions.
const {
mode: stateMode,
setMode,
systemMode,
lightColorScheme,
darkColorScheme,
colorScheme: stateColorScheme,
setColorScheme
} = useCurrentColorScheme({
supportedColorSchemes: allColorSchemes,
defaultLightColorScheme,
defaultDarkColorScheme,
modeStorageKey,
colorSchemeStorageKey,
defaultMode,
storageManager,
storageWindow,
noSsr
});
let mode = stateMode;
let colorScheme = stateColorScheme;
if (nested) {
mode = ctx.mode;
colorScheme = ctx.colorScheme;
}
const memoTheme = reactExports.useMemo(() => {
// `colorScheme` is undefined on the server and hydration phase
const calculatedColorScheme = colorScheme || restThemeProp.defaultColorScheme;
// 2. get the `vars` object that refers to the CSS custom properties
const themeVars = restThemeProp.generateThemeVars?.() || restThemeProp.vars;
// 3. Start composing the theme object
const theme = {
...restThemeProp,
components,
colorSchemes,
cssVarPrefix,
vars: themeVars
};
if (typeof theme.generateSpacing === 'function') {
theme.spacing = theme.generateSpacing();
}
// 4. Resolve the color scheme and merge it to the theme
if (calculatedColorScheme) {
const scheme = colorSchemes[calculatedColorScheme];
if (scheme && typeof scheme === 'object') {
// 4.1 Merge the selected color scheme to the theme
Object.keys(scheme).forEach(schemeKey => {
if (scheme[schemeKey] && typeof scheme[schemeKey] === 'object') {
// shallow merge the 1st level structure of the theme.
theme[schemeKey] = {
...theme[schemeKey],
...scheme[schemeKey]
};
} else {
theme[schemeKey] = scheme[schemeKey];
}
});
}
}
return resolveTheme ? resolveTheme(theme) : theme;
}, [restThemeProp, colorScheme, components, colorSchemes, cssVarPrefix]);
// 5. Declaring effects
// 5.1 Updates the selector value to use the current color scheme which tells CSS to use the proper stylesheet.
const colorSchemeSelector = restThemeProp.colorSchemeSelector;
useEnhancedEffect(() => {
if (colorScheme && colorSchemeNode && colorSchemeSelector && colorSchemeSelector !== 'media') {
const selector = colorSchemeSelector;
let rule = colorSchemeSelector;
if (selector === 'class') {
rule = `.%s`;
}
if (selector === 'data') {
rule = `[data-%s]`;
}
if (selector?.startsWith('data-') && !selector.includes('%s')) {
// 'data-mui-color-scheme' -> '[data-mui-color-scheme="%s"]'
rule = `[${selector}="%s"]`;
}
if (rule.startsWith('.')) {
colorSchemeNode.classList.remove(...allColorSchemes.map(scheme => rule.substring(1).replace('%s', scheme)));
colorSchemeNode.classList.add(rule.substring(1).replace('%s', colorScheme));
} else {
const matches = rule.replace('%s', colorScheme).match(/\[([^\]]+)\]/);
if (matches) {
const [attr, value] = matches[1].split('=');
if (!value) {
// for attributes like `data-theme-dark`, `data-theme-light`
// remove all the existing data attributes before setting the new one
allColorSchemes.forEach(scheme => {
colorSchemeNode.removeAttribute(attr.replace(colorScheme, scheme));
});
}
colorSchemeNode.setAttribute(attr, value ? value.replace(/"|'/g, '') : '');
} else {
colorSchemeNode.setAttribute(rule, colorScheme);
}
}
}
}, [colorScheme, colorSchemeSelector, colorSchemeNode, allColorSchemes]);
// 5.2 Remove the CSS transition when color scheme changes to create instant experience.
// credit: https://github.com/pacocoursey/next-themes/blob/b5c2bad50de2d61ad7b52a9c5cdc801a78507d7a/index.tsx#L313
reactExports.useEffect(() => {
let timer;
if (disableTransitionOnChange && hasMounted.current && documentNode) {
const css = documentNode.createElement('style');
css.appendChild(documentNode.createTextNode(DISABLE_CSS_TRANSITION));
documentNode.head.appendChild(css);
// Force browser repaint
(() => window.getComputedStyle(documentNode.body))();
timer = setTimeout(() => {
documentNode.head.removeChild(css);
}, 1);
}
return () => {
clearTimeout(timer);
};
}, [colorScheme, disableTransitionOnChange, documentNode]);
reactExports.useEffect(() => {
hasMounted.current = true;
return () => {
hasMounted.current = false;
};
}, []);
const contextValue = reactExports.useMemo(() => ({
allColorSchemes,
colorScheme,
darkColorScheme,
lightColorScheme,
mode,
setColorScheme,
setMode: setMode ,
systemMode
}), [allColorSchemes, colorScheme, darkColorScheme, lightColorScheme, mode, setColorScheme, setMode, systemMode, memoTheme.colorSchemeSelector]);
let shouldGenerateStyleSheet = true;
if (disableStyleSheetGeneration || restThemeProp.cssVariables === false || nested && upperTheme?.cssVarPrefix === cssVarPrefix) {
shouldGenerateStyleSheet = false;
}
const element = /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports.Fragment, {
children: [/*#__PURE__*/jsxRuntimeExports.jsx(ThemeProvider$1, {
themeId: scopedTheme ? themeId : undefined,
theme: memoTheme,
children: children
}), shouldGenerateStyleSheet && /*#__PURE__*/jsxRuntimeExports.jsx(GlobalStyles$2, {
styles: memoTheme.generateStyleSheets?.() || []
})]
});
if (nested) {
return element;
}
return /*#__PURE__*/jsxRuntimeExports.jsx(ColorSchemeContext.Provider, {
value: contextValue,
children: element
});
}
const defaultLightColorScheme = typeof defaultColorScheme === 'string' ? defaultColorScheme : defaultColorScheme.light;
const defaultDarkColorScheme = typeof defaultColorScheme === 'string' ? defaultColorScheme : defaultColorScheme.dark;
const getInitColorSchemeScript = params => InitColorSchemeScript({
colorSchemeStorageKey: defaultColorSchemeStorageKey,
defaultLightColorScheme,
defaultDarkColorScheme,
modeStorageKey: defaultModeStorageKey,
...params
});
return {
CssVarsProvider,
useColorScheme,
getInitColorSchemeScript
};
}
/**
* The benefit of this function is to help developers get CSS var from theme without specifying the whole variable
* and they does not need to remember the prefix (defined once).
*/
function createGetCssVar$1(prefix = '') {
function appendVar(...vars) {
if (!vars.length) {
return '';
}
const value = vars[0];
if (typeof value === 'string' && !value.match(/(#|\(|\)|(-?(\d*\.)?\d+)(px|em|%|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc))|^(-?(\d*\.)?\d+)$|(\d+ \d+ \d+)/)) {
return `, var(--${prefix ? `${prefix}-` : ''}${value}${appendVar(...vars.slice(1))})`;
}
return `, ${value}`;
}
// AdditionalVars makes `getCssVar` less strict, so it can be use like this `getCssVar('non-mui-variable')` without type error.
const getCssVar = (field, ...fallbacks) => {
return `var(--${prefix ? `${prefix}-` : ''}${field}${appendVar(...fallbacks)})`;
};
return getCssVar;
}
/**
* This function create an object from keys, value and then assign to target
*
* @param {Object} obj : the target object to be assigned
* @param {string[]} keys
* @param {string | number} value
*
* @example
* const source = {}
* assignNestedKeys(source, ['palette', 'primary'], 'var(--palette-primary)')
* console.log(source) // { palette: { primary: 'var(--palette-primary)' } }
*
* @example
* const source = { palette: { primary: 'var(--palette-primary)' } }
* assignNestedKeys(source, ['palette', 'secondary'], 'var(--palette-secondary)')
* console.log(source) // { palette: { primary: 'var(--palette-primary)', secondary: 'var(--palette-secondary)' } }
*/
const assignNestedKeys = (obj, keys, value, arrayKeys = []) => {
let temp = obj;
keys.forEach((k, index) => {
if (index === keys.length - 1) {
if (Array.isArray(temp)) {
temp[Number(k)] = value;
} else if (temp && typeof temp === 'object') {
temp[k] = value;
}
} else if (temp && typeof temp === 'object') {
if (!temp[k]) {
temp[k] = arrayKeys.includes(k) ? [] : {};
}
temp = temp[k];
}
});
};
/**
*
* @param {Object} obj : source object
* @param {Function} callback : a function that will be called when
* - the deepest key in source object is reached
* - the value of the deepest key is NOT `undefined` | `null`
*
* @example
* walkObjectDeep({ palette: { primary: { main: '#000000' } } }, console.log)
* // ['palette', 'primary', 'main'] '#000000'
*/
const walkObjectDeep = (obj, callback, shouldSkipPaths) => {
function recurse(object, parentKeys = [], arrayKeys = []) {
Object.entries(object).forEach(([key, value]) => {
if (!shouldSkipPaths || shouldSkipPaths && !shouldSkipPaths([...parentKeys, key])) {
if (value !== undefined && value !== null) {
if (typeof value === 'object' && Object.keys(value).length > 0) {
recurse(value, [...parentKeys, key], Array.isArray(value) ? [...arrayKeys, key] : arrayKeys);
} else {
callback([...parentKeys, key], value, arrayKeys);
}
}
}
});
}
recurse(obj);
};
const getCssValue = (keys, value) => {
if (typeof value === 'number') {
if (['lineHeight', 'fontWeight', 'opacity', 'zIndex'].some(prop => keys.includes(prop))) {
// CSS property that are unitless
return value;
}
const lastKey = keys[keys.length - 1];
if (lastKey.toLowerCase().includes('opacity')) {
// opacity values are unitless
return value;
}
return `${value}px`;
}
return value;
};
/**
* a function that parse theme and return { css, vars }
*
* @param {Object} theme
* @param {{
* prefix?: string,
* shouldSkipGeneratingVar?: (objectPathKeys: Array<string>, value: string | number) => boolean
* }} options.
* `prefix`: The prefix of the generated CSS variables. This function does not change the value.
*
* @returns {{ css: Object, vars: Object }} `css` is the stylesheet, `vars` is an object to get css variable (same structure as theme).
*
* @example
* const { css, vars } = parser({
* fontSize: 12,
* lineHeight: 1.2,
* palette: { primary: { 500: 'var(--color)' } }
* }, { prefix: 'foo' })
*
* console.log(css) // { '--foo-fontSize': '12px', '--foo-lineHeight': 1.2, '--foo-palette-primary-500': 'var(--color)' }
* console.log(vars) // { fontSize: 'var(--foo-fontSize)', lineHeight: 'var(--foo-lineHeight)', palette: { primary: { 500: 'var(--foo-palette-primary-500)' } } }
*/
function cssVarsParser(theme, options) {
const {
prefix,
shouldSkipGeneratingVar
} = options || {};
const css = {};
const vars = {};
const varsWithDefaults = {};
walkObjectDeep(theme, (keys, value, arrayKeys) => {
if (typeof value === 'string' || typeof value === 'number') {
if (!shouldSkipGeneratingVar || !shouldSkipGeneratingVar(keys, value)) {
// only create css & var if `shouldSkipGeneratingVar` return false
const cssVar = `--${prefix ? `${prefix}-` : ''}${keys.join('-')}`;
const resolvedValue = getCssValue(keys, value);
Object.assign(css, {
[cssVar]: resolvedValue
});
assignNestedKeys(vars, keys, `var(${cssVar})`, arrayKeys);
assignNestedKeys(varsWithDefaults, keys, `var(${cssVar}, ${resolvedValue})`, arrayKeys);
}
}
}, keys => keys[0] === 'vars' // skip 'vars/*' paths
);
return {
css,
vars,
varsWithDefaults
};
}
function prepareCssVars(theme, parserConfig = {}) {
const {
getSelector = defaultGetSelector,
disableCssColorScheme,
colorSchemeSelector: selector
} = parserConfig;
// @ts-ignore - ignore components do not exist
const {
colorSchemes = {},
components,
defaultColorScheme = 'light',
...otherTheme
} = theme;
const {
vars: rootVars,
css: rootCss,
varsWithDefaults: rootVarsWithDefaults
} = cssVarsParser(otherTheme, parserConfig);
let themeVars = rootVarsWithDefaults;
const colorSchemesMap = {};
const {
[defaultColorScheme]: defaultScheme,
...otherColorSchemes
} = colorSchemes;
Object.entries(otherColorSchemes || {}).forEach(([key, scheme]) => {
const {
vars,
css,
varsWithDefaults
} = cssVarsParser(scheme, parserConfig);
themeVars = deepmerge(themeVars, varsWithDefaults);
colorSchemesMap[key] = {
css,
vars
};
});
if (defaultScheme) {
// default color scheme vars should be merged last to set as default
const {
css,
vars,
varsWithDefaults
} = cssVarsParser(defaultScheme, parserConfig);
themeVars = deepmerge(themeVars, varsWithDefaults);
colorSchemesMap[defaultColorScheme] = {
css,
vars
};
}
function defaultGetSelector(colorScheme, cssObject) {
let rule = selector;
if (selector === 'class') {
rule = '.%s';
}
if (selector === 'data') {
rule = '[data-%s]';
}
if (selector?.startsWith('data-') && !selector.includes('%s')) {
// 'data-joy-color-scheme' -> '[data-joy-color-scheme="%s"]'
rule = `[${selector}="%s"]`;
}
if (colorScheme) {
if (rule === 'media') {
if (theme.defaultColorScheme === colorScheme) {
return ':root';
}
const mode = colorSchemes[colorScheme]?.palette?.mode || colorScheme;
return {
[`@media (prefers-color-scheme: ${mode})`]: {
':root': cssObject
}
};
}
if (rule) {
if (theme.defaultColorScheme === colorScheme) {
return `:root, ${rule.replace('%s', String(colorScheme))}`;
}
return rule.replace('%s', String(colorScheme));
}
}
return ':root';
}
const generateThemeVars = () => {
let vars = {
...rootVars
};
Object.entries(colorSchemesMap).forEach(([, {
vars: schemeVars
}]) => {
vars = deepmerge(vars, schemeVars);
});
return vars;
};
const generateStyleSheets = () => {
const stylesheets = [];
const colorScheme = theme.defaultColorScheme || 'light';
function insertStyleSheet(key, css) {
if (Object.keys(css).length) {
stylesheets.push(typeof key === 'string' ? {
[key]: {
...css
}
} : key);
}
}
insertStyleSheet(getSelector(undefined, {
...rootCss
}), rootCss);
const {
[colorScheme]: defaultSchemeVal,
...other
} = colorSchemesMap;
if (defaultSchemeVal) {
// default color scheme has to come before other color schemes
const {
css
} = defaultSchemeVal;
const cssColorSheme = colorSchemes[colorScheme]?.palette?.mode;
const finalCss = !disableCssColorScheme && cssColorSheme ? {
colorScheme: cssColorSheme,
...css
} : {
...css
};
insertStyleSheet(getSelector(colorScheme, {
...finalCss
}), finalCss);
}
Object.entries(other).forEach(([key, {
css
}]) => {
const cssColorSheme = colorSchemes[key]?.palette?.mode;
const finalCss = !disableCssColorScheme && cssColorSheme ? {
colorScheme: cssColorSheme,
...css
} : {
...css
};
insertStyleSheet(getSelector(key, {
...finalCss
}), finalCss);
});
return stylesheets;
};
return {
vars: themeVars,
generateThemeVars,
generateStyleSheets
};
}
/* eslint-disable import/prefer-default-export */
function createGetColorSchemeSelector(selector) {
return function getColorSchemeSelector(colorScheme) {
if (selector === 'media') {
return `@media (prefers-color-scheme: ${colorScheme})`;
}
if (selector) {
if (selector.startsWith('data-') && !selector.includes('%s')) {
return `[${selector}="${colorScheme}"] &`;
}
if (selector === 'class') {
return `.${colorScheme} &`;
}
if (selector === 'data') {
return `[data-${colorScheme}] &`;
}
return `${selector.replace('%s', colorScheme)} &`;
}
return '&';
};
}
const common = {
black: '#000',
white: '#fff'
};
const grey = {
50: '#fafafa',
100: '#f5f5f5',
200: '#eeeeee',
300: '#e0e0e0',
400: '#bdbdbd',
500: '#9e9e9e',
600: '#757575',
700: '#616161',
800: '#424242',
900: '#212121',
A100: '#f5f5f5',
A200: '#eeeeee',
A400: '#bdbdbd',
A700: '#616161'
};
const purple = {
50: '#f3e5f5',
200: '#ce93d8',
300: '#ba68c8',
400: '#ab47bc',
500: '#9c27b0',
700: '#7b1fa2'};
const red = {
300: '#e57373',
400: '#ef5350',
500: '#f44336',
700: '#d32f2f',
800: '#c62828'};
const orange = {
300: '#ffb74d',
400: '#ffa726',
500: '#ff9800',
700: '#f57c00',
900: '#e65100'};
const blue = {
50: '#e3f2fd',
200: '#90caf9',
400: '#42a5f5',
700: '#1976d2',
800: '#1565c0'};
const lightBlue = {
300: '#4fc3f7',
400: '#29b6f6',
500: '#03a9f4',
700: '#0288d1',
900: '#01579b'};
const green = {
300: '#81c784',
400: '#66bb6a',
500: '#4caf50',
700: '#388e3c',
800: '#2e7d32',
900: '#1b5e20'};
function getLight() {
return {
// 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.6)',
// Disabled text have even lower visual prominence.
disabled: '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: common.white
},
// 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
}
};
}
const light$1 = getLight();
function getDark() {
return {
text: {
primary: common.white,
secondary: 'rgba(255, 255, 255, 0.7)',
disabled: 'rgba(255, 255, 255, 0.5)',
icon: 'rgba(255, 255, 255, 0.5)'
},
divider: 'rgba(255, 255, 255, 0.12)',
background: {
paper: '#121212',
default: '#121212'
},
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
}
};
}
const dark$1 = getDark();
function addLightOrDark(intent, direction, shade, tonalOffset) {
const tonalOffsetLight = tonalOffset.light || tonalOffset;
const 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 getDefaultPrimary(mode = 'light') {
if (mode === 'dark') {
return {
main: blue[200],
light: blue[50],
dark: blue[400]
};
}
return {
main: blue[700],
light: blue[400],
dark: blue[800]
};
}
function getDefaultSecondary(mode = 'light') {
if (mode === 'dark') {
return {
main: purple[200],
light: purple[50],
dark: purple[400]
};
}
return {
main: purple[500],
light: purple[300],
dark: purple[700]
};
}
function getDefaultError(mode = 'light') {
if (mode === 'dark') {
return {
main: red[500],
light: red[300],
dark: red[700]
};
}
return {
main: red[700],
light: red[400],
dark: red[800]
};
}
function getDefaultInfo(mode = 'light') {
if (mode === 'dark') {
return {
main: lightBlue[400],
light: lightBlue[300],
dark: lightBlue[700]
};
}
return {
main: lightBlue[700],
light: lightBlue[500],
dark: lightBlue[900]
};
}
function getDefaultSuccess(mode = 'light') {
if (mode === 'dark') {
return {
main: green[400],
light: green[300],
dark: green[700]
};
}
return {
main: green[800],
light: green[500],
dark: green[900]
};
}
function getDefaultWarning(mode = 'light') {
if (mode === 'dark') {
return {
main: orange[400],
light: orange[300],
dark: orange[700]
};
}
return {
main: '#ed6c02',
// closest to orange[800] that pass 3:1.
light: orange[500],
dark: orange[900]
};
}
function createPalette(palette) {
const {
mode = 'light',
contrastThreshold = 3,
tonalOffset = 0.2,
...other
} = palette;
const primary = palette.primary || getDefaultPrimary(mode);
const secondary = palette.secondary || getDefaultSecondary(mode);
const error = palette.error || getDefaultError(mode);
const info = palette.info || getDefaultInfo(mode);
const success = palette.success || getDefaultSuccess(mode);
const warning = palette.warning || getDefaultWarning(mode);
// 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) {
const contrastText = getContrastRatio(background, dark$1.text.primary) >= contrastThreshold ? dark$1.text.primary : light$1.text.primary;
return contrastText;
}
const augmentColor = ({
color,
name,
mainShade = 500,
lightShade = 300,
darkShade = 700
}) => {
color = {
...color
};
if (!color.main && color[mainShade]) {
color.main = color[mainShade];
}
if (!color.hasOwnProperty('main')) {
throw new Error(formatMuiErrorMessage(11, name ? ` (${name})` : '', mainShade));
}
if (typeof color.main !== 'string') {
throw new Error(formatMuiErrorMessage(12, name ? ` (${name})` : '', JSON.stringify(color.main)));
}
addLightOrDark(color, 'light', lightShade, tonalOffset);
addLightOrDark(color, 'dark', darkShade, tonalOffset);
if (!color.contrastText) {
color.contrastText = getContrastText(color.main);
}
return color;
};
let modeHydrated;
if (mode === 'light') {
modeHydrated = getLight();
} else if (mode === 'dark') {
modeHydrated = getDark();
}
const paletteOutput = deepmerge({
// A collection of common colors.
common: {
...common
},
// prevent mutable object.
// The palette mode, can be light or dark.
mode,
// The colors used to represent primary interface elements for a user.
primary: augmentColor({
color: primary,
name: 'primary'
}),
// The colors used to represent secondary interface elements for a user.
secondary: augmentColor({
color: secondary,
name: 'secondary',
mainShade: 'A400',
lightShade: 'A200',
darkShade: 'A700'
}),
// The colors used to represent interface elements that the user should be made aware of.
error: augmentColor({
color: error,
name: 'error'
}),
// The colors used to represent potentially dangerous actions or important messages.
warning: augmentColor({
color: warning,
name: 'warning'
}),
// The colors used to present information to the user that is neutral and not necessarily important.
info: augmentColor({
color: info,
name: 'info'
}),
// The colors used to indicate the successful completion of an action that user triggered.
success: augmentColor({
color: success,
name: 'success'
}),
// The grey colors.
grey,
// Used by `getContrastText()` to maximize the contrast between
// the background and the text.
contrastThreshold,
// Takes a background color and returns the text color that maximizes the contrast.
getContrastText,
// Generate a rich color object.
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,
// The light and dark mode object.
...modeHydrated
}, other);
return paletteOutput;
}
function prepareTypographyVars(typography) {
const vars = {};
const entries = Object.entries(typography);
entries.forEach(entry => {
const [key, value] = entry;
if (typeof value === 'object') {
vars[key] = `${value.fontStyle ? `${value.fontStyle} ` : ''}${value.fontVariant ? `${value.fontVariant} ` : ''}${value.fontWeight ? `${value.fontWeight} ` : ''}${value.fontStretch ? `${value.fontStretch} ` : ''}${value.fontSize || ''}${value.lineHeight ? `/${value.lineHeight} ` : ''}${value.fontFamily || ''}`;
}
});
return vars;
}
function createMixins(breakpoints, mixins) {
return {
toolbar: {
minHeight: 56,
[breakpoints.up('xs')]: {
'@media (orientation: landscape)': {
minHeight: 48
}
},
[breakpoints.up('sm')]: {
minHeight: 64
}
},
...mixins
};
}
function round$2(value) {
return Math.round(value * 1e5) / 1e5;
}
const caseAllCaps = {
textTransform: 'uppercase'
};
const defaultFontFamily = '"Roboto", "Helvetica", "Arial", sans-serif';
/**
* @see @link{https://m2.material.io/design/typography/the-type-system.html}
* @see @link{https://m2.material.io/design/typography/understanding-typography.html}
*/
function createTypography(palette, typography) {
const {
fontFamily = defaultFontFamily,
// The default font size of the Material Specification.
fontSize = 14,
// px
fontWeightLight = 300,
fontWeightRegular = 400,
fontWeightMedium = 500,
fontWeightBold = 700,
// Tell MUI what's the font-size on the html element.
// 16px is the default font-size used by browsers.
htmlFontSize = 16,
// Apply the CSS properties to all the variants.
allVariants,
pxToRem: pxToRem2,
...other
} = typeof typography === 'function' ? typography(palette) : typography;
const coef = fontSize / 14;
const pxToRem = pxToRem2 || (size => `${size / htmlFontSize * coef}rem`);
const buildVariant = (fontWeight, size, lineHeight, letterSpacing, casing) => ({
fontFamily,
fontWeight,
fontSize: pxToRem(size),
// Unitless following https://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/
lineHeight,
// The letter spacing was designed for the Roboto font-family. Using the same letter-spacing
// across font-families can cause issues with the kerning.
...(fontFamily === defaultFontFamily ? {
letterSpacing: `${round$2(letterSpacing / size)}em`
} : {}),
...casing,
...allVariants
});
const 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),
// TODO v6: Remove handling of 'inherit' variant from the theme as it is already handled in Material UI's Typography component. Also, remember to remove the associated types.
inherit: {
fontFamily: 'inherit',
fontWeight: 'inherit',
fontSize: 'inherit',
lineHeight: 'inherit',
letterSpacing: 'inherit'
}
};
return deepmerge({
htmlFontSize,
pxToRem,
fontFamily,
fontSize,
fontWeightLight,
fontWeightRegular,
fontWeightMedium,
fontWeightBold,
...variants
}, other, {
clone: false // No need to clone deep
});
}
const shadowKeyUmbraOpacity = 0.2;
const shadowKeyPenumbraOpacity = 0.14;
const shadowAmbientShadowOpacity = 0.12;
function createShadow(...px) {
return [`${px[0]}px ${px[1]}px ${px[2]}px ${px[3]}px rgba(0,0,0,${shadowKeyUmbraOpacity})`, `${px[4]}px ${px[5]}px ${px[6]}px ${px[7]}px rgba(0,0,0,${shadowKeyPenumbraOpacity})`, `${px[8]}px ${px[9]}px ${px[10]}px ${px[11]}px rgba(0,0,0,${shadowAmbientShadowOpacity})`].join(',');
}
// Values from https://github.com/material-components/material-components-web/blob/be8747f94574669cb5e7add1a7c54fa41a89cec7/packages/mdc-elevation/_variables.scss
const 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)];
// 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.
const 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://m2.material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations
// to learn when use what timing
const 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 `${Math.round(milliseconds)}ms`;
}
function getAutoHeightDuration(height) {
if (!height) {
return 0;
}
const constant = height / 36;
// https://www.desmos.com/calculator/vbrp3ggqet
return Math.min(Math.round((4 + 15 * constant ** 0.25 + constant / 5) * 10), 3000);
}
function createTransitions(inputTransitions) {
const mergedEasing = {
...easing,
...inputTransitions.easing
};
const mergedDuration = {
...duration,
...inputTransitions.duration
};
const create = (props = ['all'], options = {}) => {
const {
duration: durationOption = mergedDuration.standard,
easing: easingOption = mergedEasing.easeInOut,
delay = 0,
...other
} = options;
return (Array.isArray(props) ? props : [props]).map(animatedProp => `${animatedProp} ${typeof durationOption === 'string' ? durationOption : formatMs(durationOption)} ${easingOption} ${typeof delay === 'string' ? delay : formatMs(delay)}`).join(',');
};
return {
getAutoHeightDuration,
create,
...inputTransitions,
easing: mergedEasing,
duration: mergedDuration
};
}
// We need to centralize the zIndex definitions as they work
// like global values in the browser.
const zIndex = {
mobileStepper: 1000,
fab: 1050,
speedDial: 1050,
appBar: 1100,
drawer: 1200,
modal: 1300,
snackbar: 1400,
tooltip: 1500
};
/* eslint-disable import/prefer-default-export */
function isSerializable(val) {
return isPlainObject(val) || typeof val === 'undefined' || typeof val === 'string' || typeof val === 'boolean' || typeof val === 'number' || Array.isArray(val);
}
/**
* `baseTheme` usually comes from `createTheme()` or `extendTheme()`.
*
* This function is intended to be used with zero-runtime CSS-in-JS like Pigment CSS
* For example, in a Next.js project:
*
* ```js
* // next.config.js
* const { extendTheme } = require('@mui/material/styles');
*
* const theme = extendTheme();
* // `.toRuntimeSource` is Pigment CSS specific to create a theme that is available at runtime.
* theme.toRuntimeSource = stringifyTheme;
*
* module.exports = withPigment({
* theme,
* });
* ```
*/
function stringifyTheme(baseTheme = {}) {
const serializableTheme = {
...baseTheme
};
function serializeTheme(object) {
const array = Object.entries(object);
// eslint-disable-next-line no-plusplus
for (let index = 0; index < array.length; index++) {
const [key, value] = array[index];
if (!isSerializable(value) || key.startsWith('unstable_')) {
delete object[key];
} else if (isPlainObject(value)) {
object[key] = {
...value
};
serializeTheme(object[key]);
}
}
}
serializeTheme(serializableTheme);
return `import { unstable_createBreakpoints as createBreakpoints, createTransitions } from '@mui/material/styles';
const theme = ${JSON.stringify(serializableTheme, null, 2)};
theme.breakpoints = createBreakpoints(theme.breakpoints || {});
theme.transitions = createTransitions(theme.transitions || {});
export default theme;`;
}
function createThemeNoVars(options = {}, ...args) {
const {
breakpoints: breakpointsInput,
mixins: mixinsInput = {},
spacing: spacingInput,
palette: paletteInput = {},
transitions: transitionsInput = {},
typography: typographyInput = {},
shape: shapeInput,
...other
} = options;
if (options.vars &&
// The error should throw only for the root theme creation because user is not allowed to use a custom node `vars`.
// `generateThemeVars` is the closest identifier for checking that the `options` is a result of `createTheme` with CSS variables so that user can create new theme for nested ThemeProvider.
options.generateThemeVars === undefined) {
throw new Error(formatMuiErrorMessage(20));
}
const palette = createPalette(paletteInput);
const systemTheme = createTheme$1(options);
let muiTheme = deepmerge(systemTheme, {
mixins: createMixins(systemTheme.breakpoints, mixinsInput),
palette,
// Don't use [...shadows] until you've verified its transpiled code is not invoking the iterator protocol.
shadows: shadows.slice(),
typography: createTypography(palette, typographyInput),
transitions: createTransitions(transitionsInput),
zIndex: {
...zIndex
}
});
muiTheme = deepmerge(muiTheme, other);
muiTheme = args.reduce((acc, argument) => deepmerge(acc, argument), muiTheme);
muiTheme.unstable_sxConfig = {
...defaultSxConfig,
...other?.unstable_sxConfig
};
muiTheme.unstable_sx = function sx(props) {
return styleFunctionSx({
sx: props,
theme: this
});
};
muiTheme.toRuntimeSource = stringifyTheme; // for Pigment CSS integration
return muiTheme;
}
// Inspired by https://github.com/material-components/material-components-ios/blob/bca36107405594d5b7b16265a5b0ed698f85a5ee/components/Elevation/src/UIColor%2BMaterialElevation.m#L61
function getOverlayAlpha(elevation) {
let alphaValue;
if (elevation < 1) {
alphaValue = 5.11916 * elevation ** 2;
} else {
alphaValue = 4.5 * Math.log(elevation + 1) + 2;
}
return Math.round(alphaValue * 10) / 1000;
}
const defaultDarkOverlays = [...Array(25)].map((_, index) => {
if (index === 0) {
return 'none';
}
const overlay = getOverlayAlpha(index);
return `linear-gradient(rgba(255 255 255 / ${overlay}), rgba(255 255 255 / ${overlay}))`;
});
function getOpacity(mode) {
return {
inputPlaceholder: mode === 'dark' ? 0.5 : 0.42,
inputUnderline: mode === 'dark' ? 0.7 : 0.42,
switchTrackDisabled: mode === 'dark' ? 0.2 : 0.12,
switchTrack: mode === 'dark' ? 0.3 : 0.38
};
}
function getOverlays(mode) {
return mode === 'dark' ? defaultDarkOverlays : [];
}
function createColorScheme(options) {
const {
palette: paletteInput = {
mode: 'light'
},
// need to cast to avoid module augmentation test
opacity,
overlays,
...rest
} = options;
const palette = createPalette(paletteInput);
return {
palette,
opacity: {
...getOpacity(palette.mode),
...opacity
},
overlays: overlays || getOverlays(palette.mode),
...rest
};
}
function shouldSkipGeneratingVar(keys) {
return !!keys[0].match(/(cssVarPrefix|colorSchemeSelector|modularCssLayers|rootSelector|typography|mixins|breakpoints|direction|transitions)/) || !!keys[0].match(/sxConfig$/) ||
// ends with sxConfig
keys[0] === 'palette' && !!keys[1]?.match(/(mode|contrastThreshold|tonalOffset)/);
}
/**
* @internal These variables should not appear in the :root stylesheet when the `defaultColorScheme="dark"`
*/
const excludeVariablesFromRoot = cssVarPrefix => [...[...Array(25)].map((_, index) => `--${cssVarPrefix ? `${cssVarPrefix}-` : ''}overlays-${index}`), `--${cssVarPrefix ? `${cssVarPrefix}-` : ''}palette-AppBar-darkBg`, `--${cssVarPrefix ? `${cssVarPrefix}-` : ''}palette-AppBar-darkColor`];
var defaultGetSelector = theme => (colorScheme, css) => {
const root = theme.rootSelector || ':root';
const selector = theme.colorSchemeSelector;
let rule = selector;
if (selector === 'class') {
rule = '.%s';
}
if (selector === 'data') {
rule = '[data-%s]';
}
if (selector?.startsWith('data-') && !selector.includes('%s')) {
// 'data-mui-color-scheme' -> '[data-mui-color-scheme="%s"]'
rule = `[${selector}="%s"]`;
}
if (theme.defaultColorScheme === colorScheme) {
if (colorScheme === 'dark') {
const excludedVariables = {};
excludeVariablesFromRoot(theme.cssVarPrefix).forEach(cssVar => {
excludedVariables[cssVar] = css[cssVar];
delete css[cssVar];
});
if (rule === 'media') {
return {
[root]: css,
[`@media (prefers-color-scheme: dark)`]: {
[root]: excludedVariables
}
};
}
if (rule) {
return {
[rule.replace('%s', colorScheme)]: excludedVariables,
[`${root}, ${rule.replace('%s', colorScheme)}`]: css
};
}
return {
[root]: {
...css,
...excludedVariables
}
};
}
if (rule && rule !== 'media') {
return `${root}, ${rule.replace('%s', String(colorScheme))}`;
}
} else if (colorScheme) {
if (rule === 'media') {
return {
[`@media (prefers-color-scheme: ${String(colorScheme)})`]: {
[root]: css
}
};
}
if (rule) {
return rule.replace('%s', String(colorScheme));
}
}
return root;
};
function assignNode(obj, keys) {
keys.forEach(k => {
if (!obj[k]) {
obj[k] = {};
}
});
}
function setColor(obj, key, defaultValue) {
if (!obj[key] && defaultValue) {
obj[key] = defaultValue;
}
}
function toRgb(color) {
if (typeof color !== 'string' || !color.startsWith('hsl')) {
return color;
}
return hslToRgb(color);
}
function setColorChannel(obj, key) {
if (!(`${key}Channel` in obj)) {
// custom channel token is not provided, generate one.
// if channel token can't be generated, show a warning.
obj[`${key}Channel`] = private_safeColorChannel(toRgb(obj[key]));
}
}
function getSpacingVal(spacingInput) {
if (typeof spacingInput === 'number') {
return `${spacingInput}px`;
}
if (typeof spacingInput === 'string' || typeof spacingInput === 'function' || Array.isArray(spacingInput)) {
return spacingInput;
}
return '8px';
}
const silent = fn => {
try {
return fn();
} catch (error) {
// ignore error
}
return undefined;
};
const createGetCssVar = (cssVarPrefix = 'mui') => createGetCssVar$1(cssVarPrefix);
function attachColorScheme$1(colorSchemes, scheme, restTheme, colorScheme) {
if (!scheme) {
return undefined;
}
scheme = scheme === true ? {} : scheme;
const mode = colorScheme === 'dark' ? 'dark' : 'light';
if (!restTheme) {
colorSchemes[colorScheme] = createColorScheme({
...scheme,
palette: {
mode,
...scheme?.palette
}
});
return undefined;
}
const {
palette,
...muiTheme
} = createThemeNoVars({
...restTheme,
palette: {
mode,
...scheme?.palette
}
});
colorSchemes[colorScheme] = {
...scheme,
palette,
opacity: {
...getOpacity(mode),
...scheme?.opacity
},
overlays: scheme?.overlays || getOverlays(mode)
};
return muiTheme;
}
/**
* A default `createThemeWithVars` comes with a single color scheme, either `light` or `dark` based on the `defaultColorScheme`.
* This is better suited for apps that only need a single color scheme.
*
* To enable built-in `light` and `dark` color schemes, either:
* 1. provide a `colorSchemeSelector` to define how the color schemes will change.
* 2. provide `colorSchemes.dark` will set `colorSchemeSelector: 'media'` by default.
*/
function createThemeWithVars(options = {}, ...args) {
const {
colorSchemes: colorSchemesInput = {
light: true
},
defaultColorScheme: defaultColorSchemeInput,
disableCssColorScheme = false,
cssVarPrefix = 'mui',
shouldSkipGeneratingVar: shouldSkipGeneratingVar$1 = shouldSkipGeneratingVar,
colorSchemeSelector: selector = colorSchemesInput.light && colorSchemesInput.dark ? 'media' : undefined,
rootSelector = ':root',
...input
} = options;
const firstColorScheme = Object.keys(colorSchemesInput)[0];
const defaultColorScheme = defaultColorSchemeInput || (colorSchemesInput.light && firstColorScheme !== 'light' ? 'light' : firstColorScheme);
const getCssVar = createGetCssVar(cssVarPrefix);
const {
[defaultColorScheme]: defaultSchemeInput,
light: builtInLight,
dark: builtInDark,
...customColorSchemes
} = colorSchemesInput;
const colorSchemes = {
...customColorSchemes
};
let defaultScheme = defaultSchemeInput;
// For built-in light and dark color schemes, ensure that the value is valid if they are the default color scheme.
if (defaultColorScheme === 'dark' && !('dark' in colorSchemesInput) || defaultColorScheme === 'light' && !('light' in colorSchemesInput)) {
defaultScheme = true;
}
if (!defaultScheme) {
throw new Error(formatMuiErrorMessage(21, defaultColorScheme));
}
// Create the palette for the default color scheme, either `light`, `dark`, or custom color scheme.
const muiTheme = attachColorScheme$1(colorSchemes, defaultScheme, input, defaultColorScheme);
if (builtInLight && !colorSchemes.light) {
attachColorScheme$1(colorSchemes, builtInLight, undefined, 'light');
}
if (builtInDark && !colorSchemes.dark) {
attachColorScheme$1(colorSchemes, builtInDark, undefined, 'dark');
}
let theme = {
defaultColorScheme,
...muiTheme,
cssVarPrefix,
colorSchemeSelector: selector,
rootSelector,
getCssVar,
colorSchemes,
font: {
...prepareTypographyVars(muiTheme.typography),
...muiTheme.font
},
spacing: getSpacingVal(input.spacing)
};
Object.keys(theme.colorSchemes).forEach(key => {
const palette = theme.colorSchemes[key].palette;
const setCssVarColor = cssVar => {
const tokens = cssVar.split('-');
const color = tokens[1];
const colorToken = tokens[2];
return getCssVar(cssVar, palette[color][colorToken]);
};
// attach black & white channels to common node
if (palette.mode === 'light') {
setColor(palette.common, 'background', '#fff');
setColor(palette.common, 'onBackground', '#000');
}
if (palette.mode === 'dark') {
setColor(palette.common, 'background', '#000');
setColor(palette.common, 'onBackground', '#fff');
}
// assign component variables
assignNode(palette, ['Alert', 'AppBar', 'Avatar', 'Button', 'Chip', 'FilledInput', 'LinearProgress', 'Skeleton', 'Slider', 'SnackbarContent', 'SpeedDialAction', 'StepConnector', 'StepContent', 'Switch', 'TableCell', 'Tooltip']);
if (palette.mode === 'light') {
setColor(palette.Alert, 'errorColor', private_safeDarken(palette.error.light, 0.6));
setColor(palette.Alert, 'infoColor', private_safeDarken(palette.info.light, 0.6));
setColor(palette.Alert, 'successColor', private_safeDarken(palette.success.light, 0.6));
setColor(palette.Alert, 'warningColor', private_safeDarken(palette.warning.light, 0.6));
setColor(palette.Alert, 'errorFilledBg', setCssVarColor('palette-error-main'));
setColor(palette.Alert, 'infoFilledBg', setCssVarColor('palette-info-main'));
setColor(palette.Alert, 'successFilledBg', setCssVarColor('palette-success-main'));
setColor(palette.Alert, 'warningFilledBg', setCssVarColor('palette-warning-main'));
setColor(palette.Alert, 'errorFilledColor', silent(() => palette.getContrastText(palette.error.main)));
setColor(palette.Alert, 'infoFilledColor', silent(() => palette.getContrastText(palette.info.main)));
setColor(palette.Alert, 'successFilledColor', silent(() => palette.getContrastText(palette.success.main)));
setColor(palette.Alert, 'warningFilledColor', silent(() => palette.getContrastText(palette.warning.main)));
setColor(palette.Alert, 'errorStandardBg', private_safeLighten(palette.error.light, 0.9));
setColor(palette.Alert, 'infoStandardBg', private_safeLighten(palette.info.light, 0.9));
setColor(palette.Alert, 'successStandardBg', private_safeLighten(palette.success.light, 0.9));
setColor(palette.Alert, 'warningStandardBg', private_safeLighten(palette.warning.light, 0.9));
setColor(palette.Alert, 'errorIconColor', setCssVarColor('palette-error-main'));
setColor(palette.Alert, 'infoIconColor', setCssVarColor('palette-info-main'));
setColor(palette.Alert, 'successIconColor', setCssVarColor('palette-success-main'));
setColor(palette.Alert, 'warningIconColor', setCssVarColor('palette-warning-main'));
setColor(palette.AppBar, 'defaultBg', setCssVarColor('palette-grey-100'));
setColor(palette.Avatar, 'defaultBg', setCssVarColor('palette-grey-400'));
setColor(palette.Button, 'inheritContainedBg', setCssVarColor('palette-grey-300'));
setColor(palette.Button, 'inheritContainedHoverBg', setCssVarColor('palette-grey-A100'));
setColor(palette.Chip, 'defaultBorder', setCssVarColor('palette-grey-400'));
setColor(palette.Chip, 'defaultAvatarColor', setCssVarColor('palette-grey-700'));
setColor(palette.Chip, 'defaultIconColor', setCssVarColor('palette-grey-700'));
setColor(palette.FilledInput, 'bg', 'rgba(0, 0, 0, 0.06)');
setColor(palette.FilledInput, 'hoverBg', 'rgba(0, 0, 0, 0.09)');
setColor(palette.FilledInput, 'disabledBg', 'rgba(0, 0, 0, 0.12)');
setColor(palette.LinearProgress, 'primaryBg', private_safeLighten(palette.primary.main, 0.62));
setColor(palette.LinearProgress, 'secondaryBg', private_safeLighten(palette.secondary.main, 0.62));
setColor(palette.LinearProgress, 'errorBg', private_safeLighten(palette.error.main, 0.62));
setColor(palette.LinearProgress, 'infoBg', private_safeLighten(palette.info.main, 0.62));
setColor(palette.LinearProgress, 'successBg', private_safeLighten(palette.success.main, 0.62));
setColor(palette.LinearProgress, 'warningBg', private_safeLighten(palette.warning.main, 0.62));
setColor(palette.Skeleton, 'bg', `rgba(${setCssVarColor('palette-text-primaryChannel')} / 0.11)`);
setColor(palette.Slider, 'primaryTrack', private_safeLighten(palette.primary.main, 0.62));
setColor(palette.Slider, 'secondaryTrack', private_safeLighten(palette.secondary.main, 0.62));
setColor(palette.Slider, 'errorTrack', private_safeLighten(palette.error.main, 0.62));
setColor(palette.Slider, 'infoTrack', private_safeLighten(palette.info.main, 0.62));
setColor(palette.Slider, 'successTrack', private_safeLighten(palette.success.main, 0.62));
setColor(palette.Slider, 'warningTrack', private_safeLighten(palette.warning.main, 0.62));
const snackbarContentBackground = private_safeEmphasize(palette.background.default, 0.8);
setColor(palette.SnackbarContent, 'bg', snackbarContentBackground);
setColor(palette.SnackbarContent, 'color', silent(() => palette.getContrastText(snackbarContentBackground)));
setColor(palette.SpeedDialAction, 'fabHoverBg', private_safeEmphasize(palette.background.paper, 0.15));
setColor(palette.StepConnector, 'border', setCssVarColor('palette-grey-400'));
setColor(palette.StepContent, 'border', setCssVarColor('palette-grey-400'));
setColor(palette.Switch, 'defaultColor', setCssVarColor('palette-common-white'));
setColor(palette.Switch, 'defaultDisabledColor', setCssVarColor('palette-grey-100'));
setColor(palette.Switch, 'primaryDisabledColor', private_safeLighten(palette.primary.main, 0.62));
setColor(palette.Switch, 'secondaryDisabledColor', private_safeLighten(palette.secondary.main, 0.62));
setColor(palette.Switch, 'errorDisabledColor', private_safeLighten(palette.error.main, 0.62));
setColor(palette.Switch, 'infoDisabledColor', private_safeLighten(palette.info.main, 0.62));
setColor(palette.Switch, 'successDisabledColor', private_safeLighten(palette.success.main, 0.62));
setColor(palette.Switch, 'warningDisabledColor', private_safeLighten(palette.warning.main, 0.62));
setColor(palette.TableCell, 'border', private_safeLighten(private_safeAlpha(palette.divider, 1), 0.88));
setColor(palette.Tooltip, 'bg', private_safeAlpha(palette.grey[700], 0.92));
}
if (palette.mode === 'dark') {
setColor(palette.Alert, 'errorColor', private_safeLighten(palette.error.light, 0.6));
setColor(palette.Alert, 'infoColor', private_safeLighten(palette.info.light, 0.6));
setColor(palette.Alert, 'successColor', private_safeLighten(palette.success.light, 0.6));
setColor(palette.Alert, 'warningColor', private_safeLighten(palette.warning.light, 0.6));
setColor(palette.Alert, 'errorFilledBg', setCssVarColor('palette-error-dark'));
setColor(palette.Alert, 'infoFilledBg', setCssVarColor('palette-info-dark'));
setColor(palette.Alert, 'successFilledBg', setCssVarColor('palette-success-dark'));
setColor(palette.Alert, 'warningFilledBg', setCssVarColor('palette-warning-dark'));
setColor(palette.Alert, 'errorFilledColor', silent(() => palette.getContrastText(palette.error.dark)));
setColor(palette.Alert, 'infoFilledColor', silent(() => palette.getContrastText(palette.info.dark)));
setColor(palette.Alert, 'successFilledColor', silent(() => palette.getContrastText(palette.success.dark)));
setColor(palette.Alert, 'warningFilledColor', silent(() => palette.getContrastText(palette.warning.dark)));
setColor(palette.Alert, 'errorStandardBg', private_safeDarken(palette.error.light, 0.9));
setColor(palette.Alert, 'infoStandardBg', private_safeDarken(palette.info.light, 0.9));
setColor(palette.Alert, 'successStandardBg', private_safeDarken(palette.success.light, 0.9));
setColor(palette.Alert, 'warningStandardBg', private_safeDarken(palette.warning.light, 0.9));
setColor(palette.Alert, 'errorIconColor', setCssVarColor('palette-error-main'));
setColor(palette.Alert, 'infoIconColor', setCssVarColor('palette-info-main'));
setColor(palette.Alert, 'successIconColor', setCssVarColor('palette-success-main'));
setColor(palette.Alert, 'warningIconColor', setCssVarColor('palette-warning-main'));
setColor(palette.AppBar, 'defaultBg', setCssVarColor('palette-grey-900'));
setColor(palette.AppBar, 'darkBg', setCssVarColor('palette-background-paper')); // specific for dark mode
setColor(palette.AppBar, 'darkColor', setCssVarColor('palette-text-primary')); // specific for dark mode
setColor(palette.Avatar, 'defaultBg', setCssVarColor('palette-grey-600'));
setColor(palette.Button, 'inheritContainedBg', setCssVarColor('palette-grey-800'));
setColor(palette.Button, 'inheritContainedHoverBg', setCssVarColor('palette-grey-700'));
setColor(palette.Chip, 'defaultBorder', setCssVarColor('palette-grey-700'));
setColor(palette.Chip, 'defaultAvatarColor', setCssVarColor('palette-grey-300'));
setColor(palette.Chip, 'defaultIconColor', setCssVarColor('palette-grey-300'));
setColor(palette.FilledInput, 'bg', 'rgba(255, 255, 255, 0.09)');
setColor(palette.FilledInput, 'hoverBg', 'rgba(255, 255, 255, 0.13)');
setColor(palette.FilledInput, 'disabledBg', 'rgba(255, 255, 255, 0.12)');
setColor(palette.LinearProgress, 'primaryBg', private_safeDarken(palette.primary.main, 0.5));
setColor(palette.LinearProgress, 'secondaryBg', private_safeDarken(palette.secondary.main, 0.5));
setColor(palette.LinearProgress, 'errorBg', private_safeDarken(palette.error.main, 0.5));
setColor(palette.LinearProgress, 'infoBg', private_safeDarken(palette.info.main, 0.5));
setColor(palette.LinearProgress, 'successBg', private_safeDarken(palette.success.main, 0.5));
setColor(palette.LinearProgress, 'warningBg', private_safeDarken(palette.warning.main, 0.5));
setColor(palette.Skeleton, 'bg', `rgba(${setCssVarColor('palette-text-primaryChannel')} / 0.13)`);
setColor(palette.Slider, 'primaryTrack', private_safeDarken(palette.primary.main, 0.5));
setColor(palette.Slider, 'secondaryTrack', private_safeDarken(palette.secondary.main, 0.5));
setColor(palette.Slider, 'errorTrack', private_safeDarken(palette.error.main, 0.5));
setColor(palette.Slider, 'infoTrack', private_safeDarken(palette.info.main, 0.5));
setColor(palette.Slider, 'successTrack', private_safeDarken(palette.success.main, 0.5));
setColor(palette.Slider, 'warningTrack', private_safeDarken(palette.warning.main, 0.5));
const snackbarContentBackground = private_safeEmphasize(palette.background.default, 0.98);
setColor(palette.SnackbarContent, 'bg', snackbarContentBackground);
setColor(palette.SnackbarContent, 'color', silent(() => palette.getContrastText(snackbarContentBackground)));
setColor(palette.SpeedDialAction, 'fabHoverBg', private_safeEmphasize(palette.background.paper, 0.15));
setColor(palette.StepConnector, 'border', setCssVarColor('palette-grey-600'));
setColor(palette.StepContent, 'border', setCssVarColor('palette-grey-600'));
setColor(palette.Switch, 'defaultColor', setCssVarColor('palette-grey-300'));
setColor(palette.Switch, 'defaultDisabledColor', setCssVarColor('palette-grey-600'));
setColor(palette.Switch, 'primaryDisabledColor', private_safeDarken(palette.primary.main, 0.55));
setColor(palette.Switch, 'secondaryDisabledColor', private_safeDarken(palette.secondary.main, 0.55));
setColor(palette.Switch, 'errorDisabledColor', private_safeDarken(palette.error.main, 0.55));
setColor(palette.Switch, 'infoDisabledColor', private_safeDarken(palette.info.main, 0.55));
setColor(palette.Switch, 'successDisabledColor', private_safeDarken(palette.success.main, 0.55));
setColor(palette.Switch, 'warningDisabledColor', private_safeDarken(palette.warning.main, 0.55));
setColor(palette.TableCell, 'border', private_safeDarken(private_safeAlpha(palette.divider, 1), 0.68));
setColor(palette.Tooltip, 'bg', private_safeAlpha(palette.grey[700], 0.92));
}
// MUI X - DataGrid needs this token.
setColorChannel(palette.background, 'default');
// added for consistency with the `background.default` token
setColorChannel(palette.background, 'paper');
setColorChannel(palette.common, 'background');
setColorChannel(palette.common, 'onBackground');
setColorChannel(palette, 'divider');
Object.keys(palette).forEach(color => {
const colors = palette[color];
// The default palettes (primary, secondary, error, info, success, and warning) errors are handled by the above `createTheme(...)`.
if (color !== 'tonalOffset' && colors && typeof colors === 'object') {
// Silent the error for custom palettes.
if (colors.main) {
setColor(palette[color], 'mainChannel', private_safeColorChannel(toRgb(colors.main)));
}
if (colors.light) {
setColor(palette[color], 'lightChannel', private_safeColorChannel(toRgb(colors.light)));
}
if (colors.dark) {
setColor(palette[color], 'darkChannel', private_safeColorChannel(toRgb(colors.dark)));
}
if (colors.contrastText) {
setColor(palette[color], 'contrastTextChannel', private_safeColorChannel(toRgb(colors.contrastText)));
}
if (color === 'text') {
// Text colors: text.primary, text.secondary
setColorChannel(palette[color], 'primary');
setColorChannel(palette[color], 'secondary');
}
if (color === 'action') {
// Action colors: action.active, action.selected
if (colors.active) {
setColorChannel(palette[color], 'active');
}
if (colors.selected) {
setColorChannel(palette[color], 'selected');
}
}
}
});
});
theme = args.reduce((acc, argument) => deepmerge(acc, argument), theme);
const parserConfig = {
prefix: cssVarPrefix,
disableCssColorScheme,
shouldSkipGeneratingVar: shouldSkipGeneratingVar$1,
getSelector: defaultGetSelector(theme)
};
const {
vars,
generateThemeVars,
generateStyleSheets
} = prepareCssVars(theme, parserConfig);
theme.vars = vars;
Object.entries(theme.colorSchemes[theme.defaultColorScheme]).forEach(([key, value]) => {
theme[key] = value;
});
theme.generateThemeVars = generateThemeVars;
theme.generateStyleSheets = generateStyleSheets;
theme.generateSpacing = function generateSpacing() {
return createSpacing(input.spacing, createUnarySpacing(this));
};
theme.getColorSchemeSelector = createGetColorSchemeSelector(selector);
theme.spacing = theme.generateSpacing();
theme.shouldSkipGeneratingVar = shouldSkipGeneratingVar$1;
theme.unstable_sxConfig = {
...defaultSxConfig,
...input?.unstable_sxConfig
};
theme.unstable_sx = function sx(props) {
return styleFunctionSx({
sx: props,
theme: this
});
};
theme.toRuntimeSource = stringifyTheme; // for Pigment CSS integration
return theme;
}
// eslint-disable-next-line consistent-return
function attachColorScheme(theme, scheme, colorScheme) {
if (!theme.colorSchemes) {
return undefined;
}
if (colorScheme) {
theme.colorSchemes[scheme] = {
...(colorScheme !== true && colorScheme),
palette: createPalette({
...(colorScheme === true ? {} : colorScheme.palette),
mode: scheme
}) // cast type to skip module augmentation test
};
}
}
/**
* Generate a theme base on the options received.
* @param options Takes an incomplete theme object and adds the missing parts.
* @param args Deep merge the arguments with the about to be returned theme.
* @returns A complete, ready-to-use theme object.
*/
function createTheme(options = {},
// cast type to skip module augmentation test
...args) {
const {
palette,
cssVariables = false,
colorSchemes: initialColorSchemes = !palette ? {
light: true
} : undefined,
defaultColorScheme: initialDefaultColorScheme = palette?.mode,
...rest
} = options;
const defaultColorSchemeInput = initialDefaultColorScheme || 'light';
const defaultScheme = initialColorSchemes?.[defaultColorSchemeInput];
const colorSchemesInput = {
...initialColorSchemes,
...(palette ? {
[defaultColorSchemeInput]: {
...(typeof defaultScheme !== 'boolean' && defaultScheme),
palette
}
} : undefined)
};
if (cssVariables === false) {
if (!('colorSchemes' in options)) {
// Behaves exactly as v5
return createThemeNoVars(options, ...args);
}
let paletteOptions = palette;
if (!('palette' in options)) {
if (colorSchemesInput[defaultColorSchemeInput]) {
if (colorSchemesInput[defaultColorSchemeInput] !== true) {
paletteOptions = colorSchemesInput[defaultColorSchemeInput].palette;
} else if (defaultColorSchemeInput === 'dark') {
// @ts-ignore to prevent the module augmentation test from failing
paletteOptions = {
mode: 'dark'
};
}
}
}
const theme = createThemeNoVars({
...options,
palette: paletteOptions
}, ...args);
theme.defaultColorScheme = defaultColorSchemeInput;
theme.colorSchemes = colorSchemesInput;
if (theme.palette.mode === 'light') {
theme.colorSchemes.light = {
...(colorSchemesInput.light !== true && colorSchemesInput.light),
palette: theme.palette
};
attachColorScheme(theme, 'dark', colorSchemesInput.dark);
}
if (theme.palette.mode === 'dark') {
theme.colorSchemes.dark = {
...(colorSchemesInput.dark !== true && colorSchemesInput.dark),
palette: theme.palette
};
attachColorScheme(theme, 'light', colorSchemesInput.light);
}
return theme;
}
if (!palette && !('light' in colorSchemesInput) && defaultColorSchemeInput === 'light') {
colorSchemesInput.light = true;
}
return createThemeWithVars({
...rest,
colorSchemes: colorSchemesInput,
defaultColorScheme: defaultColorSchemeInput,
...(typeof cssVariables !== 'boolean' && cssVariables)
}, ...args);
}
const defaultTheme$1 = createTheme();
function useTheme$1() {
const theme = useTheme$3(defaultTheme$1);
return theme[THEME_ID] || theme;
}
// copied from @mui/system/createStyled
function slotShouldForwardProp(prop) {
return prop !== 'ownerState' && prop !== 'theme' && prop !== 'sx' && prop !== 'as';
}
const rootShouldForwardProp = prop => slotShouldForwardProp(prop) && prop !== 'classes';
const styled = createStyled({
themeId: THEME_ID,
defaultTheme: defaultTheme$1,
rootShouldForwardProp
});
function ThemeProviderNoVars({
theme: themeInput,
...props
}) {
const scopedTheme = THEME_ID in themeInput ? themeInput[THEME_ID] : undefined;
return /*#__PURE__*/jsxRuntimeExports.jsx(ThemeProvider$1, {
...props,
themeId: scopedTheme ? THEME_ID : undefined,
theme: scopedTheme || themeInput
});
}
const defaultConfig = {
colorSchemeStorageKey: 'mui-color-scheme',
defaultLightColorScheme: 'light',
defaultDarkColorScheme: 'dark',
modeStorageKey: 'mui-mode'
};
const {
CssVarsProvider: InternalCssVarsProvider} = createCssVarsProvider({
themeId: THEME_ID,
// @ts-ignore ignore module augmentation tests
theme: () => createTheme({
cssVariables: true
}),
colorSchemeStorageKey: defaultConfig.colorSchemeStorageKey,
modeStorageKey: defaultConfig.modeStorageKey,
defaultColorScheme: {
light: defaultConfig.defaultLightColorScheme,
dark: defaultConfig.defaultDarkColorScheme
},
resolveTheme: theme => {
const newTheme = {
...theme,
typography: createTypography(theme.palette, theme.typography)
};
newTheme.unstable_sx = function sx(props) {
return styleFunctionSx({
sx: props,
theme: this
});
};
return newTheme;
}
});
/**
* TODO: remove this export in v7
* @deprecated
* The `CssVarsProvider` component has been deprecated and ported into `ThemeProvider`.
*
* You should use `ThemeProvider` and `createTheme()` instead:
*
* ```diff
* - import { CssVarsProvider, extendTheme } from '@mui/material/styles';
* + import { ThemeProvider, createTheme } from '@mui/material/styles';
*
* - const theme = extendTheme();
* + const theme = createTheme({
* + cssVariables: true,
* + colorSchemes: { light: true, dark: true },
* + });
*
* - <CssVarsProvider theme={theme}>
* + <ThemeProvider theme={theme}>
* ```
*
* To see the full documentation, check out https://mui.com/material-ui/customization/css-theme-variables/usage/.
*/
const CssVarsProvider = InternalCssVarsProvider;
function ThemeProvider({
theme,
...props
}) {
const noVarsTheme = reactExports.useMemo(() => {
if (typeof theme === 'function') {
return theme;
}
const muiTheme = THEME_ID in theme ? theme[THEME_ID] : theme;
if (!('colorSchemes' in muiTheme)) {
if (!('vars' in muiTheme)) {
// For non-CSS variables themes, set `vars` to null to prevent theme inheritance from the upper theme.
// The example use case is the docs demo that uses ThemeProvider to customize the theme while the upper theme is using CSS variables.
return {
...theme,
vars: null
};
}
return theme;
}
return null;
}, [theme]);
if (noVarsTheme) {
return /*#__PURE__*/jsxRuntimeExports.jsx(ThemeProviderNoVars, {
theme: noVarsTheme,
...props
});
}
return /*#__PURE__*/jsxRuntimeExports.jsx(CssVarsProvider, {
theme: theme,
...props
});
}
function GlobalStyles(props) {
return /*#__PURE__*/jsxRuntimeExports.jsx(GlobalStyles$1, {
...props,
defaultTheme: defaultTheme$1,
themeId: THEME_ID
});
}
function globalCss(styles) {
return function GlobalStylesWrapper(props) {
return (
/*#__PURE__*/
// Pigment CSS `globalCss` support callback with theme inside an object but `GlobalStyles` support theme as a callback value.
jsxRuntimeExports.jsx(GlobalStyles, {
styles: typeof styles === 'function' ? theme => styles({
theme,
...props
}) : styles
})
);
};
}
// eslint-disable-next-line @typescript-eslint/naming-convention
function internal_createExtendSxProp() {
return extendSxProp$1;
}
const memoTheme = unstable_memoTheme;
function useDefaultProps(params) {
return useDefaultProps$1(params);
}
function getSvgIconUtilityClass(slot) {
return generateUtilityClass('MuiSvgIcon', slot);
}
generateUtilityClasses('MuiSvgIcon', ['root', 'colorPrimary', 'colorSecondary', 'colorAction', 'colorError', 'colorDisabled', 'fontSizeInherit', 'fontSizeSmall', 'fontSizeMedium', 'fontSizeLarge']);
const useUtilityClasses$r = ownerState => {
const {
color,
fontSize,
classes
} = ownerState;
const slots = {
root: ['root', color !== 'inherit' && `color${capitalize(color)}`, `fontSize${capitalize(fontSize)}`]
};
return composeClasses(slots, getSvgIconUtilityClass, classes);
};
const SvgIconRoot = styled('svg', {
name: 'MuiSvgIcon',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, ownerState.color !== 'inherit' && styles[`color${capitalize(ownerState.color)}`], styles[`fontSize${capitalize(ownerState.fontSize)}`]];
}
})(memoTheme(({
theme
}) => ({
userSelect: 'none',
width: '1em',
height: '1em',
display: 'inline-block',
flexShrink: 0,
transition: theme.transitions?.create?.('fill', {
duration: (theme.vars ?? theme).transitions?.duration?.shorter
}),
variants: [{
props: props => !props.hasSvgAsChild,
style: {
// the <svg> will define the property that has `currentColor`
// for example heroicons uses fill="none" and stroke="currentColor"
fill: 'currentColor'
}
}, {
props: {
fontSize: 'inherit'
},
style: {
fontSize: 'inherit'
}
}, {
props: {
fontSize: 'small'
},
style: {
fontSize: theme.typography?.pxToRem?.(20) || '1.25rem'
}
}, {
props: {
fontSize: 'medium'
},
style: {
fontSize: theme.typography?.pxToRem?.(24) || '1.5rem'
}
}, {
props: {
fontSize: 'large'
},
style: {
fontSize: theme.typography?.pxToRem?.(35) || '2.1875rem'
}
},
// TODO v5 deprecate color prop, v6 remove for sx
...Object.entries((theme.vars ?? theme).palette).filter(([, value]) => value && value.main).map(([color]) => ({
props: {
color
},
style: {
color: (theme.vars ?? theme).palette?.[color]?.main
}
})), {
props: {
color: 'action'
},
style: {
color: (theme.vars ?? theme).palette?.action?.active
}
}, {
props: {
color: 'disabled'
},
style: {
color: (theme.vars ?? theme).palette?.action?.disabled
}
}, {
props: {
color: 'inherit'
},
style: {
color: undefined
}
}]
})));
const SvgIcon$1 = /*#__PURE__*/reactExports.forwardRef(function SvgIcon(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiSvgIcon'
});
const {
children,
className,
color = 'inherit',
component = 'svg',
fontSize = 'medium',
htmlColor,
inheritViewBox = false,
titleAccess,
viewBox = '0 0 24 24',
...other
} = props;
const hasSvgAsChild = /*#__PURE__*/reactExports.isValidElement(children) && children.type === 'svg';
const ownerState = {
...props,
color,
component,
fontSize,
instanceFontSize: inProps.fontSize,
inheritViewBox,
viewBox,
hasSvgAsChild
};
const more = {};
if (!inheritViewBox) {
more.viewBox = viewBox;
}
const classes = useUtilityClasses$r(ownerState);
return /*#__PURE__*/jsxRuntimeExports.jsxs(SvgIconRoot, {
as: component,
className: clsx(classes.root, className),
focusable: "false",
color: htmlColor,
"aria-hidden": titleAccess ? undefined : true,
role: titleAccess ? 'img' : undefined,
ref: ref,
...more,
...other,
...(hasSvgAsChild && children.props),
ownerState: ownerState,
children: [hasSvgAsChild ? children.props.children : children, titleAccess ? /*#__PURE__*/jsxRuntimeExports.jsx("title", {
children: titleAccess
}) : null]
});
});
SvgIcon$1.muiName = 'SvgIcon';
function createSvgIcon(path, displayName) {
function Component(props, ref) {
return /*#__PURE__*/jsxRuntimeExports.jsx(SvgIcon$1, {
"data-testid": `${displayName}Icon`,
ref: ref,
...props,
children: path
});
}
Component.muiName = SvgIcon$1.muiName;
return /*#__PURE__*/reactExports.memo(/*#__PURE__*/reactExports.forwardRef(Component));
}
function mergeSlotProps(externalSlotProps, defaultSlotProps) {
if (!externalSlotProps) {
return defaultSlotProps;
}
if (typeof externalSlotProps === 'function' || typeof defaultSlotProps === 'function') {
return ownerState => {
const defaultSlotPropsValue = typeof defaultSlotProps === 'function' ? defaultSlotProps(ownerState) : defaultSlotProps;
const externalSlotPropsValue = typeof externalSlotProps === 'function' ? externalSlotProps({
...ownerState,
...defaultSlotPropsValue
}) : externalSlotProps;
const className = clsx(ownerState?.className, defaultSlotPropsValue?.className, externalSlotPropsValue?.className);
return {
...defaultSlotPropsValue,
...externalSlotPropsValue,
...(!!className && {
className
}),
...(defaultSlotPropsValue?.style && externalSlotPropsValue?.style && {
style: {
...defaultSlotPropsValue.style,
...externalSlotPropsValue.style
}
}),
...(defaultSlotPropsValue?.sx && externalSlotPropsValue?.sx && {
sx: [...(Array.isArray(defaultSlotPropsValue.sx) ? defaultSlotPropsValue.sx : [defaultSlotPropsValue.sx]), ...(Array.isArray(externalSlotPropsValue.sx) ? externalSlotPropsValue.sx : [externalSlotPropsValue.sx])]
})
};
};
}
const typedDefaultSlotProps = defaultSlotProps;
const className = clsx(typedDefaultSlotProps?.className, externalSlotProps?.className);
return {
...defaultSlotProps,
...externalSlotProps,
...(!!className && {
className
}),
...(typedDefaultSlotProps?.style && externalSlotProps?.style && {
style: {
...typedDefaultSlotProps.style,
...externalSlotProps.style
}
}),
...(typedDefaultSlotProps?.sx && externalSlotProps?.sx && {
sx: [...(Array.isArray(typedDefaultSlotProps.sx) ? typedDefaultSlotProps.sx : [typedDefaultSlotProps.sx]), ...(Array.isArray(externalSlotProps.sx) ? externalSlotProps.sx : [externalSlotProps.sx])]
})
};
}
/**
* Lazy initialization container for the Ripple instance. This improves
* performance by delaying mounting the ripple until it's needed.
*/
class LazyRipple {
/** React ref to the ripple instance */
/** If the ripple component should be mounted */
/** Promise that resolves when the ripple component is mounted */
/** If the ripple component has been mounted */
/** React state hook setter */
static create() {
return new LazyRipple();
}
static use() {
/* eslint-disable */
const ripple = useLazyRef(LazyRipple.create).current;
const [shouldMount, setShouldMount] = reactExports.useState(false);
ripple.shouldMount = shouldMount;
ripple.setShouldMount = setShouldMount;
reactExports.useEffect(ripple.mountEffect, [shouldMount]);
/* eslint-enable */
return ripple;
}
constructor() {
this.ref = {
current: null
};
this.mounted = null;
this.didMount = false;
this.shouldMount = false;
this.setShouldMount = null;
}
mount() {
if (!this.mounted) {
this.mounted = createControlledPromise();
this.shouldMount = true;
this.setShouldMount(this.shouldMount);
}
return this.mounted;
}
mountEffect = () => {
if (this.shouldMount && !this.didMount) {
if (this.ref.current !== null) {
this.didMount = true;
this.mounted.resolve();
}
}
};
/* Ripple API */
start(...args) {
this.mount().then(() => this.ref.current?.start(...args));
}
stop(...args) {
this.mount().then(() => this.ref.current?.stop(...args));
}
pulsate(...args) {
this.mount().then(() => this.ref.current?.pulsate(...args));
}
}
function useLazyRipple() {
return LazyRipple.use();
}
function createControlledPromise() {
let resolve;
let reject;
const p = new Promise((resolveFn, rejectFn) => {
resolve = resolveFn;
reject = rejectFn;
});
p.resolve = resolve;
p.reject = reject;
return p;
}
function _objectWithoutPropertiesLoose(r, e) {
if (null == r) return {};
var t = {};
for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
if (-1 !== e.indexOf(n)) continue;
t[n] = r[n];
}
return t;
}
function _setPrototypeOf(t, e) {
return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
return t.__proto__ = e, t;
}, _setPrototypeOf(t, e);
}
function _inheritsLoose(t, o) {
t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
}
var reactDomExports = requireReactDom();
var ReactDOM = /*@__PURE__*/getDefaultExportFromCjs(reactDomExports);
var config = {
disabled: false
};
var TransitionGroupContext = React.createContext(null);
var forceReflow = function forceReflow(node) {
return node.scrollTop;
};
var UNMOUNTED = 'unmounted';
var EXITED = 'exited';
var ENTERING = 'entering';
var ENTERED = 'entered';
var EXITING = 'exiting';
/**
* The Transition component lets you describe a transition from one component
* state to another _over time_ with a simple declarative API. Most commonly
* it's used to animate the mounting and unmounting of a component, but can also
* be used to describe in-place transition states as well.
*
* ---
*
* **Note**: `Transition` is a platform-agnostic base component. If you're using
* transitions in CSS, you'll probably want to use
* [`CSSTransition`](https://reactcommunity.org/react-transition-group/css-transition)
* instead. It inherits all the features of `Transition`, but contains
* additional features necessary to play nice with CSS transitions (hence the
* name of the component).
*
* ---
*
* By default the `Transition` component does not alter the behavior of the
* component it renders, it only tracks "enter" and "exit" states for the
* components. It's up to you to give meaning and effect to those states. For
* example we can add styles to a component when it enters or exits:
*
* ```jsx
* import { Transition } from 'react-transition-group';
*
* const duration = 300;
*
* const defaultStyle = {
* transition: `opacity ${duration}ms ease-in-out`,
* opacity: 0,
* }
*
* const transitionStyles = {
* entering: { opacity: 1 },
* entered: { opacity: 1 },
* exiting: { opacity: 0 },
* exited: { opacity: 0 },
* };
*
* const Fade = ({ in: inProp }) => (
* <Transition in={inProp} timeout={duration}>
* {state => (
* <div style={{
* ...defaultStyle,
* ...transitionStyles[state]
* }}>
* I'm a fade Transition!
* </div>
* )}
* </Transition>
* );
* ```
*
* There are 4 main states a Transition can be in:
* - `'entering'`
* - `'entered'`
* - `'exiting'`
* - `'exited'`
*
* Transition state is toggled via the `in` prop. When `true` the component
* begins the "Enter" stage. During this stage, the component will shift from
* its current transition state, to `'entering'` for the duration of the
* transition and then to the `'entered'` stage once it's complete. Let's take
* the following example (we'll use the
* [useState](https://reactjs.org/docs/hooks-reference.html#usestate) hook):
*
* ```jsx
* function App() {
* const [inProp, setInProp] = useState(false);
* return (
* <div>
* <Transition in={inProp} timeout={500}>
* {state => (
* // ...
* )}
* </Transition>
* <button onClick={() => setInProp(true)}>
* Click to Enter
* </button>
* </div>
* );
* }
* ```
*
* When the button is clicked the component will shift to the `'entering'` state
* and stay there for 500ms (the value of `timeout`) before it finally switches
* to `'entered'`.
*
* When `in` is `false` the same thing happens except the state moves from
* `'exiting'` to `'exited'`.
*/
var Transition = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(Transition, _React$Component);
function Transition(props, context) {
var _this;
_this = _React$Component.call(this, props, context) || this;
var parentGroup = context; // In the context of a TransitionGroup all enters are really appears
var appear = parentGroup && !parentGroup.isMounting ? props.enter : props.appear;
var initialStatus;
_this.appearStatus = null;
if (props.in) {
if (appear) {
initialStatus = EXITED;
_this.appearStatus = ENTERING;
} else {
initialStatus = ENTERED;
}
} else {
if (props.unmountOnExit || props.mountOnEnter) {
initialStatus = UNMOUNTED;
} else {
initialStatus = EXITED;
}
}
_this.state = {
status: initialStatus
};
_this.nextCallback = null;
return _this;
}
Transition.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) {
var nextIn = _ref.in;
if (nextIn && prevState.status === UNMOUNTED) {
return {
status: EXITED
};
}
return null;
} // getSnapshotBeforeUpdate(prevProps) {
// let nextStatus = null
// if (prevProps !== this.props) {
// const { status } = this.state
// if (this.props.in) {
// if (status !== ENTERING && status !== ENTERED) {
// nextStatus = ENTERING
// }
// } else {
// if (status === ENTERING || status === ENTERED) {
// nextStatus = EXITING
// }
// }
// }
// return { nextStatus }
// }
;
var _proto = Transition.prototype;
_proto.componentDidMount = function componentDidMount() {
this.updateStatus(true, this.appearStatus);
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
var nextStatus = null;
if (prevProps !== this.props) {
var status = this.state.status;
if (this.props.in) {
if (status !== ENTERING && status !== ENTERED) {
nextStatus = ENTERING;
}
} else {
if (status === ENTERING || status === ENTERED) {
nextStatus = EXITING;
}
}
}
this.updateStatus(false, nextStatus);
};
_proto.componentWillUnmount = function componentWillUnmount() {
this.cancelNextCallback();
};
_proto.getTimeouts = function getTimeouts() {
var timeout = this.props.timeout;
var exit, enter, appear;
exit = enter = appear = timeout;
if (timeout != null && typeof timeout !== 'number') {
exit = timeout.exit;
enter = timeout.enter; // TODO: remove fallback for next major
appear = timeout.appear !== undefined ? timeout.appear : enter;
}
return {
exit: exit,
enter: enter,
appear: appear
};
};
_proto.updateStatus = function updateStatus(mounting, nextStatus) {
if (mounting === void 0) {
mounting = false;
}
if (nextStatus !== null) {
// nextStatus will always be ENTERING or EXITING.
this.cancelNextCallback();
if (nextStatus === ENTERING) {
if (this.props.unmountOnExit || this.props.mountOnEnter) {
var node = this.props.nodeRef ? this.props.nodeRef.current : ReactDOM.findDOMNode(this); // https://github.com/reactjs/react-transition-group/pull/749
// With unmountOnExit or mountOnEnter, the enter animation should happen at the transition between `exited` and `entering`.
// To make the animation happen, we have to separate each rendering and avoid being processed as batched.
if (node) forceReflow(node);
}
this.performEnter(mounting);
} else {
this.performExit();
}
} else if (this.props.unmountOnExit && this.state.status === EXITED) {
this.setState({
status: UNMOUNTED
});
}
};
_proto.performEnter = function performEnter(mounting) {
var _this2 = this;
var enter = this.props.enter;
var appearing = this.context ? this.context.isMounting : mounting;
var _ref2 = this.props.nodeRef ? [appearing] : [ReactDOM.findDOMNode(this), appearing],
maybeNode = _ref2[0],
maybeAppearing = _ref2[1];
var timeouts = this.getTimeouts();
var enterTimeout = appearing ? timeouts.appear : timeouts.enter; // no enter animation skip right to ENTERED
// if we are mounting and running this it means appear _must_ be set
if (!mounting && !enter || config.disabled) {
this.safeSetState({
status: ENTERED
}, function () {
_this2.props.onEntered(maybeNode);
});
return;
}
this.props.onEnter(maybeNode, maybeAppearing);
this.safeSetState({
status: ENTERING
}, function () {
_this2.props.onEntering(maybeNode, maybeAppearing);
_this2.onTransitionEnd(enterTimeout, function () {
_this2.safeSetState({
status: ENTERED
}, function () {
_this2.props.onEntered(maybeNode, maybeAppearing);
});
});
});
};
_proto.performExit = function performExit() {
var _this3 = this;
var exit = this.props.exit;
var timeouts = this.getTimeouts();
var maybeNode = this.props.nodeRef ? undefined : ReactDOM.findDOMNode(this); // no exit animation skip right to EXITED
if (!exit || config.disabled) {
this.safeSetState({
status: EXITED
}, function () {
_this3.props.onExited(maybeNode);
});
return;
}
this.props.onExit(maybeNode);
this.safeSetState({
status: EXITING
}, function () {
_this3.props.onExiting(maybeNode);
_this3.onTransitionEnd(timeouts.exit, function () {
_this3.safeSetState({
status: EXITED
}, function () {
_this3.props.onExited(maybeNode);
});
});
});
};
_proto.cancelNextCallback = function cancelNextCallback() {
if (this.nextCallback !== null) {
this.nextCallback.cancel();
this.nextCallback = null;
}
};
_proto.safeSetState = function safeSetState(nextState, callback) {
// This shouldn't be necessary, but there are weird race conditions with
// setState callbacks and unmounting in testing, so always make sure that
// we can cancel any pending setState callbacks after we unmount.
callback = this.setNextCallback(callback);
this.setState(nextState, callback);
};
_proto.setNextCallback = function setNextCallback(callback) {
var _this4 = this;
var active = true;
this.nextCallback = function (event) {
if (active) {
active = false;
_this4.nextCallback = null;
callback(event);
}
};
this.nextCallback.cancel = function () {
active = false;
};
return this.nextCallback;
};
_proto.onTransitionEnd = function onTransitionEnd(timeout, handler) {
this.setNextCallback(handler);
var node = this.props.nodeRef ? this.props.nodeRef.current : ReactDOM.findDOMNode(this);
var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener;
if (!node || doesNotHaveTimeoutOrListener) {
setTimeout(this.nextCallback, 0);
return;
}
if (this.props.addEndListener) {
var _ref3 = this.props.nodeRef ? [this.nextCallback] : [node, this.nextCallback],
maybeNode = _ref3[0],
maybeNextCallback = _ref3[1];
this.props.addEndListener(maybeNode, maybeNextCallback);
}
if (timeout != null) {
setTimeout(this.nextCallback, timeout);
}
};
_proto.render = function render() {
var status = this.state.status;
if (status === UNMOUNTED) {
return null;
}
var _this$props = this.props,
children = _this$props.children;
_this$props.in;
_this$props.mountOnEnter;
_this$props.unmountOnExit;
_this$props.appear;
_this$props.enter;
_this$props.exit;
_this$props.timeout;
_this$props.addEndListener;
_this$props.onEnter;
_this$props.onEntering;
_this$props.onEntered;
_this$props.onExit;
_this$props.onExiting;
_this$props.onExited;
_this$props.nodeRef;
var childProps = _objectWithoutPropertiesLoose(_this$props, ["children", "in", "mountOnEnter", "unmountOnExit", "appear", "enter", "exit", "timeout", "addEndListener", "onEnter", "onEntering", "onEntered", "onExit", "onExiting", "onExited", "nodeRef"]);
return (
/*#__PURE__*/
// allows for nested Transitions
React.createElement(TransitionGroupContext.Provider, {
value: null
}, typeof children === 'function' ? children(status, childProps) : React.cloneElement(React.Children.only(children), childProps))
);
};
return Transition;
}(React.Component);
Transition.contextType = TransitionGroupContext;
Transition.propTypes = {}; // Name the function so it is clearer in the documentation
function noop$2() {}
Transition.defaultProps = {
in: false,
mountOnEnter: false,
unmountOnExit: false,
appear: false,
enter: true,
exit: true,
onEnter: noop$2,
onEntering: noop$2,
onEntered: noop$2,
onExit: noop$2,
onExiting: noop$2,
onExited: noop$2
};
Transition.UNMOUNTED = UNMOUNTED;
Transition.EXITED = EXITED;
Transition.ENTERING = ENTERING;
Transition.ENTERED = ENTERED;
Transition.EXITING = EXITING;
function _assertThisInitialized(e) {
if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return e;
}
/**
* Given `this.props.children`, return an object mapping key to child.
*
* @param {*} children `this.props.children`
* @return {object} Mapping of key to child
*/
function getChildMapping(children, mapFn) {
var mapper = function mapper(child) {
return mapFn && reactExports.isValidElement(child) ? mapFn(child) : child;
};
var result = Object.create(null);
if (children) reactExports.Children.map(children, function (c) {
return c;
}).forEach(function (child) {
// run the map function here instead so that the key is the computed one
result[child.key] = mapper(child);
});
return result;
}
/**
* When you're adding or removing children some may be added or removed in the
* same render pass. We want to show *both* since we want to simultaneously
* animate elements in and out. This function takes a previous set of keys
* and a new set of keys and merges them with its best guess of the correct
* ordering. In the future we may expose some of the utilities in
* ReactMultiChild to make this easy, but for now React itself does not
* directly have this concept of the union of prevChildren and nextChildren
* so we implement it here.
*
* @param {object} prev prev children as returned from
* `ReactTransitionChildMapping.getChildMapping()`.
* @param {object} next next children as returned from
* `ReactTransitionChildMapping.getChildMapping()`.
* @return {object} a key set that contains all keys in `prev` and all keys
* in `next` in a reasonable order.
*/
function mergeChildMappings(prev, next) {
prev = prev || {};
next = next || {};
function getValueForKey(key) {
return key in next ? next[key] : prev[key];
} // For each key of `next`, the list of keys to insert before that key in
// the combined list
var nextKeysPending = Object.create(null);
var pendingKeys = [];
for (var prevKey in prev) {
if (prevKey in next) {
if (pendingKeys.length) {
nextKeysPending[prevKey] = pendingKeys;
pendingKeys = [];
}
} else {
pendingKeys.push(prevKey);
}
}
var i;
var childMapping = {};
for (var nextKey in next) {
if (nextKeysPending[nextKey]) {
for (i = 0; i < nextKeysPending[nextKey].length; i++) {
var pendingNextKey = nextKeysPending[nextKey][i];
childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey);
}
}
childMapping[nextKey] = getValueForKey(nextKey);
} // Finally, add the keys which didn't appear before any key in `next`
for (i = 0; i < pendingKeys.length; i++) {
childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);
}
return childMapping;
}
function getProp(child, prop, props) {
return props[prop] != null ? props[prop] : child.props[prop];
}
function getInitialChildMapping(props, onExited) {
return getChildMapping(props.children, function (child) {
return reactExports.cloneElement(child, {
onExited: onExited.bind(null, child),
in: true,
appear: getProp(child, 'appear', props),
enter: getProp(child, 'enter', props),
exit: getProp(child, 'exit', props)
});
});
}
function getNextChildMapping(nextProps, prevChildMapping, onExited) {
var nextChildMapping = getChildMapping(nextProps.children);
var children = mergeChildMappings(prevChildMapping, nextChildMapping);
Object.keys(children).forEach(function (key) {
var child = children[key];
if (!reactExports.isValidElement(child)) return;
var hasPrev = (key in prevChildMapping);
var hasNext = (key in nextChildMapping);
var prevChild = prevChildMapping[key];
var isLeaving = reactExports.isValidElement(prevChild) && !prevChild.props.in; // item is new (entering)
if (hasNext && (!hasPrev || isLeaving)) {
// console.log('entering', key)
children[key] = reactExports.cloneElement(child, {
onExited: onExited.bind(null, child),
in: true,
exit: getProp(child, 'exit', nextProps),
enter: getProp(child, 'enter', nextProps)
});
} else if (!hasNext && hasPrev && !isLeaving) {
// item is old (exiting)
// console.log('leaving', key)
children[key] = reactExports.cloneElement(child, {
in: false
});
} else if (hasNext && hasPrev && reactExports.isValidElement(prevChild)) {
// item hasn't changed transition states
// copy over the last transition props;
// console.log('unchanged', key)
children[key] = reactExports.cloneElement(child, {
onExited: onExited.bind(null, child),
in: prevChild.props.in,
exit: getProp(child, 'exit', nextProps),
enter: getProp(child, 'enter', nextProps)
});
}
});
return children;
}
var values = Object.values || function (obj) {
return Object.keys(obj).map(function (k) {
return obj[k];
});
};
var defaultProps = {
component: 'div',
childFactory: function childFactory(child) {
return child;
}
};
/**
* The `<TransitionGroup>` component manages a set of transition components
* (`<Transition>` and `<CSSTransition>`) in a list. Like with the transition
* components, `<TransitionGroup>` is a state machine for managing the mounting
* and unmounting of components over time.
*
* Consider the example below. As items are removed or added to the TodoList the
* `in` prop is toggled automatically by the `<TransitionGroup>`.
*
* Note that `<TransitionGroup>` does not define any animation behavior!
* Exactly _how_ a list item animates is up to the individual transition
* component. This means you can mix and match animations across different list
* items.
*/
var TransitionGroup = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(TransitionGroup, _React$Component);
function TransitionGroup(props, context) {
var _this;
_this = _React$Component.call(this, props, context) || this;
var handleExited = _this.handleExited.bind(_assertThisInitialized(_this)); // Initial children should all be entering, dependent on appear
_this.state = {
contextValue: {
isMounting: true
},
handleExited: handleExited,
firstRender: true
};
return _this;
}
var _proto = TransitionGroup.prototype;
_proto.componentDidMount = function componentDidMount() {
this.mounted = true;
this.setState({
contextValue: {
isMounting: false
}
});
};
_proto.componentWillUnmount = function componentWillUnmount() {
this.mounted = false;
};
TransitionGroup.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, _ref) {
var prevChildMapping = _ref.children,
handleExited = _ref.handleExited,
firstRender = _ref.firstRender;
return {
children: firstRender ? getInitialChildMapping(nextProps, handleExited) : getNextChildMapping(nextProps, prevChildMapping, handleExited),
firstRender: false
};
} // node is `undefined` when user provided `nodeRef` prop
;
_proto.handleExited = function handleExited(child, node) {
var currentChildMapping = getChildMapping(this.props.children);
if (child.key in currentChildMapping) return;
if (child.props.onExited) {
child.props.onExited(node);
}
if (this.mounted) {
this.setState(function (state) {
var children = _extends({}, state.children);
delete children[child.key];
return {
children: children
};
});
}
};
_proto.render = function render() {
var _this$props = this.props,
Component = _this$props.component,
childFactory = _this$props.childFactory,
props = _objectWithoutPropertiesLoose(_this$props, ["component", "childFactory"]);
var contextValue = this.state.contextValue;
var children = values(this.state.children).map(childFactory);
delete props.appear;
delete props.enter;
delete props.exit;
if (Component === null) {
return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, {
value: contextValue
}, children);
}
return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, {
value: contextValue
}, /*#__PURE__*/React.createElement(Component, props, children));
};
return TransitionGroup;
}(React.Component);
TransitionGroup.propTypes = {};
TransitionGroup.defaultProps = defaultProps;
function Ripple(props) {
const {
className,
classes,
pulsate = false,
rippleX,
rippleY,
rippleSize,
in: inProp,
onExited,
timeout
} = props;
const [leaving, setLeaving] = reactExports.useState(false);
const rippleClassName = clsx(className, classes.ripple, classes.rippleVisible, pulsate && classes.ripplePulsate);
const rippleStyles = {
width: rippleSize,
height: rippleSize,
top: -(rippleSize / 2) + rippleY,
left: -(rippleSize / 2) + rippleX
};
const childClassName = clsx(classes.child, leaving && classes.childLeaving, pulsate && classes.childPulsate);
if (!inProp && !leaving) {
setLeaving(true);
}
reactExports.useEffect(() => {
if (!inProp && onExited != null) {
// react-transition-group#onExited
const timeoutId = setTimeout(onExited, timeout);
return () => {
clearTimeout(timeoutId);
};
}
return undefined;
}, [onExited, inProp, timeout]);
return /*#__PURE__*/jsxRuntimeExports.jsx("span", {
className: rippleClassName,
style: rippleStyles,
children: /*#__PURE__*/jsxRuntimeExports.jsx("span", {
className: childClassName
})
});
}
const touchRippleClasses = generateUtilityClasses('MuiTouchRipple', ['root', 'ripple', 'rippleVisible', 'ripplePulsate', 'child', 'childLeaving', 'childPulsate']);
const DURATION = 550;
const DELAY_RIPPLE = 80;
const enterKeyframe = keyframes`
0% {
transform: scale(0);
opacity: 0.1;
}
100% {
transform: scale(1);
opacity: 0.3;
}
`;
const exitKeyframe = keyframes`
0% {
opacity: 1;
}
100% {
opacity: 0;
}
`;
const pulsateKeyframe = keyframes`
0% {
transform: scale(1);
}
50% {
transform: scale(0.92);
}
100% {
transform: scale(1);
}
`;
const TouchRippleRoot = styled('span', {
name: 'MuiTouchRipple',
slot: 'Root'
})({
overflow: 'hidden',
pointerEvents: 'none',
position: 'absolute',
zIndex: 0,
top: 0,
right: 0,
bottom: 0,
left: 0,
borderRadius: 'inherit'
});
// This `styled()` function invokes keyframes. `styled-components` only supports keyframes
// in string templates. Do not convert these styles in JS object as it will break.
const TouchRippleRipple = styled(Ripple, {
name: 'MuiTouchRipple',
slot: 'Ripple'
})`
opacity: 0;
position: absolute;
&.${touchRippleClasses.rippleVisible} {
opacity: 0.3;
transform: scale(1);
animation-name: ${enterKeyframe};
animation-duration: ${DURATION}ms;
animation-timing-function: ${({
theme
}) => theme.transitions.easing.easeInOut};
}
&.${touchRippleClasses.ripplePulsate} {
animation-duration: ${({
theme
}) => theme.transitions.duration.shorter}ms;
}
& .${touchRippleClasses.child} {
opacity: 1;
display: block;
width: 100%;
height: 100%;
border-radius: 50%;
background-color: currentColor;
}
& .${touchRippleClasses.childLeaving} {
opacity: 0;
animation-name: ${exitKeyframe};
animation-duration: ${DURATION}ms;
animation-timing-function: ${({
theme
}) => theme.transitions.easing.easeInOut};
}
& .${touchRippleClasses.childPulsate} {
position: absolute;
/* @noflip */
left: 0px;
top: 0;
animation-name: ${pulsateKeyframe};
animation-duration: 2500ms;
animation-timing-function: ${({
theme
}) => theme.transitions.easing.easeInOut};
animation-iteration-count: infinite;
animation-delay: 200ms;
}
`;
/**
* @ignore - internal component.
*
* TODO v5: Make private
*/
const TouchRipple = /*#__PURE__*/reactExports.forwardRef(function TouchRipple(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiTouchRipple'
});
const {
center: centerProp = false,
classes = {},
className,
...other
} = props;
const [ripples, setRipples] = reactExports.useState([]);
const nextKey = reactExports.useRef(0);
const rippleCallback = reactExports.useRef(null);
reactExports.useEffect(() => {
if (rippleCallback.current) {
rippleCallback.current();
rippleCallback.current = null;
}
}, [ripples]);
// Used to filter out mouse emulated events on mobile.
const ignoringMouseDown = reactExports.useRef(false);
// We use a timer in order to only show the ripples for touch "click" like events.
// We don't want to display the ripple for touch scroll events.
const startTimer = useTimeout();
// This is the hook called once the previous timeout is ready.
const startTimerCommit = reactExports.useRef(null);
const container = reactExports.useRef(null);
const startCommit = reactExports.useCallback(params => {
const {
pulsate,
rippleX,
rippleY,
rippleSize,
cb
} = params;
setRipples(oldRipples => [...oldRipples, /*#__PURE__*/jsxRuntimeExports.jsx(TouchRippleRipple, {
classes: {
ripple: clsx(classes.ripple, touchRippleClasses.ripple),
rippleVisible: clsx(classes.rippleVisible, touchRippleClasses.rippleVisible),
ripplePulsate: clsx(classes.ripplePulsate, touchRippleClasses.ripplePulsate),
child: clsx(classes.child, touchRippleClasses.child),
childLeaving: clsx(classes.childLeaving, touchRippleClasses.childLeaving),
childPulsate: clsx(classes.childPulsate, touchRippleClasses.childPulsate)
},
timeout: DURATION,
pulsate: pulsate,
rippleX: rippleX,
rippleY: rippleY,
rippleSize: rippleSize
}, nextKey.current)]);
nextKey.current += 1;
rippleCallback.current = cb;
}, [classes]);
const start = reactExports.useCallback((event = {}, options = {}, cb = () => {}) => {
const {
pulsate = false,
center = centerProp || options.pulsate,
fakeElement = false // For test purposes
} = options;
if (event?.type === 'mousedown' && ignoringMouseDown.current) {
ignoringMouseDown.current = false;
return;
}
if (event?.type === 'touchstart') {
ignoringMouseDown.current = true;
}
const element = fakeElement ? null : container.current;
const rect = element ? element.getBoundingClientRect() : {
width: 0,
height: 0,
left: 0,
top: 0
};
// Get the size of the ripple
let rippleX;
let rippleY;
let rippleSize;
if (center || event === undefined || event.clientX === 0 && event.clientY === 0 || !event.clientX && !event.touches) {
rippleX = Math.round(rect.width / 2);
rippleY = Math.round(rect.height / 2);
} else {
const {
clientX,
clientY
} = event.touches && event.touches.length > 0 ? event.touches[0] : event;
rippleX = Math.round(clientX - rect.left);
rippleY = Math.round(clientY - rect.top);
}
if (center) {
rippleSize = Math.sqrt((2 * rect.width ** 2 + rect.height ** 2) / 3);
// For some reason the animation is broken on Mobile Chrome if the size is even.
if (rippleSize % 2 === 0) {
rippleSize += 1;
}
} else {
const sizeX = Math.max(Math.abs((element ? element.clientWidth : 0) - rippleX), rippleX) * 2 + 2;
const sizeY = Math.max(Math.abs((element ? element.clientHeight : 0) - rippleY), rippleY) * 2 + 2;
rippleSize = Math.sqrt(sizeX ** 2 + sizeY ** 2);
}
// Touche devices
if (event?.touches) {
// check that this isn't another touchstart due to multitouch
// otherwise we will only clear a single timer when unmounting while two
// are running
if (startTimerCommit.current === null) {
// Prepare the ripple effect.
startTimerCommit.current = () => {
startCommit({
pulsate,
rippleX,
rippleY,
rippleSize,
cb
});
};
// Delay the execution of the ripple effect.
// We have to make a tradeoff with this delay value.
startTimer.start(DELAY_RIPPLE, () => {
if (startTimerCommit.current) {
startTimerCommit.current();
startTimerCommit.current = null;
}
});
}
} else {
startCommit({
pulsate,
rippleX,
rippleY,
rippleSize,
cb
});
}
}, [centerProp, startCommit, startTimer]);
const pulsate = reactExports.useCallback(() => {
start({}, {
pulsate: true
});
}, [start]);
const stop = reactExports.useCallback((event, cb) => {
startTimer.clear();
// The touch interaction occurs too quickly.
// We still want to show ripple effect.
if (event?.type === 'touchend' && startTimerCommit.current) {
startTimerCommit.current();
startTimerCommit.current = null;
startTimer.start(0, () => {
stop(event, cb);
});
return;
}
startTimerCommit.current = null;
setRipples(oldRipples => {
if (oldRipples.length > 0) {
return oldRipples.slice(1);
}
return oldRipples;
});
rippleCallback.current = cb;
}, [startTimer]);
reactExports.useImperativeHandle(ref, () => ({
pulsate,
start,
stop
}), [pulsate, start, stop]);
return /*#__PURE__*/jsxRuntimeExports.jsx(TouchRippleRoot, {
className: clsx(touchRippleClasses.root, classes.root, className),
ref: container,
...other,
children: /*#__PURE__*/jsxRuntimeExports.jsx(TransitionGroup, {
component: null,
exit: true,
children: ripples
})
});
});
function getButtonBaseUtilityClass(slot) {
return generateUtilityClass('MuiButtonBase', slot);
}
const buttonBaseClasses = generateUtilityClasses('MuiButtonBase', ['root', 'disabled', 'focusVisible']);
const useUtilityClasses$q = ownerState => {
const {
disabled,
focusVisible,
focusVisibleClassName,
classes
} = ownerState;
const slots = {
root: ['root', disabled && 'disabled', focusVisible && 'focusVisible']
};
const composedClasses = composeClasses(slots, getButtonBaseUtilityClass, classes);
if (focusVisible && focusVisibleClassName) {
composedClasses.root += ` ${focusVisibleClassName}`;
}
return composedClasses;
};
const ButtonBaseRoot = styled('button', {
name: 'MuiButtonBase',
slot: 'Root',
overridesResolver: (props, styles) => styles.root
})({
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
position: 'relative',
boxSizing: 'border-box',
WebkitTapHighlightColor: 'transparent',
backgroundColor: 'transparent',
// Reset default value
// We disable the focus ring for mouse, touch and keyboard users.
outline: 0,
border: 0,
margin: 0,
// Remove the margin in Safari
borderRadius: 0,
padding: 0,
// Remove the padding in Firefox
cursor: 'pointer',
userSelect: 'none',
verticalAlign: 'middle',
MozAppearance: 'none',
// Reset
WebkitAppearance: 'none',
// Reset
textDecoration: 'none',
// So we take precedent over the style of a native <a /> element.
color: 'inherit',
'&::-moz-focus-inner': {
borderStyle: 'none' // Remove Firefox dotted outline.
},
[`&.${buttonBaseClasses.disabled}`]: {
pointerEvents: 'none',
// Disable link interactions
cursor: 'default'
},
'@media print': {
colorAdjust: 'exact'
}
});
/**
* `ButtonBase` contains as few styles as possible.
* It aims to be a simple building block for creating a button.
* It contains a load of style reset and some focus/ripple logic.
*/
const ButtonBase = /*#__PURE__*/reactExports.forwardRef(function ButtonBase(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiButtonBase'
});
const {
action,
centerRipple = false,
children,
className,
component = 'button',
disabled = false,
disableRipple = false,
disableTouchRipple = false,
focusRipple = false,
focusVisibleClassName,
LinkComponent = 'a',
onBlur,
onClick,
onContextMenu,
onDragLeave,
onFocus,
onFocusVisible,
onKeyDown,
onKeyUp,
onMouseDown,
onMouseLeave,
onMouseUp,
onTouchEnd,
onTouchMove,
onTouchStart,
tabIndex = 0,
TouchRippleProps,
touchRippleRef,
type,
...other
} = props;
const buttonRef = reactExports.useRef(null);
const ripple = useLazyRipple();
const handleRippleRef = useForkRef(ripple.ref, touchRippleRef);
const [focusVisible, setFocusVisible] = reactExports.useState(false);
if (disabled && focusVisible) {
setFocusVisible(false);
}
reactExports.useImperativeHandle(action, () => ({
focusVisible: () => {
setFocusVisible(true);
buttonRef.current.focus();
}
}), []);
const enableTouchRipple = ripple.shouldMount && !disableRipple && !disabled;
reactExports.useEffect(() => {
if (focusVisible && focusRipple && !disableRipple) {
ripple.pulsate();
}
}, [disableRipple, focusRipple, focusVisible, ripple]);
const handleMouseDown = useRippleHandler(ripple, 'start', onMouseDown, disableTouchRipple);
const handleContextMenu = useRippleHandler(ripple, 'stop', onContextMenu, disableTouchRipple);
const handleDragLeave = useRippleHandler(ripple, 'stop', onDragLeave, disableTouchRipple);
const handleMouseUp = useRippleHandler(ripple, 'stop', onMouseUp, disableTouchRipple);
const handleMouseLeave = useRippleHandler(ripple, 'stop', event => {
if (focusVisible) {
event.preventDefault();
}
if (onMouseLeave) {
onMouseLeave(event);
}
}, disableTouchRipple);
const handleTouchStart = useRippleHandler(ripple, 'start', onTouchStart, disableTouchRipple);
const handleTouchEnd = useRippleHandler(ripple, 'stop', onTouchEnd, disableTouchRipple);
const handleTouchMove = useRippleHandler(ripple, 'stop', onTouchMove, disableTouchRipple);
const handleBlur = useRippleHandler(ripple, 'stop', event => {
if (!isFocusVisible(event.target)) {
setFocusVisible(false);
}
if (onBlur) {
onBlur(event);
}
}, false);
const handleFocus = useEventCallback(event => {
// Fix for https://github.com/facebook/react/issues/7769
if (!buttonRef.current) {
buttonRef.current = event.currentTarget;
}
if (isFocusVisible(event.target)) {
setFocusVisible(true);
if (onFocusVisible) {
onFocusVisible(event);
}
}
if (onFocus) {
onFocus(event);
}
});
const isNonNativeButton = () => {
const button = buttonRef.current;
return component && component !== 'button' && !(button.tagName === 'A' && button.href);
};
const handleKeyDown = useEventCallback(event => {
// Check if key is already down to avoid repeats being counted as multiple activations
if (focusRipple && !event.repeat && focusVisible && event.key === ' ') {
ripple.stop(event, () => {
ripple.start(event);
});
}
if (event.target === event.currentTarget && isNonNativeButton() && event.key === ' ') {
event.preventDefault();
}
if (onKeyDown) {
onKeyDown(event);
}
// Keyboard accessibility for non interactive elements
if (event.target === event.currentTarget && isNonNativeButton() && event.key === 'Enter' && !disabled) {
event.preventDefault();
if (onClick) {
onClick(event);
}
}
});
const handleKeyUp = useEventCallback(event => {
// calling preventDefault in keyUp on a <button> will not dispatch a click event if Space is pressed
// https://codesandbox.io/p/sandbox/button-keyup-preventdefault-dn7f0
if (focusRipple && event.key === ' ' && focusVisible && !event.defaultPrevented) {
ripple.stop(event, () => {
ripple.pulsate(event);
});
}
if (onKeyUp) {
onKeyUp(event);
}
// Keyboard accessibility for non interactive elements
if (onClick && event.target === event.currentTarget && isNonNativeButton() && event.key === ' ' && !event.defaultPrevented) {
onClick(event);
}
});
let ComponentProp = component;
if (ComponentProp === 'button' && (other.href || other.to)) {
ComponentProp = LinkComponent;
}
const buttonProps = {};
if (ComponentProp === 'button') {
buttonProps.type = type === undefined ? 'button' : type;
buttonProps.disabled = disabled;
} else {
if (!other.href && !other.to) {
buttonProps.role = 'button';
}
if (disabled) {
buttonProps['aria-disabled'] = disabled;
}
}
const handleRef = useForkRef(ref, buttonRef);
const ownerState = {
...props,
centerRipple,
component,
disabled,
disableRipple,
disableTouchRipple,
focusRipple,
tabIndex,
focusVisible
};
const classes = useUtilityClasses$q(ownerState);
return /*#__PURE__*/jsxRuntimeExports.jsxs(ButtonBaseRoot, {
as: ComponentProp,
className: clsx(classes.root, className),
ownerState: ownerState,
onBlur: handleBlur,
onClick: onClick,
onContextMenu: handleContextMenu,
onFocus: handleFocus,
onKeyDown: handleKeyDown,
onKeyUp: handleKeyUp,
onMouseDown: handleMouseDown,
onMouseLeave: handleMouseLeave,
onMouseUp: handleMouseUp,
onDragLeave: handleDragLeave,
onTouchEnd: handleTouchEnd,
onTouchMove: handleTouchMove,
onTouchStart: handleTouchStart,
ref: handleRef,
tabIndex: disabled ? -1 : tabIndex,
type: type,
...buttonProps,
...other,
children: [children, enableTouchRipple ? /*#__PURE__*/jsxRuntimeExports.jsx(TouchRipple, {
ref: handleRippleRef,
center: centerRipple,
...TouchRippleProps
}) : null]
});
});
function useRippleHandler(ripple, rippleAction, eventCallback, skipRippleAction = false) {
return useEventCallback(event => {
if (eventCallback) {
eventCallback(event);
}
if (!skipRippleAction) {
ripple[rippleAction](event);
}
return true;
});
}
/**
* Type guard to check if the object has a "main" property of type string.
*
* @param obj - the object to check
* @returns boolean
*/
function hasCorrectMainProperty(obj) {
return typeof obj.main === 'string';
}
/**
* Checks if the object conforms to the SimplePaletteColorOptions type.
* The minimum requirement is that the object has a "main" property of type string, this is always checked.
* Optionally, you can pass additional properties to check.
*
* @param obj - The object to check
* @param additionalPropertiesToCheck - Array containing "light", "dark", and/or "contrastText"
* @returns boolean
*/
function checkSimplePaletteColorValues(obj, additionalPropertiesToCheck = []) {
if (!hasCorrectMainProperty(obj)) {
return false;
}
for (const value of additionalPropertiesToCheck) {
if (!obj.hasOwnProperty(value) || typeof obj[value] !== 'string') {
return false;
}
}
return true;
}
/**
* Creates a filter function used to filter simple palette color options.
* The minimum requirement is that the object has a "main" property of type string, this is always checked.
* Optionally, you can pass additional properties to check.
*
* @param additionalPropertiesToCheck - Array containing "light", "dark", and/or "contrastText"
* @returns ([, value]: [any, PaletteColorOptions]) => boolean
*/
function createSimplePaletteValueFilter(additionalPropertiesToCheck = []) {
return ([, value]) => value && checkSimplePaletteColorValues(value, additionalPropertiesToCheck);
}
function getCircularProgressUtilityClass(slot) {
return generateUtilityClass('MuiCircularProgress', slot);
}
generateUtilityClasses('MuiCircularProgress', ['root', 'determinate', 'indeterminate', 'colorPrimary', 'colorSecondary', 'svg', 'circle', 'circleDeterminate', 'circleIndeterminate', 'circleDisableShrink']);
const SIZE = 44;
const circularRotateKeyframe = keyframes`
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
`;
const circularDashKeyframe = keyframes`
0% {
stroke-dasharray: 1px, 200px;
stroke-dashoffset: 0;
}
50% {
stroke-dasharray: 100px, 200px;
stroke-dashoffset: -15px;
}
100% {
stroke-dasharray: 1px, 200px;
stroke-dashoffset: -126px;
}
`;
// This implementation is for supporting both Styled-components v4+ and Pigment CSS.
// A global animation has to be created here for Styled-components v4+ (https://github.com/styled-components/styled-components/blob/main/packages/styled-components/src/utils/errors.md#12).
// which can be done by checking typeof indeterminate1Keyframe !== 'string' (at runtime, Pigment CSS transform keyframes`` to a string).
const rotateAnimation = typeof circularRotateKeyframe !== 'string' ? css`
animation: ${circularRotateKeyframe} 1.4s linear infinite;
` : null;
const dashAnimation = typeof circularDashKeyframe !== 'string' ? css`
animation: ${circularDashKeyframe} 1.4s ease-in-out infinite;
` : null;
const useUtilityClasses$p = ownerState => {
const {
classes,
variant,
color,
disableShrink
} = ownerState;
const slots = {
root: ['root', variant, `color${capitalize(color)}`],
svg: ['svg'],
circle: ['circle', `circle${capitalize(variant)}`, disableShrink && 'circleDisableShrink']
};
return composeClasses(slots, getCircularProgressUtilityClass, classes);
};
const CircularProgressRoot = styled('span', {
name: 'MuiCircularProgress',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, styles[ownerState.variant], styles[`color${capitalize(ownerState.color)}`]];
}
})(memoTheme(({
theme
}) => ({
display: 'inline-block',
variants: [{
props: {
variant: 'determinate'
},
style: {
transition: theme.transitions.create('transform')
}
}, {
props: {
variant: 'indeterminate'
},
style: rotateAnimation || {
animation: `${circularRotateKeyframe} 1.4s linear infinite`
}
}, ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()).map(([color]) => ({
props: {
color
},
style: {
color: (theme.vars || theme).palette[color].main
}
}))]
})));
const CircularProgressSVG = styled('svg', {
name: 'MuiCircularProgress',
slot: 'Svg',
overridesResolver: (props, styles) => styles.svg
})({
display: 'block' // Keeps the progress centered
});
const CircularProgressCircle = styled('circle', {
name: 'MuiCircularProgress',
slot: 'Circle',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.circle, styles[`circle${capitalize(ownerState.variant)}`], ownerState.disableShrink && styles.circleDisableShrink];
}
})(memoTheme(({
theme
}) => ({
stroke: 'currentColor',
variants: [{
props: {
variant: 'determinate'
},
style: {
transition: theme.transitions.create('stroke-dashoffset')
}
}, {
props: {
variant: 'indeterminate'
},
style: {
// Some default value that looks fine waiting for the animation to kicks in.
strokeDasharray: '80px, 200px',
strokeDashoffset: 0 // Add the unit to fix a Edge 16 and below bug.
}
}, {
props: ({
ownerState
}) => ownerState.variant === 'indeterminate' && !ownerState.disableShrink,
style: dashAnimation || {
// At runtime for Pigment CSS, `bufferAnimation` will be null and the generated keyframe will be used.
animation: `${circularDashKeyframe} 1.4s ease-in-out infinite`
}
}]
})));
/**
* ## ARIA
*
* If the progress bar is describing the loading progress of a particular region of a page,
* you should use `aria-describedby` to point to the progress bar, and set the `aria-busy`
* attribute to `true` on that region until it has finished loading.
*/
const CircularProgress = /*#__PURE__*/reactExports.forwardRef(function CircularProgress(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiCircularProgress'
});
const {
className,
color = 'primary',
disableShrink = false,
size = 40,
style,
thickness = 3.6,
value = 0,
variant = 'indeterminate',
...other
} = props;
const ownerState = {
...props,
color,
disableShrink,
size,
thickness,
value,
variant
};
const classes = useUtilityClasses$p(ownerState);
const circleStyle = {};
const rootStyle = {};
const rootProps = {};
if (variant === 'determinate') {
const circumference = 2 * Math.PI * ((SIZE - thickness) / 2);
circleStyle.strokeDasharray = circumference.toFixed(3);
rootProps['aria-valuenow'] = Math.round(value);
circleStyle.strokeDashoffset = `${((100 - value) / 100 * circumference).toFixed(3)}px`;
rootStyle.transform = 'rotate(-90deg)';
}
return /*#__PURE__*/jsxRuntimeExports.jsx(CircularProgressRoot, {
className: clsx(classes.root, className),
style: {
width: size,
height: size,
...rootStyle,
...style
},
ownerState: ownerState,
ref: ref,
role: "progressbar",
...rootProps,
...other,
children: /*#__PURE__*/jsxRuntimeExports.jsx(CircularProgressSVG, {
className: classes.svg,
ownerState: ownerState,
viewBox: `${SIZE / 2} ${SIZE / 2} ${SIZE} ${SIZE}`,
children: /*#__PURE__*/jsxRuntimeExports.jsx(CircularProgressCircle, {
className: classes.circle,
style: circleStyle,
ownerState: ownerState,
cx: SIZE,
cy: SIZE,
r: (SIZE - thickness) / 2,
fill: "none",
strokeWidth: thickness
})
})
});
});
function getButtonUtilityClass(slot) {
return generateUtilityClass('MuiButton', slot);
}
const buttonClasses = generateUtilityClasses('MuiButton', ['root', 'text', 'textInherit', 'textPrimary', 'textSecondary', 'textSuccess', 'textError', 'textInfo', 'textWarning', 'outlined', 'outlinedInherit', 'outlinedPrimary', 'outlinedSecondary', 'outlinedSuccess', 'outlinedError', 'outlinedInfo', 'outlinedWarning', 'contained', 'containedInherit', 'containedPrimary', 'containedSecondary', 'containedSuccess', 'containedError', 'containedInfo', 'containedWarning', 'disableElevation', 'focusVisible', 'disabled', 'colorInherit', 'colorPrimary', 'colorSecondary', 'colorSuccess', 'colorError', 'colorInfo', 'colorWarning', 'textSizeSmall', 'textSizeMedium', 'textSizeLarge', 'outlinedSizeSmall', 'outlinedSizeMedium', 'outlinedSizeLarge', 'containedSizeSmall', 'containedSizeMedium', 'containedSizeLarge', 'sizeMedium', 'sizeSmall', 'sizeLarge', 'fullWidth', 'startIcon', 'endIcon', 'icon', 'iconSizeSmall', 'iconSizeMedium', 'iconSizeLarge', 'loading', 'loadingWrapper', 'loadingIconPlaceholder', 'loadingIndicator', 'loadingPositionCenter', 'loadingPositionStart', 'loadingPositionEnd']);
/**
* @ignore - internal component.
*/
const ButtonGroupContext = /*#__PURE__*/reactExports.createContext({});
/**
* @ignore - internal component.
*/
const ButtonGroupButtonContext = /*#__PURE__*/reactExports.createContext(undefined);
const useUtilityClasses$o = ownerState => {
const {
color,
disableElevation,
fullWidth,
size,
variant,
loading,
loadingPosition,
classes
} = ownerState;
const slots = {
root: ['root', loading && 'loading', variant, `${variant}${capitalize(color)}`, `size${capitalize(size)}`, `${variant}Size${capitalize(size)}`, `color${capitalize(color)}`, disableElevation && 'disableElevation', fullWidth && 'fullWidth', loading && `loadingPosition${capitalize(loadingPosition)}`],
startIcon: ['icon', 'startIcon', `iconSize${capitalize(size)}`],
endIcon: ['icon', 'endIcon', `iconSize${capitalize(size)}`],
loadingIndicator: ['loadingIndicator'],
loadingWrapper: ['loadingWrapper']
};
const composedClasses = composeClasses(slots, getButtonUtilityClass, classes);
return {
...classes,
// forward the focused, disabled, etc. classes to the ButtonBase
...composedClasses
};
};
const commonIconStyles = [{
props: {
size: 'small'
},
style: {
'& > *:nth-of-type(1)': {
fontSize: 18
}
}
}, {
props: {
size: 'medium'
},
style: {
'& > *:nth-of-type(1)': {
fontSize: 20
}
}
}, {
props: {
size: 'large'
},
style: {
'& > *:nth-of-type(1)': {
fontSize: 22
}
}
}];
const ButtonRoot = styled(ButtonBase, {
shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
name: 'MuiButton',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, styles[ownerState.variant], styles[`${ownerState.variant}${capitalize(ownerState.color)}`], styles[`size${capitalize(ownerState.size)}`], styles[`${ownerState.variant}Size${capitalize(ownerState.size)}`], ownerState.color === 'inherit' && styles.colorInherit, ownerState.disableElevation && styles.disableElevation, ownerState.fullWidth && styles.fullWidth, ownerState.loading && styles.loading];
}
})(memoTheme(({
theme
}) => {
const inheritContainedBackgroundColor = theme.palette.mode === 'light' ? theme.palette.grey[300] : theme.palette.grey[800];
const inheritContainedHoverBackgroundColor = theme.palette.mode === 'light' ? theme.palette.grey.A100 : theme.palette.grey[700];
return {
...theme.typography.button,
minWidth: 64,
padding: '6px 16px',
border: 0,
borderRadius: (theme.vars || theme).shape.borderRadius,
transition: theme.transitions.create(['background-color', 'box-shadow', 'border-color', 'color'], {
duration: theme.transitions.duration.short
}),
'&:hover': {
textDecoration: 'none'
},
[`&.${buttonClasses.disabled}`]: {
color: (theme.vars || theme).palette.action.disabled
},
variants: [{
props: {
variant: 'contained'
},
style: {
color: `var(--variant-containedColor)`,
backgroundColor: `var(--variant-containedBg)`,
boxShadow: (theme.vars || theme).shadows[2],
'&:hover': {
boxShadow: (theme.vars || theme).shadows[4],
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
boxShadow: (theme.vars || theme).shadows[2]
}
},
'&:active': {
boxShadow: (theme.vars || theme).shadows[8]
},
[`&.${buttonClasses.focusVisible}`]: {
boxShadow: (theme.vars || theme).shadows[6]
},
[`&.${buttonClasses.disabled}`]: {
color: (theme.vars || theme).palette.action.disabled,
boxShadow: (theme.vars || theme).shadows[0],
backgroundColor: (theme.vars || theme).palette.action.disabledBackground
}
}
}, {
props: {
variant: 'outlined'
},
style: {
padding: '5px 15px',
border: '1px solid currentColor',
borderColor: `var(--variant-outlinedBorder, currentColor)`,
backgroundColor: `var(--variant-outlinedBg)`,
color: `var(--variant-outlinedColor)`,
[`&.${buttonClasses.disabled}`]: {
border: `1px solid ${(theme.vars || theme).palette.action.disabledBackground}`
}
}
}, {
props: {
variant: 'text'
},
style: {
padding: '6px 8px',
color: `var(--variant-textColor)`,
backgroundColor: `var(--variant-textBg)`
}
}, ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()).map(([color]) => ({
props: {
color
},
style: {
'--variant-textColor': (theme.vars || theme).palette[color].main,
'--variant-outlinedColor': (theme.vars || theme).palette[color].main,
'--variant-outlinedBorder': theme.vars ? `rgba(${theme.vars.palette[color].mainChannel} / 0.5)` : alpha(theme.palette[color].main, 0.5),
'--variant-containedColor': (theme.vars || theme).palette[color].contrastText,
'--variant-containedBg': (theme.vars || theme).palette[color].main,
'@media (hover: hover)': {
'&:hover': {
'--variant-containedBg': (theme.vars || theme).palette[color].dark,
'--variant-textBg': theme.vars ? `rgba(${theme.vars.palette[color].mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette[color].main, theme.palette.action.hoverOpacity),
'--variant-outlinedBorder': (theme.vars || theme).palette[color].main,
'--variant-outlinedBg': theme.vars ? `rgba(${theme.vars.palette[color].mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette[color].main, theme.palette.action.hoverOpacity)
}
}
}
})), {
props: {
color: 'inherit'
},
style: {
color: 'inherit',
borderColor: 'currentColor',
'--variant-containedBg': theme.vars ? theme.vars.palette.Button.inheritContainedBg : inheritContainedBackgroundColor,
'@media (hover: hover)': {
'&:hover': {
'--variant-containedBg': theme.vars ? theme.vars.palette.Button.inheritContainedHoverBg : inheritContainedHoverBackgroundColor,
'--variant-textBg': theme.vars ? `rgba(${theme.vars.palette.text.primaryChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette.text.primary, theme.palette.action.hoverOpacity),
'--variant-outlinedBg': theme.vars ? `rgba(${theme.vars.palette.text.primaryChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette.text.primary, theme.palette.action.hoverOpacity)
}
}
}
}, {
props: {
size: 'small',
variant: 'text'
},
style: {
padding: '4px 5px',
fontSize: theme.typography.pxToRem(13)
}
}, {
props: {
size: 'large',
variant: 'text'
},
style: {
padding: '8px 11px',
fontSize: theme.typography.pxToRem(15)
}
}, {
props: {
size: 'small',
variant: 'outlined'
},
style: {
padding: '3px 9px',
fontSize: theme.typography.pxToRem(13)
}
}, {
props: {
size: 'large',
variant: 'outlined'
},
style: {
padding: '7px 21px',
fontSize: theme.typography.pxToRem(15)
}
}, {
props: {
size: 'small',
variant: 'contained'
},
style: {
padding: '4px 10px',
fontSize: theme.typography.pxToRem(13)
}
}, {
props: {
size: 'large',
variant: 'contained'
},
style: {
padding: '8px 22px',
fontSize: theme.typography.pxToRem(15)
}
}, {
props: {
disableElevation: true
},
style: {
boxShadow: 'none',
'&:hover': {
boxShadow: 'none'
},
[`&.${buttonClasses.focusVisible}`]: {
boxShadow: 'none'
},
'&:active': {
boxShadow: 'none'
},
[`&.${buttonClasses.disabled}`]: {
boxShadow: 'none'
}
}
}, {
props: {
fullWidth: true
},
style: {
width: '100%'
}
}, {
props: {
loadingPosition: 'center'
},
style: {
transition: theme.transitions.create(['background-color', 'box-shadow', 'border-color'], {
duration: theme.transitions.duration.short
}),
[`&.${buttonClasses.loading}`]: {
color: 'transparent'
}
}
}]
};
}));
const ButtonStartIcon = styled('span', {
name: 'MuiButton',
slot: 'StartIcon',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.startIcon, ownerState.loading && styles.startIconLoadingStart, styles[`iconSize${capitalize(ownerState.size)}`]];
}
})(({
theme
}) => ({
display: 'inherit',
marginRight: 8,
marginLeft: -4,
variants: [{
props: {
size: 'small'
},
style: {
marginLeft: -2
}
}, {
props: {
loadingPosition: 'start',
loading: true
},
style: {
transition: theme.transitions.create(['opacity'], {
duration: theme.transitions.duration.short
}),
opacity: 0
}
}, {
props: {
loadingPosition: 'start',
loading: true,
fullWidth: true
},
style: {
marginRight: -8
}
}, ...commonIconStyles]
}));
const ButtonEndIcon = styled('span', {
name: 'MuiButton',
slot: 'EndIcon',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.endIcon, ownerState.loading && styles.endIconLoadingEnd, styles[`iconSize${capitalize(ownerState.size)}`]];
}
})(({
theme
}) => ({
display: 'inherit',
marginRight: -4,
marginLeft: 8,
variants: [{
props: {
size: 'small'
},
style: {
marginRight: -2
}
}, {
props: {
loadingPosition: 'end',
loading: true
},
style: {
transition: theme.transitions.create(['opacity'], {
duration: theme.transitions.duration.short
}),
opacity: 0
}
}, {
props: {
loadingPosition: 'end',
loading: true,
fullWidth: true
},
style: {
marginLeft: -8
}
}, ...commonIconStyles]
}));
const ButtonLoadingIndicator = styled('span', {
name: 'MuiButton',
slot: 'LoadingIndicator',
overridesResolver: (props, styles) => styles.loadingIndicator
})(({
theme
}) => ({
display: 'none',
position: 'absolute',
visibility: 'visible',
variants: [{
props: {
loading: true
},
style: {
display: 'flex'
}
}, {
props: {
loadingPosition: 'start'
},
style: {
left: 14
}
}, {
props: {
loadingPosition: 'start',
size: 'small'
},
style: {
left: 10
}
}, {
props: {
variant: 'text',
loadingPosition: 'start'
},
style: {
left: 6
}
}, {
props: {
loadingPosition: 'center'
},
style: {
left: '50%',
transform: 'translate(-50%)',
color: (theme.vars || theme).palette.action.disabled
}
}, {
props: {
loadingPosition: 'end'
},
style: {
right: 14
}
}, {
props: {
loadingPosition: 'end',
size: 'small'
},
style: {
right: 10
}
}, {
props: {
variant: 'text',
loadingPosition: 'end'
},
style: {
right: 6
}
}, {
props: {
loadingPosition: 'start',
fullWidth: true
},
style: {
position: 'relative',
left: -10
}
}, {
props: {
loadingPosition: 'end',
fullWidth: true
},
style: {
position: 'relative',
right: -10
}
}]
}));
const ButtonLoadingIconPlaceholder = styled('span', {
name: 'MuiButton',
slot: 'LoadingIconPlaceholder',
overridesResolver: (props, styles) => styles.loadingIconPlaceholder
})({
display: 'inline-block',
width: '1em',
height: '1em'
});
const Button = /*#__PURE__*/reactExports.forwardRef(function Button(inProps, ref) {
// props priority: `inProps` > `contextProps` > `themeDefaultProps`
const contextProps = reactExports.useContext(ButtonGroupContext);
const buttonGroupButtonContextPositionClassName = reactExports.useContext(ButtonGroupButtonContext);
const resolvedProps = resolveProps(contextProps, inProps);
const props = useDefaultProps({
props: resolvedProps,
name: 'MuiButton'
});
const {
children,
color = 'primary',
component = 'button',
className,
disabled = false,
disableElevation = false,
disableFocusRipple = false,
endIcon: endIconProp,
focusVisibleClassName,
fullWidth = false,
id: idProp,
loading = null,
loadingIndicator: loadingIndicatorProp,
loadingPosition = 'center',
size = 'medium',
startIcon: startIconProp,
type,
variant = 'text',
...other
} = props;
const loadingId = useId(idProp);
const loadingIndicator = loadingIndicatorProp ?? /*#__PURE__*/jsxRuntimeExports.jsx(CircularProgress, {
"aria-labelledby": loadingId,
color: "inherit",
size: 16
});
const ownerState = {
...props,
color,
component,
disabled,
disableElevation,
disableFocusRipple,
fullWidth,
loading,
loadingIndicator,
loadingPosition,
size,
type,
variant
};
const classes = useUtilityClasses$o(ownerState);
const startIcon = (startIconProp || loading && loadingPosition === 'start') && /*#__PURE__*/jsxRuntimeExports.jsx(ButtonStartIcon, {
className: classes.startIcon,
ownerState: ownerState,
children: startIconProp || /*#__PURE__*/jsxRuntimeExports.jsx(ButtonLoadingIconPlaceholder, {
className: classes.loadingIconPlaceholder,
ownerState: ownerState
})
});
const endIcon = (endIconProp || loading && loadingPosition === 'end') && /*#__PURE__*/jsxRuntimeExports.jsx(ButtonEndIcon, {
className: classes.endIcon,
ownerState: ownerState,
children: endIconProp || /*#__PURE__*/jsxRuntimeExports.jsx(ButtonLoadingIconPlaceholder, {
className: classes.loadingIconPlaceholder,
ownerState: ownerState
})
});
const positionClassName = buttonGroupButtonContextPositionClassName || '';
const loader = typeof loading === 'boolean' ?
/*#__PURE__*/
// use plain HTML span to minimize the runtime overhead
jsxRuntimeExports.jsx("span", {
className: classes.loadingWrapper,
style: {
display: 'contents'
},
children: loading && /*#__PURE__*/jsxRuntimeExports.jsx(ButtonLoadingIndicator, {
className: classes.loadingIndicator,
ownerState: ownerState,
children: loadingIndicator
})
}) : null;
return /*#__PURE__*/jsxRuntimeExports.jsxs(ButtonRoot, {
ownerState: ownerState,
className: clsx(contextProps.className, classes.root, className, positionClassName),
component: component,
disabled: disabled || loading,
focusRipple: !disableFocusRipple,
focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName),
ref: ref,
type: type,
id: loading ? loadingId : idProp,
...other,
classes: classes,
children: [startIcon, loadingPosition !== 'end' && loader, children, loadingPosition === 'end' && loader, endIcon]
});
});
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)']
};
const colors = {
green: '#00873D',
blue: '#3F8AB3',
// greyscale
grey100: '#ffffff',
grey98: '#FBFBFB',
grey95: '#F2F2F2',
grey90: '#E6E6E6',
grey45: '#737373',
grey25: '#404040',
grey20: '#333333',
grey15: '#262626',
grey10: '#1A1A1A',
grey0: '#000000'
};
const light = {
mode: '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)',
light: colors.grey100,
dark: colors.grey0
},
action: {
active: '#545454',
// 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)',
disabledBackground: colors.grey45,
disabledContrastText: colors.grey100
},
selected: {
main: colors.green,
alternative: '#E4E4E4',
excluded: '#BEBEBE',
selectedExcluded: '#BEBEBE',
possible: colors.grey100,
selectedContrastText: colors.grey100,
mainContrastText: colors.grey100,
alternativeContrastText: colors.grey25,
excludedContrastText: colors.grey25,
selectedExcludedContrastText: colors.grey100,
possibleContrastText: colors.grey0
},
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 = {
mode: '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)',
light: colors.grey100,
dark: colors.grey0
},
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)',
disabledBackground: colors.grey45,
disabledContrastText: colors.grey100
},
selected: {
main: colors.green,
alternative: colors.grey20,
excluded: colors.grey10,
selectedExcluded: colors.grey10,
possible: colors.grey80,
selectedContrastText: colors.grey100,
mainContrastText: colors.grey100,
alternativeContrastText: colors.grey100,
excludedContrastText: colors.grey100,
selectedExcludedContrastText: colors.grey100,
possibleContrastText: colors.grey0
},
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 componentOverrides = theme => ({
MuiCheckbox: {
defaultProps: {
color: 'secondary'
}
},
MuiRadio: {
defaultProps: {
color: 'secondary'
}
},
MuiTabs: {
defaultProps: {
indicatorColor: 'secondary'
}
},
MuiTypography: {
styleOverrides: {
root: {
color: theme.palette.text.primary
}
}
},
MuiGrid: {
styleOverrides: {
variants: [{
props: {
alignItems: 'center'
},
style: {
'align-items': 'center'
}
}]
}
},
MuiButtonBase: {
defaultProps: {
disableRipple: true,
disableTouchRipple: true,
focusRipple: false
},
styleOverrides: {
root: {
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)
'&.Mui-focused': {
borderColor: theme.palette.custom.focusBorder,
boxShadow: "0 0 0 2px ".concat(theme.palette.custom.focusOutline)
}
}
}
},
MuiIconButton: {
styleOverrides: {
root: {
padding: 7,
borderRadius: 2,
border: '1px solid transparent',
'&:hover': {
backgroundColor: theme.palette.btn.hover
},
'&.Mui-focusVisible': {
borderColor: theme.palette.custom.focusBorder,
boxShadow: "0 0 0 2px ".concat(theme.palette.custom.focusOutline)
},
'&.Mui-active': {
borderColor: 'transparent',
boxShadow: 'none',
backgroundColor: theme.palette.btn.active
},
'&:not(.Mui-active):not(.Mui-focusVisible)': {
borderColor: 'transparent',
boxShadow: 'none'
}
}
}
},
MuiOutlinedInput: {
styleOverrides: {
root: {
backgroundColor: theme.palette.custom.inputBackground,
'&:hover .MuiOutlinedInput-notchedOutline': {
borderColor: theme.palette.btn.border
},
'&.Mui-focused .MuiOutlinedInput-notchedOutline': {
borderColor: theme.palette.custom.focusBorder,
borderWidth: 2
}
}
}
},
MuiButton: {
styleOverrides: {
outlined: {
padding: '3px 11px',
["&.".concat(buttonClasses.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',
["&.".concat(buttonClasses.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',
["&.".concat(buttonClasses.disabled)]: {
backgroundColor: theme.palette.btn.disabled
}
},
'&.Mui-active': {
boxShadow: 'none',
backgroundColor: theme.palette.btn.active
},
["&.".concat(buttonClasses.disabled)]: {
backgroundColor: theme.palette.btn.disabled
}
}
}
},
MuiAccordionSummary: {
styleOverrides: {
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.mode
}, base.palette), def.palette),
typography: _objectSpread2({}, base.typography),
shadows: base.shadows,
shape: _objectSpread2({}, base.shape)
};
const adaptedTheme = _objectSpread2(_objectSpread2({}, withDefaults), {}, {
components: componentOverrides(withDefaults)
});
cache[key] = createTheme(adaptedTheme);
cache[key].name = name;
return cache[key];
}
const NEBULA_VERSION_HASH = "56e3";
ClassNameGenerator.configure(componentName => {
return "njs-".concat(NEBULA_VERSION_HASH, "-").concat(componentName.replace('Mui', ''));
});
var InstanceContext = React.createContext({
language: null,
theme: null,
translator: null,
constraints: {},
interactions: {},
themeApi: null,
modelStore: {},
selectionStore: {},
hostConfig: null,
queryParams: null
});
const DEFAULT_INTERACTIONS = {
active: true,
select: true,
passive: true,
edit: false
};
function pickConstraintsOrInteractions(context) {
const {
constraints = {},
interactions = {}
} = context;
// If some interaction is defined, then we use that
if (Object.keys(interactions).length > 0) {
return interactions;
}
const ret = {};
Object.keys(constraints).forEach(state => {
ret[state] = !constraints[state];
});
return ret;
}
function unifyContraintsAndInteractions(context) {
const interactions = {};
const constraints = {};
const definedSettings = pickConstraintsOrInteractions(context);
Object.keys(DEFAULT_INTERACTIONS).forEach(state => {
if (definedSettings[state] !== undefined) {
interactions[state] = definedSettings[state];
constraints[state] = !definedSettings[state];
} else {
interactions[state] = DEFAULT_INTERACTIONS[state];
constraints[state] = !DEFAULT_INTERACTIONS[state];
}
});
context.constraints = constraints;
context.interactions = interactions;
}
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 subscribedListeners = {};
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;
subscribedListeners[key] = 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));
},
destroy: () => {
Object.keys(subscribedListeners).forEach(key => {
subscribedListeners[key] && subscribedListeners[key]();
});
}
};
const useKeyStore = () => {
const [, setState] = reactExports.useState(sharedState);
reactExports.useEffect(() => {
hookListeners.push(setState);
return () => {
const ix = hookListeners.indexOf(setState);
hookListeners.splice(ix, 1);
};
}, [setState]);
return [store];
};
return [useKeyStore, store];
});
function initializeStores$1(appId) {
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('closed', 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 destroy = () => {
modelStore.destroy();
};
return {
subscribe,
destroy,
useModelStore,
modelStore,
useModelChangedStore,
useRpcResultStore,
rpcResultStore,
useRpcRequestStore,
rpcRequestStore,
useRpcRequestModelStore,
rpcRequestModelStore,
useRpcRequestSessionModelStore,
rpcRequestSessionModelStore,
modelChangedStore,
appId
};
}
function initializeStores(appId) {
const [useAppSelectionsStore, appSelectionsStore] = createKeyStore({});
const [useAppModalStore, appModalStore] = createKeyStore({});
const [useModalObjectStore, modalObjectStore] = createKeyStore({});
return {
useAppSelectionsStore,
useAppModalStore,
appSelectionsStore,
appModalStore,
useModalObjectStore,
modalObjectStore,
appId
};
}
const NebulaApp = reactExports.forwardRef((_ref, ref) => {
let {
initialContext,
renderCallback,
modelStore,
selectionStore
} = _ref;
const [context, setContext] = reactExports.useState(initialContext);
const [muiThemeName, setMuiThemeName] = reactExports.useState();
const {
theme
} = reactExports.useMemo(() => ({
theme: create$3(muiThemeName)
}), [muiThemeName]);
const [components, setComponents] = reactExports.useState([]);
// Will be called directly after the first render pass
// See: https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html
reactExports.useEffect(() => {
renderCallback && renderCallback();
}, []);
reactExports.useImperativeHandle(ref, () => ({
setComps(comps) {
setComponents([...comps]);
},
setMuiThemeName,
setContext: ctx => setContext(oldContext => JSON.stringify(oldContext) !== JSON.stringify(ctx) ? ctx : oldContext)
}), []);
if (context) {
context.modelStore = modelStore;
context.selectionStore = selectionStore;
}
return /*#__PURE__*/React.createElement(StyledEngineProvider, {
injectFirst: true
}, /*#__PURE__*/React.createElement(ThemeProvider, {
theme: theme
}, /*#__PURE__*/React.createElement(InstanceContext.Provider, {
value: context
}, components)));
});
function boot(_ref2) {
let {
app,
context
} = _ref2;
let resolveRender;
let destroyed = false;
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', "6.3.0");
element.setAttribute('data-app-id', app.id);
document.body.appendChild(element);
if (context) {
unifyContraintsAndInteractions(context);
}
const modelStore = initializeStores$1(app.id);
const selectionStore = initializeStores(app.id);
const root = ReactDOM$1.createRoot(element);
root.render(/*#__PURE__*/React.createElement(NebulaApp, {
ref: appRef,
initialContext: context,
renderCallback: resolveRender,
modelStore: modelStore,
selectionStore: selectionStore
}));
const cells = {};
const componentsUnmount = [];
const components = [];
return [{
toggleFocusOfCells(cellIdToFocus) {
Object.keys(cells).forEach(i => {
var _cells$i$current;
(_cells$i$current = cells[i].current) === null || _cells$i$current === void 0 || _cells$i$current.toggleFocus(i === cellIdToFocus);
});
},
cells,
addCell(id, cell) {
cells[id] = cell;
},
removeCell(id) {
delete cells[id];
},
add(component, unmount) {
return (async _appRef$current => {
await rendered;
components.push(component);
componentsUnmount.push(unmount);
appRef === null || appRef === void 0 || (_appRef$current = appRef.current) === null || _appRef$current === void 0 || _appRef$current.setComps(components);
})();
},
remove(component) {
if (!destroyed) {
(async _appRef$current2 => {
await rendered;
const ix = components.indexOf(component);
if (ix !== -1) {
var _componentsUnmount$ix;
(_componentsUnmount$ix = componentsUnmount[ix]) === null || _componentsUnmount$ix === void 0 || _componentsUnmount$ix.call(componentsUnmount);
components.splice(ix, 1);
componentsUnmount.splice(ix, 1);
}
appRef === null || appRef === void 0 || (_appRef$current2 = appRef.current) === null || _appRef$current2 === void 0 || _appRef$current2.setComps(components);
})();
}
},
setMuiThemeName(themeName) {
(async _appRef$current3 => {
await rendered;
appRef === null || appRef === void 0 || (_appRef$current3 = appRef.current) === null || _appRef$current3 === void 0 || _appRef$current3.setMuiThemeName(themeName);
})();
},
context(ctx) {
(async _appRef$current4 => {
await rendered;
// Should be done here, unify contraints and interactions
if (ctx) {
unifyContraintsAndInteractions(ctx);
}
appRef === null || appRef === void 0 || (_appRef$current4 = appRef.current) === null || _appRef$current4 === void 0 || _appRef$current4.setContext(ctx);
})();
},
destroy() {
destroyed = true;
componentsUnmount.forEach(c => {
c && c();
});
modelStore.destroy();
root.unmount();
document.body.removeChild(element);
}
}, modelStore, selectionStore, appRef, rendered];
}
const reflow = node => node.scrollTop;
function getTransitionProps(props, options) {
const {
timeout,
easing,
style = {}
} = props;
return {
duration: style.transitionDuration ?? (typeof timeout === 'number' ? timeout : timeout[options.mode] || 0),
easing: style.transitionTimingFunction ?? (typeof easing === 'object' ? easing[options.mode] : easing),
delay: style.transitionDelay
};
}
function getPaperUtilityClass(slot) {
return generateUtilityClass('MuiPaper', slot);
}
generateUtilityClasses('MuiPaper', ['root', 'rounded', 'outlined', 'elevation', 'elevation0', 'elevation1', 'elevation2', 'elevation3', 'elevation4', 'elevation5', 'elevation6', 'elevation7', 'elevation8', 'elevation9', 'elevation10', 'elevation11', 'elevation12', 'elevation13', 'elevation14', 'elevation15', 'elevation16', 'elevation17', 'elevation18', 'elevation19', 'elevation20', 'elevation21', 'elevation22', 'elevation23', 'elevation24']);
const useUtilityClasses$n = ownerState => {
const {
square,
elevation,
variant,
classes
} = ownerState;
const slots = {
root: ['root', variant, !square && 'rounded', variant === 'elevation' && `elevation${elevation}`]
};
return composeClasses(slots, getPaperUtilityClass, classes);
};
const PaperRoot = styled('div', {
name: 'MuiPaper',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, styles[ownerState.variant], !ownerState.square && styles.rounded, ownerState.variant === 'elevation' && styles[`elevation${ownerState.elevation}`]];
}
})(memoTheme(({
theme
}) => ({
backgroundColor: (theme.vars || theme).palette.background.paper,
color: (theme.vars || theme).palette.text.primary,
transition: theme.transitions.create('box-shadow'),
variants: [{
props: ({
ownerState
}) => !ownerState.square,
style: {
borderRadius: theme.shape.borderRadius
}
}, {
props: {
variant: 'outlined'
},
style: {
border: `1px solid ${(theme.vars || theme).palette.divider}`
}
}, {
props: {
variant: 'elevation'
},
style: {
boxShadow: 'var(--Paper-shadow)',
backgroundImage: 'var(--Paper-overlay)'
}
}]
})));
const Paper = /*#__PURE__*/reactExports.forwardRef(function Paper(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiPaper'
});
const theme = useTheme$1();
const {
className,
component = 'div',
elevation = 1,
square = false,
variant = 'elevation',
...other
} = props;
const ownerState = {
...props,
component,
elevation,
square,
variant
};
const classes = useUtilityClasses$n(ownerState);
return /*#__PURE__*/jsxRuntimeExports.jsx(PaperRoot, {
as: component,
ownerState: ownerState,
className: clsx(classes.root, className),
ref: ref,
...other,
style: {
...(variant === 'elevation' && {
'--Paper-shadow': (theme.vars || theme).shadows[elevation],
...(theme.vars && {
'--Paper-overlay': theme.vars.overlays?.[elevation]
}),
...(!theme.vars && theme.palette.mode === 'dark' && {
'--Paper-overlay': `linear-gradient(${alpha('#fff', getOverlayAlpha(elevation))}, ${alpha('#fff', getOverlayAlpha(elevation))})`
})
}),
...other.style
}
});
});
/**
* An internal function to create a Material UI slot.
*
* This is an advanced version of Base UI `useSlotProps` because Material UI allows leaf component to be customized via `component` prop
* while Base UI does not need to support leaf component customization.
*
* @param {string} name: name of the slot
* @param {object} parameters
* @returns {[Slot, slotProps]} The slot's React component and the slot's props
*
* Note: the returned slot's props
* - will never contain `component` prop.
* - might contain `as` prop.
*/
function useSlot(
/**
* The slot's name. All Material UI components should have `root` slot.
*
* If the name is `root`, the logic behaves differently from other slots,
* e.g. the `externalForwardedProps` are spread to `root` slot but not other slots.
*/
name, parameters) {
const {
className,
elementType: initialElementType,
ownerState,
externalForwardedProps,
internalForwardedProps,
shouldForwardComponentProp = false,
...useSlotPropsParams
} = parameters;
const {
component: rootComponent,
slots = {
[name]: undefined
},
slotProps = {
[name]: undefined
},
...other
} = externalForwardedProps;
const elementType = slots[name] || initialElementType;
// `slotProps[name]` can be a callback that receives the component's ownerState.
// `resolvedComponentsProps` is always a plain object.
const resolvedComponentsProps = resolveComponentProps(slotProps[name], ownerState);
const {
props: {
component: slotComponent,
...mergedProps
},
internalRef
} = mergeSlotProps$1({
className,
...useSlotPropsParams,
externalForwardedProps: name === 'root' ? other : undefined,
externalSlotProps: resolvedComponentsProps
});
const ref = useForkRef(internalRef, resolvedComponentsProps?.ref, parameters.ref);
const LeafComponent = name === 'root' ? slotComponent || rootComponent : slotComponent;
const props = appendOwnerState(elementType, {
...(name === 'root' && !rootComponent && !slots[name] && internalForwardedProps),
...(name !== 'root' && !slots[name] && internalForwardedProps),
...mergedProps,
...(LeafComponent && !shouldForwardComponentProp && {
as: LeafComponent
}),
...(LeafComponent && shouldForwardComponentProp && {
component: LeafComponent
}),
ref
}, ownerState);
return [elementType, props];
}
function getIconButtonUtilityClass(slot) {
return generateUtilityClass('MuiIconButton', slot);
}
const iconButtonClasses = generateUtilityClasses('MuiIconButton', ['root', 'disabled', 'colorInherit', 'colorPrimary', 'colorSecondary', 'colorError', 'colorInfo', 'colorSuccess', 'colorWarning', 'edgeStart', 'edgeEnd', 'sizeSmall', 'sizeMedium', 'sizeLarge', 'loading', 'loadingIndicator', 'loadingWrapper']);
const useUtilityClasses$m = ownerState => {
const {
classes,
disabled,
color,
edge,
size,
loading
} = ownerState;
const slots = {
root: ['root', loading && 'loading', disabled && 'disabled', color !== 'default' && `color${capitalize(color)}`, edge && `edge${capitalize(edge)}`, `size${capitalize(size)}`],
loadingIndicator: ['loadingIndicator'],
loadingWrapper: ['loadingWrapper']
};
return composeClasses(slots, getIconButtonUtilityClass, classes);
};
const IconButtonRoot = styled(ButtonBase, {
name: 'MuiIconButton',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, ownerState.loading && styles.loading, ownerState.color !== 'default' && styles[`color${capitalize(ownerState.color)}`], ownerState.edge && styles[`edge${capitalize(ownerState.edge)}`], styles[`size${capitalize(ownerState.size)}`]];
}
})(memoTheme(({
theme
}) => ({
textAlign: 'center',
flex: '0 0 auto',
fontSize: theme.typography.pxToRem(24),
padding: 8,
borderRadius: '50%',
color: (theme.vars || theme).palette.action.active,
transition: theme.transitions.create('background-color', {
duration: theme.transitions.duration.shortest
}),
variants: [{
props: props => !props.disableRipple,
style: {
'--IconButton-hoverBg': theme.vars ? `rgba(${theme.vars.palette.action.activeChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette.action.active, theme.palette.action.hoverOpacity),
'&:hover': {
backgroundColor: 'var(--IconButton-hoverBg)',
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
}
}, {
props: {
edge: 'start'
},
style: {
marginLeft: -12
}
}, {
props: {
edge: 'start',
size: 'small'
},
style: {
marginLeft: -3
}
}, {
props: {
edge: 'end'
},
style: {
marginRight: -12
}
}, {
props: {
edge: 'end',
size: 'small'
},
style: {
marginRight: -3
}
}]
})), memoTheme(({
theme
}) => ({
variants: [{
props: {
color: 'inherit'
},
style: {
color: 'inherit'
}
}, ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()) // check all the used fields in the style below
.map(([color]) => ({
props: {
color
},
style: {
color: (theme.vars || theme).palette[color].main
}
})), ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()) // check all the used fields in the style below
.map(([color]) => ({
props: {
color
},
style: {
'--IconButton-hoverBg': theme.vars ? `rgba(${(theme.vars || theme).palette[color].mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha((theme.vars || theme).palette[color].main, theme.palette.action.hoverOpacity)
}
})), {
props: {
size: 'small'
},
style: {
padding: 5,
fontSize: theme.typography.pxToRem(18)
}
}, {
props: {
size: 'large'
},
style: {
padding: 12,
fontSize: theme.typography.pxToRem(28)
}
}],
[`&.${iconButtonClasses.disabled}`]: {
backgroundColor: 'transparent',
color: (theme.vars || theme).palette.action.disabled
},
[`&.${iconButtonClasses.loading}`]: {
color: 'transparent'
}
})));
const IconButtonLoadingIndicator = styled('span', {
name: 'MuiIconButton',
slot: 'LoadingIndicator',
overridesResolver: (props, styles) => styles.loadingIndicator
})(({
theme
}) => ({
display: 'none',
position: 'absolute',
visibility: 'visible',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
color: (theme.vars || theme).palette.action.disabled,
variants: [{
props: {
loading: true
},
style: {
display: 'flex'
}
}]
}));
/**
* Refer to the [Icons](/material-ui/icons/) section of the documentation
* regarding the available icon options.
*/
const IconButton = /*#__PURE__*/reactExports.forwardRef(function IconButton(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiIconButton'
});
const {
edge = false,
children,
className,
color = 'default',
disabled = false,
disableFocusRipple = false,
size = 'medium',
id: idProp,
loading = null,
loadingIndicator: loadingIndicatorProp,
...other
} = props;
const loadingId = useId(idProp);
const loadingIndicator = loadingIndicatorProp ?? /*#__PURE__*/jsxRuntimeExports.jsx(CircularProgress, {
"aria-labelledby": loadingId,
color: "inherit",
size: 16
});
const ownerState = {
...props,
edge,
color,
disabled,
disableFocusRipple,
loading,
loadingIndicator,
size
};
const classes = useUtilityClasses$m(ownerState);
return /*#__PURE__*/jsxRuntimeExports.jsxs(IconButtonRoot, {
id: loading ? loadingId : idProp,
className: clsx(classes.root, className),
centerRipple: true,
focusRipple: !disableFocusRipple,
disabled: disabled || loading,
ref: ref,
...other,
ownerState: ownerState,
children: [typeof loading === 'boolean' &&
/*#__PURE__*/
// use plain HTML span to minimize the runtime overhead
jsxRuntimeExports.jsx("span", {
className: classes.loadingWrapper,
style: {
display: 'contents'
},
children: /*#__PURE__*/jsxRuntimeExports.jsx(IconButtonLoadingIndicator, {
className: classes.loadingIndicator,
ownerState: ownerState,
children: loading && loadingIndicator
})
}), children]
});
});
function getTypographyUtilityClass(slot) {
return generateUtilityClass('MuiTypography', slot);
}
generateUtilityClasses('MuiTypography', ['root', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'subtitle1', 'subtitle2', 'body1', 'body2', 'inherit', 'button', 'caption', 'overline', 'alignLeft', 'alignRight', 'alignCenter', 'alignJustify', 'noWrap', 'gutterBottom', 'paragraph']);
const v6Colors = {
primary: true,
secondary: true,
error: true,
info: true,
success: true,
warning: true,
textPrimary: true,
textSecondary: true,
textDisabled: true
};
const extendSxProp = internal_createExtendSxProp();
const useUtilityClasses$l = ownerState => {
const {
align,
gutterBottom,
noWrap,
paragraph,
variant,
classes
} = ownerState;
const slots = {
root: ['root', variant, ownerState.align !== 'inherit' && `align${capitalize(align)}`, gutterBottom && 'gutterBottom', noWrap && 'noWrap', paragraph && 'paragraph']
};
return composeClasses(slots, getTypographyUtilityClass, classes);
};
const TypographyRoot = styled('span', {
name: 'MuiTypography',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, ownerState.variant && styles[ownerState.variant], ownerState.align !== 'inherit' && styles[`align${capitalize(ownerState.align)}`], ownerState.noWrap && styles.noWrap, ownerState.gutterBottom && styles.gutterBottom, ownerState.paragraph && styles.paragraph];
}
})(memoTheme(({
theme
}) => ({
margin: 0,
variants: [{
props: {
variant: 'inherit'
},
style: {
// Some elements, like <button> on Chrome have default font that doesn't inherit, reset this.
font: 'inherit',
lineHeight: 'inherit',
letterSpacing: 'inherit'
}
}, ...Object.entries(theme.typography).filter(([variant, value]) => variant !== 'inherit' && value && typeof value === 'object').map(([variant, value]) => ({
props: {
variant
},
style: value
})), ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()).map(([color]) => ({
props: {
color
},
style: {
color: (theme.vars || theme).palette[color].main
}
})), ...Object.entries(theme.palette?.text || {}).filter(([, value]) => typeof value === 'string').map(([color]) => ({
props: {
color: `text${capitalize(color)}`
},
style: {
color: (theme.vars || theme).palette.text[color]
}
})), {
props: ({
ownerState
}) => ownerState.align !== 'inherit',
style: {
textAlign: 'var(--Typography-textAlign)'
}
}, {
props: ({
ownerState
}) => ownerState.noWrap,
style: {
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
}
}, {
props: ({
ownerState
}) => ownerState.gutterBottom,
style: {
marginBottom: '0.35em'
}
}, {
props: ({
ownerState
}) => ownerState.paragraph,
style: {
marginBottom: 16
}
}]
})));
const defaultVariantMapping = {
h1: 'h1',
h2: 'h2',
h3: 'h3',
h4: 'h4',
h5: 'h5',
h6: 'h6',
subtitle1: 'h6',
subtitle2: 'h6',
body1: 'p',
body2: 'p',
inherit: 'p'
};
const Typography = /*#__PURE__*/reactExports.forwardRef(function Typography(inProps, ref) {
const {
color,
...themeProps
} = useDefaultProps({
props: inProps,
name: 'MuiTypography'
});
const isSxColor = !v6Colors[color];
// TODO: Remove `extendSxProp` in v7
const props = extendSxProp({
...themeProps,
...(isSxColor && {
color
})
});
const {
align = 'inherit',
className,
component,
gutterBottom = false,
noWrap = false,
paragraph = false,
variant = 'body1',
variantMapping = defaultVariantMapping,
...other
} = props;
const ownerState = {
...props,
align,
color,
className,
component,
gutterBottom,
noWrap,
paragraph,
variant,
variantMapping
};
const Component = component || (paragraph ? 'p' : variantMapping[variant] || defaultVariantMapping[variant]) || 'span';
const classes = useUtilityClasses$l(ownerState);
return /*#__PURE__*/jsxRuntimeExports.jsx(TypographyRoot, {
as: Component,
ref: ref,
className: clsx(classes.root, className),
...other,
ownerState: ownerState,
style: {
...(align !== 'inherit' && {
'--Typography-textAlign': align
}),
...other.style
}
});
});
var top = 'top';
var bottom = 'bottom';
var right = 'right';
var left = 'left';
var auto = 'auto';
var basePlacements = [top, bottom, right, left];
var start = 'start';
var end = 'end';
var clippingParents = 'clippingParents';
var viewport = 'viewport';
var popper = 'popper';
var reference = 'reference';
var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {
return acc.concat([placement + "-" + start, placement + "-" + end]);
}, []);
var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {
return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
}, []); // modifiers that need to read the DOM
var beforeRead = 'beforeRead';
var read = 'read';
var afterRead = 'afterRead'; // pure-logic modifiers
var beforeMain = 'beforeMain';
var main = 'main';
var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)
var beforeWrite = 'beforeWrite';
var write = 'write';
var afterWrite = 'afterWrite';
var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];
function getNodeName(element) {
return element ? (element.nodeName || '').toLowerCase() : null;
}
function getWindow(node) {
if (node == null) {
return window;
}
if (node.toString() !== '[object Window]') {
var ownerDocument = node.ownerDocument;
return ownerDocument ? ownerDocument.defaultView || window : window;
}
return node;
}
function isElement(node) {
var OwnElement = getWindow(node).Element;
return node instanceof OwnElement || node instanceof Element;
}
function isHTMLElement$1(node) {
var OwnElement = getWindow(node).HTMLElement;
return node instanceof OwnElement || node instanceof HTMLElement;
}
function isShadowRoot(node) {
// IE 11 has no ShadowRoot
if (typeof ShadowRoot === 'undefined') {
return false;
}
var OwnElement = getWindow(node).ShadowRoot;
return node instanceof OwnElement || node instanceof ShadowRoot;
}
// and applies them to the HTMLElements such as popper and arrow
function applyStyles(_ref) {
var state = _ref.state;
Object.keys(state.elements).forEach(function (name) {
var style = state.styles[name] || {};
var attributes = state.attributes[name] || {};
var element = state.elements[name]; // arrow is optional + virtual elements
if (!isHTMLElement$1(element) || !getNodeName(element)) {
return;
} // Flow doesn't support to extend this property, but it's the most
// effective way to apply styles to an HTMLElement
// $FlowFixMe[cannot-write]
Object.assign(element.style, style);
Object.keys(attributes).forEach(function (name) {
var value = attributes[name];
if (value === false) {
element.removeAttribute(name);
} else {
element.setAttribute(name, value === true ? '' : value);
}
});
});
}
function effect$2(_ref2) {
var state = _ref2.state;
var initialStyles = {
popper: {
position: state.options.strategy,
left: '0',
top: '0',
margin: '0'
},
arrow: {
position: 'absolute'
},
reference: {}
};
Object.assign(state.elements.popper.style, initialStyles.popper);
state.styles = initialStyles;
if (state.elements.arrow) {
Object.assign(state.elements.arrow.style, initialStyles.arrow);
}
return function () {
Object.keys(state.elements).forEach(function (name) {
var element = state.elements[name];
var attributes = state.attributes[name] || {};
var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them
var style = styleProperties.reduce(function (style, property) {
style[property] = '';
return style;
}, {}); // arrow is optional + virtual elements
if (!isHTMLElement$1(element) || !getNodeName(element)) {
return;
}
Object.assign(element.style, style);
Object.keys(attributes).forEach(function (attribute) {
element.removeAttribute(attribute);
});
});
};
} // eslint-disable-next-line import/no-unused-modules
var applyStyles$1 = {
name: 'applyStyles',
enabled: true,
phase: 'write',
fn: applyStyles,
effect: effect$2,
requires: ['computeStyles']
};
function getBasePlacement(placement) {
return placement.split('-')[0];
}
var max = Math.max;
var min = Math.min;
var round$1 = Math.round;
function getUAString() {
var uaData = navigator.userAgentData;
if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {
return uaData.brands.map(function (item) {
return item.brand + "/" + item.version;
}).join(' ');
}
return navigator.userAgent;
}
function isLayoutViewport() {
return !/^((?!chrome|android).)*safari/i.test(getUAString());
}
function getBoundingClientRect(element, includeScale, isFixedStrategy) {
if (includeScale === void 0) {
includeScale = false;
}
if (isFixedStrategy === void 0) {
isFixedStrategy = false;
}
var clientRect = element.getBoundingClientRect();
var scaleX = 1;
var scaleY = 1;
if (includeScale && isHTMLElement$1(element)) {
scaleX = element.offsetWidth > 0 ? round$1(clientRect.width) / element.offsetWidth || 1 : 1;
scaleY = element.offsetHeight > 0 ? round$1(clientRect.height) / element.offsetHeight || 1 : 1;
}
var _ref = isElement(element) ? getWindow(element) : window,
visualViewport = _ref.visualViewport;
var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;
var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;
var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;
var width = clientRect.width / scaleX;
var height = clientRect.height / scaleY;
return {
width: width,
height: height,
top: y,
right: x + width,
bottom: y + height,
left: x,
x: x,
y: y
};
}
// means it doesn't take into account transforms.
function getLayoutRect(element) {
var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.
// Fixes https://github.com/popperjs/popper-core/issues/1223
var width = element.offsetWidth;
var height = element.offsetHeight;
if (Math.abs(clientRect.width - width) <= 1) {
width = clientRect.width;
}
if (Math.abs(clientRect.height - height) <= 1) {
height = clientRect.height;
}
return {
x: element.offsetLeft,
y: element.offsetTop,
width: width,
height: height
};
}
function contains(parent, child) {
var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method
if (parent.contains(child)) {
return true;
} // then fallback to custom implementation with Shadow DOM support
else if (rootNode && isShadowRoot(rootNode)) {
var next = child;
do {
if (next && parent.isSameNode(next)) {
return true;
} // $FlowFixMe[prop-missing]: need a better way to handle this...
next = next.parentNode || next.host;
} while (next);
} // Give up, the result is false
return false;
}
function getComputedStyle(element) {
return getWindow(element).getComputedStyle(element);
}
function isTableElement(element) {
return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;
}
function getDocumentElement(element) {
// $FlowFixMe[incompatible-return]: assume body is always available
return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]
element.document) || window.document).documentElement;
}
function getParentNode(element) {
if (getNodeName(element) === 'html') {
return element;
}
return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle
// $FlowFixMe[incompatible-return]
// $FlowFixMe[prop-missing]
element.assignedSlot || // step into the shadow DOM of the parent of a slotted node
element.parentNode || ( // DOM Element detected
isShadowRoot(element) ? element.host : null) || // ShadowRoot detected
// $FlowFixMe[incompatible-call]: HTMLElement is a Node
getDocumentElement(element) // fallback
);
}
function getTrueOffsetParent(element) {
if (!isHTMLElement$1(element) || // https://github.com/popperjs/popper-core/issues/837
getComputedStyle(element).position === 'fixed') {
return null;
}
return element.offsetParent;
} // `.offsetParent` reports `null` for fixed elements, while absolute elements
// return the containing block
function getContainingBlock(element) {
var isFirefox = /firefox/i.test(getUAString());
var isIE = /Trident/i.test(getUAString());
if (isIE && isHTMLElement$1(element)) {
// In IE 9, 10 and 11 fixed elements containing block is always established by the viewport
var elementCss = getComputedStyle(element);
if (elementCss.position === 'fixed') {
return null;
}
}
var currentNode = getParentNode(element);
if (isShadowRoot(currentNode)) {
currentNode = currentNode.host;
}
while (isHTMLElement$1(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {
var css = getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that
// create a containing block.
// https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {
return currentNode;
} else {
currentNode = currentNode.parentNode;
}
}
return null;
} // Gets the closest ancestor positioned element. Handles some edge cases,
// such as table ancestors and cross browser bugs.
function getOffsetParent(element) {
var window = getWindow(element);
var offsetParent = getTrueOffsetParent(element);
while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {
offsetParent = getTrueOffsetParent(offsetParent);
}
if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static')) {
return window;
}
return offsetParent || getContainingBlock(element) || window;
}
function getMainAxisFromPlacement(placement) {
return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';
}
function within(min$1, value, max$1) {
return max(min$1, min(value, max$1));
}
function withinMaxClamp(min, value, max) {
var v = within(min, value, max);
return v > max ? max : v;
}
function getFreshSideObject() {
return {
top: 0,
right: 0,
bottom: 0,
left: 0
};
}
function mergePaddingObject(paddingObject) {
return Object.assign({}, getFreshSideObject(), paddingObject);
}
function expandToHashMap(value, keys) {
return keys.reduce(function (hashMap, key) {
hashMap[key] = value;
return hashMap;
}, {});
}
var toPaddingObject = function toPaddingObject(padding, state) {
padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {
placement: state.placement
})) : padding;
return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
};
function arrow(_ref) {
var _state$modifiersData$;
var state = _ref.state,
name = _ref.name,
options = _ref.options;
var arrowElement = state.elements.arrow;
var popperOffsets = state.modifiersData.popperOffsets;
var basePlacement = getBasePlacement(state.placement);
var axis = getMainAxisFromPlacement(basePlacement);
var isVertical = [left, right].indexOf(basePlacement) >= 0;
var len = isVertical ? 'height' : 'width';
if (!arrowElement || !popperOffsets) {
return;
}
var paddingObject = toPaddingObject(options.padding, state);
var arrowRect = getLayoutRect(arrowElement);
var minProp = axis === 'y' ? top : left;
var maxProp = axis === 'y' ? bottom : right;
var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];
var startDiff = popperOffsets[axis] - state.rects.reference[axis];
var arrowOffsetParent = getOffsetParent(arrowElement);
var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is
// outside of the popper bounds
var min = paddingObject[minProp];
var max = clientSize - arrowRect[len] - paddingObject[maxProp];
var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
var offset = within(min, center, max); // Prevents breaking syntax highlighting...
var axisProp = axis;
state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);
}
function effect$1(_ref2) {
var state = _ref2.state,
options = _ref2.options;
var _options$element = options.element,
arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;
if (arrowElement == null) {
return;
} // CSS selector
if (typeof arrowElement === 'string') {
arrowElement = state.elements.popper.querySelector(arrowElement);
if (!arrowElement) {
return;
}
}
if (!contains(state.elements.popper, arrowElement)) {
return;
}
state.elements.arrow = arrowElement;
} // eslint-disable-next-line import/no-unused-modules
var arrow$1 = {
name: 'arrow',
enabled: true,
phase: 'main',
fn: arrow,
effect: effect$1,
requires: ['popperOffsets'],
requiresIfExists: ['preventOverflow']
};
function getVariation(placement) {
return placement.split('-')[1];
}
var unsetSides = {
top: 'auto',
right: 'auto',
bottom: 'auto',
left: 'auto'
}; // Round the offsets to the nearest suitable subpixel based on the DPR.
// Zooming can change the DPR, but it seems to report a value that will
// cleanly divide the values into the appropriate subpixels.
function roundOffsetsByDPR(_ref, win) {
var x = _ref.x,
y = _ref.y;
var dpr = win.devicePixelRatio || 1;
return {
x: round$1(x * dpr) / dpr || 0,
y: round$1(y * dpr) / dpr || 0
};
}
function mapToStyles(_ref2) {
var _Object$assign2;
var popper = _ref2.popper,
popperRect = _ref2.popperRect,
placement = _ref2.placement,
variation = _ref2.variation,
offsets = _ref2.offsets,
position = _ref2.position,
gpuAcceleration = _ref2.gpuAcceleration,
adaptive = _ref2.adaptive,
roundOffsets = _ref2.roundOffsets,
isFixed = _ref2.isFixed;
var _offsets$x = offsets.x,
x = _offsets$x === void 0 ? 0 : _offsets$x,
_offsets$y = offsets.y,
y = _offsets$y === void 0 ? 0 : _offsets$y;
var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({
x: x,
y: y
}) : {
x: x,
y: y
};
x = _ref3.x;
y = _ref3.y;
var hasX = offsets.hasOwnProperty('x');
var hasY = offsets.hasOwnProperty('y');
var sideX = left;
var sideY = top;
var win = window;
if (adaptive) {
var offsetParent = getOffsetParent(popper);
var heightProp = 'clientHeight';
var widthProp = 'clientWidth';
if (offsetParent === getWindow(popper)) {
offsetParent = getDocumentElement(popper);
if (getComputedStyle(offsetParent).position !== 'static' && position === 'absolute') {
heightProp = 'scrollHeight';
widthProp = 'scrollWidth';
}
} // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it
offsetParent = offsetParent;
if (placement === top || (placement === left || placement === right) && variation === end) {
sideY = bottom;
var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing]
offsetParent[heightProp];
y -= offsetY - popperRect.height;
y *= gpuAcceleration ? 1 : -1;
}
if (placement === left || (placement === top || placement === bottom) && variation === end) {
sideX = right;
var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing]
offsetParent[widthProp];
x -= offsetX - popperRect.width;
x *= gpuAcceleration ? 1 : -1;
}
}
var commonStyles = Object.assign({
position: position
}, adaptive && unsetSides);
var _ref4 = roundOffsets === true ? roundOffsetsByDPR({
x: x,
y: y
}, getWindow(popper)) : {
x: x,
y: y
};
x = _ref4.x;
y = _ref4.y;
if (gpuAcceleration) {
var _Object$assign;
return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
}
return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2));
}
function computeStyles(_ref5) {
var state = _ref5.state,
options = _ref5.options;
var _options$gpuAccelerat = options.gpuAcceleration,
gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,
_options$adaptive = options.adaptive,
adaptive = _options$adaptive === void 0 ? true : _options$adaptive,
_options$roundOffsets = options.roundOffsets,
roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
var commonStyles = {
placement: getBasePlacement(state.placement),
variation: getVariation(state.placement),
popper: state.elements.popper,
popperRect: state.rects.popper,
gpuAcceleration: gpuAcceleration,
isFixed: state.options.strategy === 'fixed'
};
if (state.modifiersData.popperOffsets != null) {
state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
offsets: state.modifiersData.popperOffsets,
position: state.options.strategy,
adaptive: adaptive,
roundOffsets: roundOffsets
})));
}
if (state.modifiersData.arrow != null) {
state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
offsets: state.modifiersData.arrow,
position: 'absolute',
adaptive: false,
roundOffsets: roundOffsets
})));
}
state.attributes.popper = Object.assign({}, state.attributes.popper, {
'data-popper-placement': state.placement
});
} // eslint-disable-next-line import/no-unused-modules
var computeStyles$1 = {
name: 'computeStyles',
enabled: true,
phase: 'beforeWrite',
fn: computeStyles,
data: {}
};
var passive = {
passive: true
};
function effect(_ref) {
var state = _ref.state,
instance = _ref.instance,
options = _ref.options;
var _options$scroll = options.scroll,
scroll = _options$scroll === void 0 ? true : _options$scroll,
_options$resize = options.resize,
resize = _options$resize === void 0 ? true : _options$resize;
var window = getWindow(state.elements.popper);
var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
if (scroll) {
scrollParents.forEach(function (scrollParent) {
scrollParent.addEventListener('scroll', instance.update, passive);
});
}
if (resize) {
window.addEventListener('resize', instance.update, passive);
}
return function () {
if (scroll) {
scrollParents.forEach(function (scrollParent) {
scrollParent.removeEventListener('scroll', instance.update, passive);
});
}
if (resize) {
window.removeEventListener('resize', instance.update, passive);
}
};
} // eslint-disable-next-line import/no-unused-modules
var eventListeners = {
name: 'eventListeners',
enabled: true,
phase: 'write',
fn: function fn() {},
effect: effect,
data: {}
};
var hash$1 = {
left: 'right',
right: 'left',
bottom: 'top',
top: 'bottom'
};
function getOppositePlacement(placement) {
return placement.replace(/left|right|bottom|top/g, function (matched) {
return hash$1[matched];
});
}
var hash = {
start: 'end',
end: 'start'
};
function getOppositeVariationPlacement(placement) {
return placement.replace(/start|end/g, function (matched) {
return hash[matched];
});
}
function getWindowScroll(node) {
var win = getWindow(node);
var scrollLeft = win.pageXOffset;
var scrollTop = win.pageYOffset;
return {
scrollLeft: scrollLeft,
scrollTop: scrollTop
};
}
function getWindowScrollBarX(element) {
// If <html> has a CSS width greater than the viewport, then this will be
// incorrect for RTL.
// Popper 1 is broken in this case and never had a bug report so let's assume
// it's not an issue. I don't think anyone ever specifies width on <html>
// anyway.
// Browsers where the left scrollbar doesn't cause an issue report `0` for
// this (e.g. Edge 2019, IE11, Safari)
return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
}
function getViewportRect(element, strategy) {
var win = getWindow(element);
var html = getDocumentElement(element);
var visualViewport = win.visualViewport;
var width = html.clientWidth;
var height = html.clientHeight;
var x = 0;
var y = 0;
if (visualViewport) {
width = visualViewport.width;
height = visualViewport.height;
var layoutViewport = isLayoutViewport();
if (layoutViewport || !layoutViewport && strategy === 'fixed') {
x = visualViewport.offsetLeft;
y = visualViewport.offsetTop;
}
}
return {
width: width,
height: height,
x: x + getWindowScrollBarX(element),
y: y
};
}
// of the `<html>` and `<body>` rect bounds if horizontally scrollable
function getDocumentRect(element) {
var _element$ownerDocumen;
var html = getDocumentElement(element);
var winScroll = getWindowScroll(element);
var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
var y = -winScroll.scrollTop;
if (getComputedStyle(body || html).direction === 'rtl') {
x += max(html.clientWidth, body ? body.clientWidth : 0) - width;
}
return {
width: width,
height: height,
x: x,
y: y
};
}
function isScrollParent(element) {
// Firefox wants us to check `-x` and `-y` variations as well
var _getComputedStyle = getComputedStyle(element),
overflow = _getComputedStyle.overflow,
overflowX = _getComputedStyle.overflowX,
overflowY = _getComputedStyle.overflowY;
return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}
function getScrollParent(node) {
if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {
// $FlowFixMe[incompatible-return]: assume body is always available
return node.ownerDocument.body;
}
if (isHTMLElement$1(node) && isScrollParent(node)) {
return node;
}
return getScrollParent(getParentNode(node));
}
/*
given a DOM element, return the list of all scroll parents, up the list of ancesors
until we get to the top window object. This list is what we attach scroll listeners
to, because if any of these parent elements scroll, we'll need to re-calculate the
reference element's position.
*/
function listScrollParents(element, list) {
var _element$ownerDocumen;
if (list === void 0) {
list = [];
}
var scrollParent = getScrollParent(element);
var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
var win = getWindow(scrollParent);
var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
var updatedList = list.concat(target);
return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
updatedList.concat(listScrollParents(getParentNode(target)));
}
function rectToClientRect(rect) {
return Object.assign({}, rect, {
left: rect.x,
top: rect.y,
right: rect.x + rect.width,
bottom: rect.y + rect.height
});
}
function getInnerBoundingClientRect(element, strategy) {
var rect = getBoundingClientRect(element, false, strategy === 'fixed');
rect.top = rect.top + element.clientTop;
rect.left = rect.left + element.clientLeft;
rect.bottom = rect.top + element.clientHeight;
rect.right = rect.left + element.clientWidth;
rect.width = element.clientWidth;
rect.height = element.clientHeight;
rect.x = rect.left;
rect.y = rect.top;
return rect;
}
function getClientRectFromMixedType(element, clippingParent, strategy) {
return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
} // A "clipping parent" is an overflowable container with the characteristic of
// clipping (or hiding) overflowing elements with a position different from
// `initial`
function getClippingParents(element) {
var clippingParents = listScrollParents(getParentNode(element));
var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle(element).position) >= 0;
var clipperElement = canEscapeClipping && isHTMLElement$1(element) ? getOffsetParent(element) : element;
if (!isElement(clipperElement)) {
return [];
} // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414
return clippingParents.filter(function (clippingParent) {
return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';
});
} // Gets the maximum area that the element is visible in due to any number of
// clipping parents
function getClippingRect(element, boundary, rootBoundary, strategy) {
var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);
var clippingParents = [].concat(mainClippingParents, [rootBoundary]);
var firstClippingParent = clippingParents[0];
var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {
var rect = getClientRectFromMixedType(element, clippingParent, strategy);
accRect.top = max(rect.top, accRect.top);
accRect.right = min(rect.right, accRect.right);
accRect.bottom = min(rect.bottom, accRect.bottom);
accRect.left = max(rect.left, accRect.left);
return accRect;
}, getClientRectFromMixedType(element, firstClippingParent, strategy));
clippingRect.width = clippingRect.right - clippingRect.left;
clippingRect.height = clippingRect.bottom - clippingRect.top;
clippingRect.x = clippingRect.left;
clippingRect.y = clippingRect.top;
return clippingRect;
}
function computeOffsets(_ref) {
var reference = _ref.reference,
element = _ref.element,
placement = _ref.placement;
var basePlacement = placement ? getBasePlacement(placement) : null;
var variation = placement ? getVariation(placement) : null;
var commonX = reference.x + reference.width / 2 - element.width / 2;
var commonY = reference.y + reference.height / 2 - element.height / 2;
var offsets;
switch (basePlacement) {
case top:
offsets = {
x: commonX,
y: reference.y - element.height
};
break;
case bottom:
offsets = {
x: commonX,
y: reference.y + reference.height
};
break;
case right:
offsets = {
x: reference.x + reference.width,
y: commonY
};
break;
case left:
offsets = {
x: reference.x - element.width,
y: commonY
};
break;
default:
offsets = {
x: reference.x,
y: reference.y
};
}
var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;
if (mainAxis != null) {
var len = mainAxis === 'y' ? 'height' : 'width';
switch (variation) {
case start:
offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);
break;
case end:
offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);
break;
}
}
return offsets;
}
function detectOverflow(state, options) {
if (options === void 0) {
options = {};
}
var _options = options,
_options$placement = _options.placement,
placement = _options$placement === void 0 ? state.placement : _options$placement,
_options$strategy = _options.strategy,
strategy = _options$strategy === void 0 ? state.strategy : _options$strategy,
_options$boundary = _options.boundary,
boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,
_options$rootBoundary = _options.rootBoundary,
rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,
_options$elementConte = _options.elementContext,
elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,
_options$altBoundary = _options.altBoundary,
altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,
_options$padding = _options.padding,
padding = _options$padding === void 0 ? 0 : _options$padding;
var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
var altContext = elementContext === popper ? reference : popper;
var popperRect = state.rects.popper;
var element = state.elements[altBoundary ? altContext : elementContext];
var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);
var referenceClientRect = getBoundingClientRect(state.elements.reference);
var popperOffsets = computeOffsets({
reference: referenceClientRect,
element: popperRect,
placement: placement
});
var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));
var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect
// 0 or negative = within the clipping rect
var overflowOffsets = {
top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
right: elementClientRect.right - clippingClientRect.right + paddingObject.right
};
var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element
if (elementContext === popper && offsetData) {
var offset = offsetData[placement];
Object.keys(overflowOffsets).forEach(function (key) {
var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';
overflowOffsets[key] += offset[axis] * multiply;
});
}
return overflowOffsets;
}
function computeAutoPlacement(state, options) {
if (options === void 0) {
options = {};
}
var _options = options,
placement = _options.placement,
boundary = _options.boundary,
rootBoundary = _options.rootBoundary,
padding = _options.padding,
flipVariations = _options.flipVariations,
_options$allowedAutoP = _options.allowedAutoPlacements,
allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP;
var variation = getVariation(placement);
var placements$1 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {
return getVariation(placement) === variation;
}) : basePlacements;
var allowedPlacements = placements$1.filter(function (placement) {
return allowedAutoPlacements.indexOf(placement) >= 0;
});
if (allowedPlacements.length === 0) {
allowedPlacements = placements$1;
} // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...
var overflows = allowedPlacements.reduce(function (acc, placement) {
acc[placement] = detectOverflow(state, {
placement: placement,
boundary: boundary,
rootBoundary: rootBoundary,
padding: padding
})[getBasePlacement(placement)];
return acc;
}, {});
return Object.keys(overflows).sort(function (a, b) {
return overflows[a] - overflows[b];
});
}
function getExpandedFallbackPlacements(placement) {
if (getBasePlacement(placement) === auto) {
return [];
}
var oppositePlacement = getOppositePlacement(placement);
return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
}
function flip(_ref) {
var state = _ref.state,
options = _ref.options,
name = _ref.name;
if (state.modifiersData[name]._skip) {
return;
}
var _options$mainAxis = options.mainAxis,
checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
_options$altAxis = options.altAxis,
checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,
specifiedFallbackPlacements = options.fallbackPlacements,
padding = options.padding,
boundary = options.boundary,
rootBoundary = options.rootBoundary,
altBoundary = options.altBoundary,
_options$flipVariatio = options.flipVariations,
flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,
allowedAutoPlacements = options.allowedAutoPlacements;
var preferredPlacement = state.options.placement;
var basePlacement = getBasePlacement(preferredPlacement);
var isBasePlacement = basePlacement === preferredPlacement;
var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {
return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {
placement: placement,
boundary: boundary,
rootBoundary: rootBoundary,
padding: padding,
flipVariations: flipVariations,
allowedAutoPlacements: allowedAutoPlacements
}) : placement);
}, []);
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var checksMap = new Map();
var makeFallbackChecks = true;
var firstFittingPlacement = placements[0];
for (var i = 0; i < placements.length; i++) {
var placement = placements[i];
var _basePlacement = getBasePlacement(placement);
var isStartVariation = getVariation(placement) === start;
var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;
var len = isVertical ? 'width' : 'height';
var overflow = detectOverflow(state, {
placement: placement,
boundary: boundary,
rootBoundary: rootBoundary,
altBoundary: altBoundary,
padding: padding
});
var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;
if (referenceRect[len] > popperRect[len]) {
mainVariationSide = getOppositePlacement(mainVariationSide);
}
var altVariationSide = getOppositePlacement(mainVariationSide);
var checks = [];
if (checkMainAxis) {
checks.push(overflow[_basePlacement] <= 0);
}
if (checkAltAxis) {
checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
}
if (checks.every(function (check) {
return check;
})) {
firstFittingPlacement = placement;
makeFallbackChecks = false;
break;
}
checksMap.set(placement, checks);
}
if (makeFallbackChecks) {
// `2` may be desired in some cases – research later
var numberOfChecks = flipVariations ? 3 : 1;
var _loop = function _loop(_i) {
var fittingPlacement = placements.find(function (placement) {
var checks = checksMap.get(placement);
if (checks) {
return checks.slice(0, _i).every(function (check) {
return check;
});
}
});
if (fittingPlacement) {
firstFittingPlacement = fittingPlacement;
return "break";
}
};
for (var _i = numberOfChecks; _i > 0; _i--) {
var _ret = _loop(_i);
if (_ret === "break") break;
}
}
if (state.placement !== firstFittingPlacement) {
state.modifiersData[name]._skip = true;
state.placement = firstFittingPlacement;
state.reset = true;
}
} // eslint-disable-next-line import/no-unused-modules
var flip$1 = {
name: 'flip',
enabled: true,
phase: 'main',
fn: flip,
requiresIfExists: ['offset'],
data: {
_skip: false
}
};
function getSideOffsets(overflow, rect, preventedOffsets) {
if (preventedOffsets === void 0) {
preventedOffsets = {
x: 0,
y: 0
};
}
return {
top: overflow.top - rect.height - preventedOffsets.y,
right: overflow.right - rect.width + preventedOffsets.x,
bottom: overflow.bottom - rect.height + preventedOffsets.y,
left: overflow.left - rect.width - preventedOffsets.x
};
}
function isAnySideFullyClipped(overflow) {
return [top, right, bottom, left].some(function (side) {
return overflow[side] >= 0;
});
}
function hide(_ref) {
var state = _ref.state,
name = _ref.name;
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var preventedOffsets = state.modifiersData.preventOverflow;
var referenceOverflow = detectOverflow(state, {
elementContext: 'reference'
});
var popperAltOverflow = detectOverflow(state, {
altBoundary: true
});
var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
state.modifiersData[name] = {
referenceClippingOffsets: referenceClippingOffsets,
popperEscapeOffsets: popperEscapeOffsets,
isReferenceHidden: isReferenceHidden,
hasPopperEscaped: hasPopperEscaped
};
state.attributes.popper = Object.assign({}, state.attributes.popper, {
'data-popper-reference-hidden': isReferenceHidden,
'data-popper-escaped': hasPopperEscaped
});
} // eslint-disable-next-line import/no-unused-modules
var hide$1 = {
name: 'hide',
enabled: true,
phase: 'main',
requiresIfExists: ['preventOverflow'],
fn: hide
};
function distanceAndSkiddingToXY(placement, rects, offset) {
var basePlacement = getBasePlacement(placement);
var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;
var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {
placement: placement
})) : offset,
skidding = _ref[0],
distance = _ref[1];
skidding = skidding || 0;
distance = (distance || 0) * invertDistance;
return [left, right].indexOf(basePlacement) >= 0 ? {
x: distance,
y: skidding
} : {
x: skidding,
y: distance
};
}
function offset(_ref2) {
var state = _ref2.state,
options = _ref2.options,
name = _ref2.name;
var _options$offset = options.offset,
offset = _options$offset === void 0 ? [0, 0] : _options$offset;
var data = placements.reduce(function (acc, placement) {
acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);
return acc;
}, {});
var _data$state$placement = data[state.placement],
x = _data$state$placement.x,
y = _data$state$placement.y;
if (state.modifiersData.popperOffsets != null) {
state.modifiersData.popperOffsets.x += x;
state.modifiersData.popperOffsets.y += y;
}
state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules
var offset$1 = {
name: 'offset',
enabled: true,
phase: 'main',
requires: ['popperOffsets'],
fn: offset
};
function popperOffsets(_ref) {
var state = _ref.state,
name = _ref.name;
// Offsets are the actual position the popper needs to have to be
// properly positioned near its reference element
// This is the most basic placement, and will be adjusted by
// the modifiers in the next step
state.modifiersData[name] = computeOffsets({
reference: state.rects.reference,
element: state.rects.popper,
placement: state.placement
});
} // eslint-disable-next-line import/no-unused-modules
var popperOffsets$1 = {
name: 'popperOffsets',
enabled: true,
phase: 'read',
fn: popperOffsets,
data: {}
};
function getAltAxis(axis) {
return axis === 'x' ? 'y' : 'x';
}
function preventOverflow(_ref) {
var state = _ref.state,
options = _ref.options,
name = _ref.name;
var _options$mainAxis = options.mainAxis,
checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
_options$altAxis = options.altAxis,
checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,
boundary = options.boundary,
rootBoundary = options.rootBoundary,
altBoundary = options.altBoundary,
padding = options.padding,
_options$tether = options.tether,
tether = _options$tether === void 0 ? true : _options$tether,
_options$tetherOffset = options.tetherOffset,
tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
var overflow = detectOverflow(state, {
boundary: boundary,
rootBoundary: rootBoundary,
padding: padding,
altBoundary: altBoundary
});
var basePlacement = getBasePlacement(state.placement);
var variation = getVariation(state.placement);
var isBasePlacement = !variation;
var mainAxis = getMainAxisFromPlacement(basePlacement);
var altAxis = getAltAxis(mainAxis);
var popperOffsets = state.modifiersData.popperOffsets;
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {
placement: state.placement
})) : tetherOffset;
var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {
mainAxis: tetherOffsetValue,
altAxis: tetherOffsetValue
} : Object.assign({
mainAxis: 0,
altAxis: 0
}, tetherOffsetValue);
var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;
var data = {
x: 0,
y: 0
};
if (!popperOffsets) {
return;
}
if (checkMainAxis) {
var _offsetModifierState$;
var mainSide = mainAxis === 'y' ? top : left;
var altSide = mainAxis === 'y' ? bottom : right;
var len = mainAxis === 'y' ? 'height' : 'width';
var offset = popperOffsets[mainAxis];
var min$1 = offset + overflow[mainSide];
var max$1 = offset - overflow[altSide];
var additive = tether ? -popperRect[len] / 2 : 0;
var minLen = variation === start ? referenceRect[len] : popperRect[len];
var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go
// outside the reference bounds
var arrowElement = state.elements.arrow;
var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
width: 0,
height: 0
};
var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();
var arrowPaddingMin = arrowPaddingObject[mainSide];
var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want
// to include its full size in the calculation. If the reference is small
// and near the edge of a boundary, the popper can overflow even if the
// reference is not overflowing as well (e.g. virtual elements with no
// width or height)
var arrowLen = within(0, referenceRect[len], arrowRect[len]);
var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;
var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;
var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;
var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;
var tetherMax = offset + maxOffset - offsetModifierValue;
var preventedOffset = within(tether ? min(min$1, tetherMin) : min$1, offset, tether ? max(max$1, tetherMax) : max$1);
popperOffsets[mainAxis] = preventedOffset;
data[mainAxis] = preventedOffset - offset;
}
if (checkAltAxis) {
var _offsetModifierState$2;
var _mainSide = mainAxis === 'x' ? top : left;
var _altSide = mainAxis === 'x' ? bottom : right;
var _offset = popperOffsets[altAxis];
var _len = altAxis === 'y' ? 'height' : 'width';
var _min = _offset + overflow[_mainSide];
var _max = _offset - overflow[_altSide];
var isOriginSide = [top, left].indexOf(basePlacement) !== -1;
var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;
var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;
var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;
var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);
popperOffsets[altAxis] = _preventedOffset;
data[altAxis] = _preventedOffset - _offset;
}
state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules
var preventOverflow$1 = {
name: 'preventOverflow',
enabled: true,
phase: 'main',
fn: preventOverflow,
requiresIfExists: ['offset']
};
function getHTMLElementScroll(element) {
return {
scrollLeft: element.scrollLeft,
scrollTop: element.scrollTop
};
}
function getNodeScroll(node) {
if (node === getWindow(node) || !isHTMLElement$1(node)) {
return getWindowScroll(node);
} else {
return getHTMLElementScroll(node);
}
}
function isElementScaled(element) {
var rect = element.getBoundingClientRect();
var scaleX = round$1(rect.width) / element.offsetWidth || 1;
var scaleY = round$1(rect.height) / element.offsetHeight || 1;
return scaleX !== 1 || scaleY !== 1;
} // Returns the composite rect of an element relative to its offsetParent.
// Composite means it takes into account transforms as well as layout.
function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
if (isFixed === void 0) {
isFixed = false;
}
var isOffsetParentAnElement = isHTMLElement$1(offsetParent);
var offsetParentIsScaled = isHTMLElement$1(offsetParent) && isElementScaled(offsetParent);
var documentElement = getDocumentElement(offsetParent);
var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);
var scroll = {
scrollLeft: 0,
scrollTop: 0
};
var offsets = {
x: 0,
y: 0
};
if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078
isScrollParent(documentElement)) {
scroll = getNodeScroll(offsetParent);
}
if (isHTMLElement$1(offsetParent)) {
offsets = getBoundingClientRect(offsetParent, true);
offsets.x += offsetParent.clientLeft;
offsets.y += offsetParent.clientTop;
} else if (documentElement) {
offsets.x = getWindowScrollBarX(documentElement);
}
}
return {
x: rect.left + scroll.scrollLeft - offsets.x,
y: rect.top + scroll.scrollTop - offsets.y,
width: rect.width,
height: rect.height
};
}
function order(modifiers) {
var map = new Map();
var visited = new Set();
var result = [];
modifiers.forEach(function (modifier) {
map.set(modifier.name, modifier);
}); // On visiting object, check for its dependencies and visit them recursively
function sort(modifier) {
visited.add(modifier.name);
var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
requires.forEach(function (dep) {
if (!visited.has(dep)) {
var depModifier = map.get(dep);
if (depModifier) {
sort(depModifier);
}
}
});
result.push(modifier);
}
modifiers.forEach(function (modifier) {
if (!visited.has(modifier.name)) {
// check for visited object
sort(modifier);
}
});
return result;
}
function orderModifiers(modifiers) {
// order based on dependencies
var orderedModifiers = order(modifiers); // order based on phase
return modifierPhases.reduce(function (acc, phase) {
return acc.concat(orderedModifiers.filter(function (modifier) {
return modifier.phase === phase;
}));
}, []);
}
function debounce(fn) {
var pending;
return function () {
if (!pending) {
pending = new Promise(function (resolve) {
Promise.resolve().then(function () {
pending = undefined;
resolve(fn());
});
});
}
return pending;
};
}
function mergeByName(modifiers) {
var merged = modifiers.reduce(function (merged, current) {
var existing = merged[current.name];
merged[current.name] = existing ? Object.assign({}, existing, current, {
options: Object.assign({}, existing.options, current.options),
data: Object.assign({}, existing.data, current.data)
}) : current;
return merged;
}, {}); // IE11 does not support Object.values
return Object.keys(merged).map(function (key) {
return merged[key];
});
}
var DEFAULT_OPTIONS = {
placement: 'bottom',
modifiers: [],
strategy: 'absolute'
};
function areValidElements() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return !args.some(function (element) {
return !(element && typeof element.getBoundingClientRect === 'function');
});
}
function popperGenerator(generatorOptions) {
if (generatorOptions === void 0) {
generatorOptions = {};
}
var _generatorOptions = generatorOptions,
_generatorOptions$def = _generatorOptions.defaultModifiers,
defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,
_generatorOptions$def2 = _generatorOptions.defaultOptions,
defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
return function createPopper(reference, popper, options) {
if (options === void 0) {
options = defaultOptions;
}
var state = {
placement: 'bottom',
orderedModifiers: [],
options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),
modifiersData: {},
elements: {
reference: reference,
popper: popper
},
attributes: {},
styles: {}
};
var effectCleanupFns = [];
var isDestroyed = false;
var instance = {
state: state,
setOptions: function setOptions(setOptionsAction) {
var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;
cleanupModifierEffects();
state.options = Object.assign({}, defaultOptions, state.options, options);
state.scrollParents = {
reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],
popper: listScrollParents(popper)
}; // Orders the modifiers based on their dependencies and `phase`
// properties
var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers
state.orderedModifiers = orderedModifiers.filter(function (m) {
return m.enabled;
});
runModifierEffects();
return instance.update();
},
// Sync update – it will always be executed, even if not necessary. This
// is useful for low frequency updates where sync behavior simplifies the
// logic.
// For high frequency updates (e.g. `resize` and `scroll` events), always
// prefer the async Popper#update method
forceUpdate: function forceUpdate() {
if (isDestroyed) {
return;
}
var _state$elements = state.elements,
reference = _state$elements.reference,
popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements
// anymore
if (!areValidElements(reference, popper)) {
return;
} // Store the reference and popper rects to be read by modifiers
state.rects = {
reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),
popper: getLayoutRect(popper)
}; // Modifiers have the ability to reset the current update cycle. The
// most common use case for this is the `flip` modifier changing the
// placement, which then needs to re-run all the modifiers, because the
// logic was previously ran for the previous placement and is therefore
// stale/incorrect
state.reset = false;
state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier
// is filled with the initial data specified by the modifier. This means
// it doesn't persist and is fresh on each update.
// To ensure persistent data, use `${name}#persistent`
state.orderedModifiers.forEach(function (modifier) {
return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
});
for (var index = 0; index < state.orderedModifiers.length; index++) {
if (state.reset === true) {
state.reset = false;
index = -1;
continue;
}
var _state$orderedModifie = state.orderedModifiers[index],
fn = _state$orderedModifie.fn,
_state$orderedModifie2 = _state$orderedModifie.options,
_options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,
name = _state$orderedModifie.name;
if (typeof fn === 'function') {
state = fn({
state: state,
options: _options,
name: name,
instance: instance
}) || state;
}
}
},
// Async and optimistically optimized update – it will not be executed if
// not necessary (debounced to run at most once-per-tick)
update: debounce(function () {
return new Promise(function (resolve) {
instance.forceUpdate();
resolve(state);
});
}),
destroy: function destroy() {
cleanupModifierEffects();
isDestroyed = true;
}
};
if (!areValidElements(reference, popper)) {
return instance;
}
instance.setOptions(options).then(function (state) {
if (!isDestroyed && options.onFirstUpdate) {
options.onFirstUpdate(state);
}
}); // Modifiers have the ability to execute arbitrary code before the first
// update cycle runs. They will be executed in the same order as the update
// cycle. This is useful when a modifier adds some persistent data that
// other modifiers need to use, but the modifier is run after the dependent
// one.
function runModifierEffects() {
state.orderedModifiers.forEach(function (_ref) {
var name = _ref.name,
_ref$options = _ref.options,
options = _ref$options === void 0 ? {} : _ref$options,
effect = _ref.effect;
if (typeof effect === 'function') {
var cleanupFn = effect({
state: state,
name: name,
instance: instance,
options: options
});
var noopFn = function noopFn() {};
effectCleanupFns.push(cleanupFn || noopFn);
}
});
}
function cleanupModifierEffects() {
effectCleanupFns.forEach(function (fn) {
return fn();
});
effectCleanupFns = [];
}
return instance;
};
}
var defaultModifiers = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1, offset$1, flip$1, preventOverflow$1, arrow$1, hide$1];
var createPopper = /*#__PURE__*/popperGenerator({
defaultModifiers: defaultModifiers
}); // eslint-disable-next-line import/no-unused-modules
function getContainer$1(container) {
return typeof container === 'function' ? container() : container;
}
/**
* Portals provide a first-class way to render children into a DOM node
* that exists outside the DOM hierarchy of the parent component.
*
* Demos:
*
* - [Portal](https://v6.mui.com/material-ui/react-portal/)
*
* API:
*
* - [Portal API](https://v6.mui.com/material-ui/api/portal/)
*/
const Portal = /*#__PURE__*/reactExports.forwardRef(function Portal(props, forwardedRef) {
const {
children,
container,
disablePortal = false
} = props;
const [mountNode, setMountNode] = reactExports.useState(null);
const handleRef = useForkRef(/*#__PURE__*/reactExports.isValidElement(children) ? getReactElementRef(children) : null, forwardedRef);
useEnhancedEffect(() => {
if (!disablePortal) {
setMountNode(getContainer$1(container) || document.body);
}
}, [container, disablePortal]);
useEnhancedEffect(() => {
if (mountNode && !disablePortal) {
setRef(forwardedRef, mountNode);
return () => {
setRef(forwardedRef, null);
};
}
return undefined;
}, [forwardedRef, mountNode, disablePortal]);
if (disablePortal) {
if (/*#__PURE__*/reactExports.isValidElement(children)) {
const newProps = {
ref: handleRef
};
return /*#__PURE__*/reactExports.cloneElement(children, newProps);
}
return children;
}
return mountNode ? /*#__PURE__*/reactDomExports.createPortal(children, mountNode) : mountNode;
});
function getPopperUtilityClass(slot) {
return generateUtilityClass('MuiPopper', slot);
}
generateUtilityClasses('MuiPopper', ['root']);
function flipPlacement(placement, direction) {
if (direction === 'ltr') {
return placement;
}
switch (placement) {
case 'bottom-end':
return 'bottom-start';
case 'bottom-start':
return 'bottom-end';
case 'top-end':
return 'top-start';
case 'top-start':
return 'top-end';
default:
return placement;
}
}
function resolveAnchorEl$1(anchorEl) {
return typeof anchorEl === 'function' ? anchorEl() : anchorEl;
}
function isHTMLElement(element) {
return element.nodeType !== undefined;
}
const useUtilityClasses$k = ownerState => {
const {
classes
} = ownerState;
const slots = {
root: ['root']
};
return composeClasses(slots, getPopperUtilityClass, classes);
};
const defaultPopperOptions = {};
const PopperTooltip = /*#__PURE__*/reactExports.forwardRef(function PopperTooltip(props, forwardedRef) {
const {
anchorEl,
children,
direction,
disablePortal,
modifiers,
open,
placement: initialPlacement,
popperOptions,
popperRef: popperRefProp,
slotProps = {},
slots = {},
TransitionProps,
// @ts-ignore internal logic
ownerState: ownerStateProp,
// prevent from spreading to DOM, it can come from the parent component e.g. Select.
...other
} = props;
const tooltipRef = reactExports.useRef(null);
const ownRef = useForkRef(tooltipRef, forwardedRef);
const popperRef = reactExports.useRef(null);
const handlePopperRef = useForkRef(popperRef, popperRefProp);
const handlePopperRefRef = reactExports.useRef(handlePopperRef);
useEnhancedEffect(() => {
handlePopperRefRef.current = handlePopperRef;
}, [handlePopperRef]);
reactExports.useImperativeHandle(popperRefProp, () => popperRef.current, []);
const rtlPlacement = flipPlacement(initialPlacement, direction);
/**
* placement initialized from prop but can change during lifetime if modifiers.flip.
* modifiers.flip is essentially a flip for controlled/uncontrolled behavior
*/
const [placement, setPlacement] = reactExports.useState(rtlPlacement);
const [resolvedAnchorElement, setResolvedAnchorElement] = reactExports.useState(resolveAnchorEl$1(anchorEl));
reactExports.useEffect(() => {
if (popperRef.current) {
popperRef.current.forceUpdate();
}
});
reactExports.useEffect(() => {
if (anchorEl) {
setResolvedAnchorElement(resolveAnchorEl$1(anchorEl));
}
}, [anchorEl]);
useEnhancedEffect(() => {
if (!resolvedAnchorElement || !open) {
return undefined;
}
const handlePopperUpdate = data => {
setPlacement(data.placement);
};
let popperModifiers = [{
name: 'preventOverflow',
options: {
altBoundary: disablePortal
}
}, {
name: 'flip',
options: {
altBoundary: disablePortal
}
}, {
name: 'onUpdate',
enabled: true,
phase: 'afterWrite',
fn: ({
state
}) => {
handlePopperUpdate(state);
}
}];
if (modifiers != null) {
popperModifiers = popperModifiers.concat(modifiers);
}
if (popperOptions && popperOptions.modifiers != null) {
popperModifiers = popperModifiers.concat(popperOptions.modifiers);
}
const popper = createPopper(resolvedAnchorElement, tooltipRef.current, {
placement: rtlPlacement,
...popperOptions,
modifiers: popperModifiers
});
handlePopperRefRef.current(popper);
return () => {
popper.destroy();
handlePopperRefRef.current(null);
};
}, [resolvedAnchorElement, disablePortal, modifiers, open, popperOptions, rtlPlacement]);
const childProps = {
placement: placement
};
if (TransitionProps !== null) {
childProps.TransitionProps = TransitionProps;
}
const classes = useUtilityClasses$k(props);
const Root = slots.root ?? 'div';
const rootProps = useSlotProps({
elementType: Root,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
additionalProps: {
role: 'tooltip',
ref: ownRef
},
ownerState: props,
className: classes.root
});
return /*#__PURE__*/jsxRuntimeExports.jsx(Root, {
...rootProps,
children: typeof children === 'function' ? children(childProps) : children
});
});
/**
* @ignore - internal component.
*/
const Popper$1 = /*#__PURE__*/reactExports.forwardRef(function Popper(props, forwardedRef) {
const {
anchorEl,
children,
container: containerProp,
direction = 'ltr',
disablePortal = false,
keepMounted = false,
modifiers,
open,
placement = 'bottom',
popperOptions = defaultPopperOptions,
popperRef,
style,
transition = false,
slotProps = {},
slots = {},
...other
} = props;
const [exited, setExited] = reactExports.useState(true);
const handleEnter = () => {
setExited(false);
};
const handleExited = () => {
setExited(true);
};
if (!keepMounted && !open && (!transition || exited)) {
return null;
}
// If the container prop is provided, use that
// If the anchorEl prop is provided, use its parent body element as the container
// If neither are provided let the Modal take care of choosing the container
let container;
if (containerProp) {
container = containerProp;
} else if (anchorEl) {
const resolvedAnchorEl = resolveAnchorEl$1(anchorEl);
container = resolvedAnchorEl && isHTMLElement(resolvedAnchorEl) ? ownerDocument(resolvedAnchorEl).body : ownerDocument(null).body;
}
const display = !open && keepMounted && (!transition || exited) ? 'none' : undefined;
const transitionProps = transition ? {
in: open,
onEnter: handleEnter,
onExited: handleExited
} : undefined;
return /*#__PURE__*/jsxRuntimeExports.jsx(Portal, {
disablePortal: disablePortal,
container: container,
children: /*#__PURE__*/jsxRuntimeExports.jsx(PopperTooltip, {
anchorEl: anchorEl,
direction: direction,
disablePortal: disablePortal,
modifiers: modifiers,
ref: forwardedRef,
open: transition ? !exited : open,
placement: placement,
popperOptions: popperOptions,
popperRef: popperRef,
slotProps: slotProps,
slots: slots,
...other,
style: {
// Prevents scroll issue, waiting for Popper.js to add this style once initiated.
position: 'fixed',
// Fix Popper.js display issue
top: 0,
left: 0,
display,
...style
},
TransitionProps: transitionProps,
children: children
})
});
});
const PopperRoot = styled(Popper$1, {
name: 'MuiPopper',
slot: 'Root',
overridesResolver: (props, styles) => styles.root
})({});
/**
*
* Demos:
*
* - [Autocomplete](https://v6.mui.com/material-ui/react-autocomplete/)
* - [Menu](https://v6.mui.com/material-ui/react-menu/)
* - [Popper](https://v6.mui.com/material-ui/react-popper/)
*
* API:
*
* - [Popper API](https://v6.mui.com/material-ui/api/popper/)
*/
const Popper = /*#__PURE__*/reactExports.forwardRef(function Popper(inProps, ref) {
const isRtl = useRtl();
const props = useDefaultProps({
props: inProps,
name: 'MuiPopper'
});
const {
anchorEl,
component,
components,
componentsProps,
container,
disablePortal,
keepMounted,
modifiers,
open,
placement,
popperOptions,
popperRef,
transition,
slots,
slotProps,
...other
} = props;
const RootComponent = slots?.root ?? components?.Root;
const otherProps = {
anchorEl,
container,
disablePortal,
keepMounted,
modifiers,
open,
placement,
popperOptions,
popperRef,
transition,
...other
};
return /*#__PURE__*/jsxRuntimeExports.jsx(PopperRoot, {
as: component,
direction: isRtl ? 'rtl' : 'ltr',
slots: {
root: RootComponent
},
slotProps: slotProps ?? componentsProps,
...otherProps,
ref: ref
});
});
function getStyleValue(value) {
return parseInt(value, 10) || 0;
}
const styles$2 = {
shadow: {
// Visibility needed to hide the extra text area on iPads
visibility: 'hidden',
// Remove from the content flow
position: 'absolute',
// Ignore the scrollbar width
overflow: 'hidden',
height: 0,
top: 0,
left: 0,
// Create a new layer, increase the isolation of the computed values
transform: 'translateZ(0)'
}
};
function isObjectEmpty(object) {
// eslint-disable-next-line
for (const _ in object) {
return false;
}
return true;
}
function isEmpty$1(obj) {
return isObjectEmpty(obj) || obj.outerHeightStyle === 0 && !obj.overflowing;
}
/**
*
* Demos:
*
* - [Textarea Autosize](https://v6.mui.com/material-ui/react-textarea-autosize/)
*
* API:
*
* - [TextareaAutosize API](https://v6.mui.com/material-ui/api/textarea-autosize/)
*/
const TextareaAutosize = /*#__PURE__*/reactExports.forwardRef(function TextareaAutosize(props, forwardedRef) {
const {
onChange,
maxRows,
minRows = 1,
style,
value,
...other
} = props;
const {
current: isControlled
} = reactExports.useRef(value != null);
const textareaRef = reactExports.useRef(null);
const handleRef = useForkRef(forwardedRef, textareaRef);
const heightRef = reactExports.useRef(null);
const hiddenTextareaRef = reactExports.useRef(null);
const calculateTextareaStyles = reactExports.useCallback(() => {
const textarea = textareaRef.current;
const hiddenTextarea = hiddenTextareaRef.current;
if (!textarea || !hiddenTextarea) {
return undefined;
}
const containerWindow = ownerWindow(textarea);
const computedStyle = containerWindow.getComputedStyle(textarea);
// If input's width is shrunk and it's not visible, don't sync height.
if (computedStyle.width === '0px') {
return {
outerHeightStyle: 0,
overflowing: false
};
}
hiddenTextarea.style.width = computedStyle.width;
hiddenTextarea.value = textarea.value || props.placeholder || 'x';
if (hiddenTextarea.value.slice(-1) === '\n') {
// Certain fonts which overflow the line height will cause the textarea
// to report a different scrollHeight depending on whether the last line
// is empty. Make it non-empty to avoid this issue.
hiddenTextarea.value += ' ';
}
const boxSizing = computedStyle.boxSizing;
const padding = getStyleValue(computedStyle.paddingBottom) + getStyleValue(computedStyle.paddingTop);
const border = getStyleValue(computedStyle.borderBottomWidth) + getStyleValue(computedStyle.borderTopWidth);
// The height of the inner content
const innerHeight = hiddenTextarea.scrollHeight;
// Measure height of a textarea with a single row
hiddenTextarea.value = 'x';
const singleRowHeight = hiddenTextarea.scrollHeight;
// The height of the outer content
let outerHeight = innerHeight;
if (minRows) {
outerHeight = Math.max(Number(minRows) * singleRowHeight, outerHeight);
}
if (maxRows) {
outerHeight = Math.min(Number(maxRows) * singleRowHeight, outerHeight);
}
outerHeight = Math.max(outerHeight, singleRowHeight);
// Take the box sizing into account for applying this value as a style.
const outerHeightStyle = outerHeight + (boxSizing === 'border-box' ? padding + border : 0);
const overflowing = Math.abs(outerHeight - innerHeight) <= 1;
return {
outerHeightStyle,
overflowing
};
}, [maxRows, minRows, props.placeholder]);
const didHeightChange = useEventCallback(() => {
const textarea = textareaRef.current;
const textareaStyles = calculateTextareaStyles();
if (!textarea || !textareaStyles || isEmpty$1(textareaStyles)) {
return false;
}
const outerHeightStyle = textareaStyles.outerHeightStyle;
return heightRef.current != null && heightRef.current !== outerHeightStyle;
});
const syncHeight = reactExports.useCallback(() => {
const textarea = textareaRef.current;
const textareaStyles = calculateTextareaStyles();
if (!textarea || !textareaStyles || isEmpty$1(textareaStyles)) {
return;
}
const outerHeightStyle = textareaStyles.outerHeightStyle;
if (heightRef.current !== outerHeightStyle) {
heightRef.current = outerHeightStyle;
textarea.style.height = `${outerHeightStyle}px`;
}
textarea.style.overflow = textareaStyles.overflowing ? 'hidden' : '';
}, [calculateTextareaStyles]);
const frameRef = reactExports.useRef(-1);
useEnhancedEffect(() => {
const debouncedHandleResize = debounce$1(syncHeight);
const textarea = textareaRef?.current;
if (!textarea) {
return undefined;
}
const containerWindow = ownerWindow(textarea);
containerWindow.addEventListener('resize', debouncedHandleResize);
let resizeObserver;
if (typeof ResizeObserver !== 'undefined') {
resizeObserver = new ResizeObserver(() => {
if (didHeightChange()) {
// avoid "ResizeObserver loop completed with undelivered notifications" error
// by temporarily unobserving the textarea element while manipulating the height
// and reobserving one frame later
resizeObserver.unobserve(textarea);
cancelAnimationFrame(frameRef.current);
syncHeight();
frameRef.current = requestAnimationFrame(() => {
resizeObserver.observe(textarea);
});
}
});
resizeObserver.observe(textarea);
}
return () => {
debouncedHandleResize.clear();
cancelAnimationFrame(frameRef.current);
containerWindow.removeEventListener('resize', debouncedHandleResize);
if (resizeObserver) {
resizeObserver.disconnect();
}
};
}, [calculateTextareaStyles, syncHeight, didHeightChange]);
useEnhancedEffect(() => {
syncHeight();
});
const handleChange = event => {
if (!isControlled) {
syncHeight();
}
if (onChange) {
onChange(event);
}
};
return /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports.Fragment, {
children: [/*#__PURE__*/jsxRuntimeExports.jsx("textarea", {
value: value,
onChange: handleChange,
ref: handleRef
// Apply the rows prop to get a "correct" first SSR paint
,
rows: minRows,
style: style,
...other
}), /*#__PURE__*/jsxRuntimeExports.jsx("textarea", {
"aria-hidden": true,
className: props.className,
readOnly: true,
ref: hiddenTextareaRef,
tabIndex: -1,
style: {
...styles$2.shadow,
...style,
paddingTop: 0,
paddingBottom: 0
}
})]
});
});
/**
* Determines if a given element is a DOM element name (i.e. not a React component).
*/
function isHostComponent(element) {
return typeof element === 'string';
}
function formControlState({
props,
states,
muiFormControl
}) {
return states.reduce((acc, state) => {
acc[state] = props[state];
if (muiFormControl) {
if (typeof props[state] === 'undefined') {
acc[state] = muiFormControl[state];
}
}
return acc;
}, {});
}
/**
* @ignore - internal component.
*/
const FormControlContext = /*#__PURE__*/reactExports.createContext(undefined);
function useFormControl() {
return reactExports.useContext(FormControlContext);
}
// Supports determination of isControlled().
// Controlled input accepts its current value as a prop.
//
// @see https://facebook.github.io/react/docs/forms.html#controlled-components
// @param value
// @returns {boolean} true if string (including '') or number (including zero)
function hasValue(value) {
return value != null && !(Array.isArray(value) && value.length === 0);
}
// Determine if field is empty or filled.
// Response determines if label is presented above field or as placeholder.
//
// @param obj
// @param SSR
// @returns {boolean} False when not present or empty string.
// True when any number or string with length.
function isFilled(obj, SSR = false) {
return obj && (hasValue(obj.value) && obj.value !== '' || SSR && hasValue(obj.defaultValue) && obj.defaultValue !== '');
}
function getInputBaseUtilityClass(slot) {
return generateUtilityClass('MuiInputBase', slot);
}
const inputBaseClasses = generateUtilityClasses('MuiInputBase', ['root', 'formControl', 'focused', 'disabled', 'adornedStart', 'adornedEnd', 'error', 'sizeSmall', 'multiline', 'colorSecondary', 'fullWidth', 'hiddenLabel', 'readOnly', 'input', 'inputSizeSmall', 'inputMultiline', 'inputTypeSearch', 'inputAdornedStart', 'inputAdornedEnd', 'inputHiddenLabel']);
var _InputGlobalStyles;
const rootOverridesResolver = (props, styles) => {
const {
ownerState
} = props;
return [styles.root, ownerState.formControl && styles.formControl, ownerState.startAdornment && styles.adornedStart, ownerState.endAdornment && styles.adornedEnd, ownerState.error && styles.error, ownerState.size === 'small' && styles.sizeSmall, ownerState.multiline && styles.multiline, ownerState.color && styles[`color${capitalize(ownerState.color)}`], ownerState.fullWidth && styles.fullWidth, ownerState.hiddenLabel && styles.hiddenLabel];
};
const inputOverridesResolver = (props, styles) => {
const {
ownerState
} = props;
return [styles.input, ownerState.size === 'small' && styles.inputSizeSmall, ownerState.multiline && styles.inputMultiline, ownerState.type === 'search' && styles.inputTypeSearch, ownerState.startAdornment && styles.inputAdornedStart, ownerState.endAdornment && styles.inputAdornedEnd, ownerState.hiddenLabel && styles.inputHiddenLabel];
};
const useUtilityClasses$j = ownerState => {
const {
classes,
color,
disabled,
error,
endAdornment,
focused,
formControl,
fullWidth,
hiddenLabel,
multiline,
readOnly,
size,
startAdornment,
type
} = ownerState;
const slots = {
root: ['root', `color${capitalize(color)}`, disabled && 'disabled', error && 'error', fullWidth && 'fullWidth', focused && 'focused', formControl && 'formControl', size && size !== 'medium' && `size${capitalize(size)}`, multiline && 'multiline', startAdornment && 'adornedStart', endAdornment && 'adornedEnd', hiddenLabel && 'hiddenLabel', readOnly && 'readOnly'],
input: ['input', disabled && 'disabled', type === 'search' && 'inputTypeSearch', multiline && 'inputMultiline', size === 'small' && 'inputSizeSmall', hiddenLabel && 'inputHiddenLabel', startAdornment && 'inputAdornedStart', endAdornment && 'inputAdornedEnd', readOnly && 'readOnly']
};
return composeClasses(slots, getInputBaseUtilityClass, classes);
};
const InputBaseRoot = styled('div', {
name: 'MuiInputBase',
slot: 'Root',
overridesResolver: rootOverridesResolver
})(memoTheme(({
theme
}) => ({
...theme.typography.body1,
color: (theme.vars || theme).palette.text.primary,
lineHeight: '1.4375em',
// 23px
boxSizing: 'border-box',
// Prevent padding issue with fullWidth.
position: 'relative',
cursor: 'text',
display: 'inline-flex',
alignItems: 'center',
[`&.${inputBaseClasses.disabled}`]: {
color: (theme.vars || theme).palette.text.disabled,
cursor: 'default'
},
variants: [{
props: ({
ownerState
}) => ownerState.multiline,
style: {
padding: '4px 0 5px'
}
}, {
props: ({
ownerState,
size
}) => ownerState.multiline && size === 'small',
style: {
paddingTop: 1
}
}, {
props: ({
ownerState
}) => ownerState.fullWidth,
style: {
width: '100%'
}
}]
})));
const InputBaseInput = styled('input', {
name: 'MuiInputBase',
slot: 'Input',
overridesResolver: inputOverridesResolver
})(memoTheme(({
theme
}) => {
const light = theme.palette.mode === 'light';
const placeholder = {
color: 'currentColor',
...(theme.vars ? {
opacity: theme.vars.opacity.inputPlaceholder
} : {
opacity: light ? 0.42 : 0.5
}),
transition: theme.transitions.create('opacity', {
duration: theme.transitions.duration.shorter
})
};
const placeholderHidden = {
opacity: '0 !important'
};
const placeholderVisible = theme.vars ? {
opacity: theme.vars.opacity.inputPlaceholder
} : {
opacity: light ? 0.42 : 0.5
};
return {
font: 'inherit',
letterSpacing: 'inherit',
color: 'currentColor',
padding: '4px 0 5px',
border: 0,
boxSizing: 'content-box',
background: 'none',
height: '1.4375em',
// Reset 23pxthe native input line-height
margin: 0,
// Reset for Safari
WebkitTapHighlightColor: 'transparent',
display: 'block',
// Make the flex item shrink with Firefox
minWidth: 0,
width: '100%',
'&::-webkit-input-placeholder': placeholder,
'&::-moz-placeholder': placeholder,
// Firefox 19+
'&::-ms-input-placeholder': placeholder,
// Edge
'&:focus': {
outline: 0
},
// Reset Firefox invalid required input style
'&:invalid': {
boxShadow: 'none'
},
'&::-webkit-search-decoration': {
// Remove the padding when type=search.
WebkitAppearance: 'none'
},
// Show and hide the placeholder logic
[`label[data-shrink=false] + .${inputBaseClasses.formControl} &`]: {
'&::-webkit-input-placeholder': placeholderHidden,
'&::-moz-placeholder': placeholderHidden,
// Firefox 19+
'&::-ms-input-placeholder': placeholderHidden,
// Edge
'&:focus::-webkit-input-placeholder': placeholderVisible,
'&:focus::-moz-placeholder': placeholderVisible,
// Firefox 19+
'&:focus::-ms-input-placeholder': placeholderVisible // Edge
},
[`&.${inputBaseClasses.disabled}`]: {
opacity: 1,
// Reset iOS opacity
WebkitTextFillColor: (theme.vars || theme).palette.text.disabled // Fix opacity Safari bug
},
variants: [{
props: ({
ownerState
}) => !ownerState.disableInjectingGlobalStyles,
style: {
animationName: 'mui-auto-fill-cancel',
animationDuration: '10ms',
'&:-webkit-autofill': {
animationDuration: '5000s',
animationName: 'mui-auto-fill'
}
}
}, {
props: {
size: 'small'
},
style: {
paddingTop: 1
}
}, {
props: ({
ownerState
}) => ownerState.multiline,
style: {
height: 'auto',
resize: 'none',
padding: 0,
paddingTop: 0
}
}, {
props: {
type: 'search'
},
style: {
MozAppearance: 'textfield' // Improve type search style.
}
}]
};
}));
const InputGlobalStyles = globalCss({
'@keyframes mui-auto-fill': {
from: {
display: 'block'
}
},
'@keyframes mui-auto-fill-cancel': {
from: {
display: 'block'
}
}
});
/**
* `InputBase` contains as few styles as possible.
* It aims to be a simple building block for creating an input.
* It contains a load of style reset and some state logic.
*/
const InputBase = /*#__PURE__*/reactExports.forwardRef(function InputBase(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiInputBase'
});
const {
'aria-describedby': ariaDescribedby,
autoComplete,
autoFocus,
className,
color,
components = {},
componentsProps = {},
defaultValue,
disabled,
disableInjectingGlobalStyles,
endAdornment,
error,
fullWidth = false,
id,
inputComponent = 'input',
inputProps: inputPropsProp = {},
inputRef: inputRefProp,
margin,
maxRows,
minRows,
multiline = false,
name,
onBlur,
onChange,
onClick,
onFocus,
onKeyDown,
onKeyUp,
placeholder,
readOnly,
renderSuffix,
rows,
size,
slotProps = {},
slots = {},
startAdornment,
type = 'text',
value: valueProp,
...other
} = props;
const value = inputPropsProp.value != null ? inputPropsProp.value : valueProp;
const {
current: isControlled
} = reactExports.useRef(value != null);
const inputRef = reactExports.useRef();
const handleInputRefWarning = reactExports.useCallback(instance => {
}, []);
const handleInputRef = useForkRef(inputRef, inputRefProp, inputPropsProp.ref, handleInputRefWarning);
const [focused, setFocused] = reactExports.useState(false);
const muiFormControl = useFormControl();
const fcs = formControlState({
props,
muiFormControl,
states: ['color', 'disabled', 'error', 'hiddenLabel', 'size', 'required', 'filled']
});
fcs.focused = muiFormControl ? muiFormControl.focused : focused;
// The blur won't fire when the disabled state is set on a focused input.
// We need to book keep the focused state manually.
reactExports.useEffect(() => {
if (!muiFormControl && disabled && focused) {
setFocused(false);
if (onBlur) {
onBlur();
}
}
}, [muiFormControl, disabled, focused, onBlur]);
const onFilled = muiFormControl && muiFormControl.onFilled;
const onEmpty = muiFormControl && muiFormControl.onEmpty;
const checkDirty = reactExports.useCallback(obj => {
if (isFilled(obj)) {
if (onFilled) {
onFilled();
}
} else if (onEmpty) {
onEmpty();
}
}, [onFilled, onEmpty]);
useEnhancedEffect(() => {
if (isControlled) {
checkDirty({
value
});
}
}, [value, checkDirty, isControlled]);
const handleFocus = event => {
if (onFocus) {
onFocus(event);
}
if (inputPropsProp.onFocus) {
inputPropsProp.onFocus(event);
}
if (muiFormControl && muiFormControl.onFocus) {
muiFormControl.onFocus(event);
} else {
setFocused(true);
}
};
const handleBlur = event => {
if (onBlur) {
onBlur(event);
}
if (inputPropsProp.onBlur) {
inputPropsProp.onBlur(event);
}
if (muiFormControl && muiFormControl.onBlur) {
muiFormControl.onBlur(event);
} else {
setFocused(false);
}
};
const handleChange = (event, ...args) => {
if (!isControlled) {
const element = event.target || inputRef.current;
if (element == null) {
throw new Error(formatMuiErrorMessage(1));
}
checkDirty({
value: element.value
});
}
if (inputPropsProp.onChange) {
inputPropsProp.onChange(event, ...args);
}
// Perform in the willUpdate
if (onChange) {
onChange(event, ...args);
}
};
// Check the input state on mount, in case it was filled by the user
// or auto filled by the browser before the hydration (for SSR).
reactExports.useEffect(() => {
checkDirty(inputRef.current);
// TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleClick = event => {
if (inputRef.current && event.currentTarget === event.target) {
inputRef.current.focus();
}
if (onClick) {
onClick(event);
}
};
let InputComponent = inputComponent;
let inputProps = inputPropsProp;
if (multiline && InputComponent === 'input') {
if (rows) {
inputProps = {
type: undefined,
minRows: rows,
maxRows: rows,
...inputProps
};
} else {
inputProps = {
type: undefined,
maxRows,
minRows,
...inputProps
};
}
InputComponent = TextareaAutosize;
}
const handleAutoFill = event => {
// Provide a fake value as Chrome might not let you access it for security reasons.
checkDirty(event.animationName === 'mui-auto-fill-cancel' ? inputRef.current : {
value: 'x'
});
};
reactExports.useEffect(() => {
if (muiFormControl) {
muiFormControl.setAdornedStart(Boolean(startAdornment));
}
}, [muiFormControl, startAdornment]);
const ownerState = {
...props,
color: fcs.color || 'primary',
disabled: fcs.disabled,
endAdornment,
error: fcs.error,
focused: fcs.focused,
formControl: muiFormControl,
fullWidth,
hiddenLabel: fcs.hiddenLabel,
multiline,
size: fcs.size,
startAdornment,
type
};
const classes = useUtilityClasses$j(ownerState);
const Root = slots.root || components.Root || InputBaseRoot;
const rootProps = slotProps.root || componentsProps.root || {};
const Input = slots.input || components.Input || InputBaseInput;
inputProps = {
...inputProps,
...(slotProps.input ?? componentsProps.input)
};
return /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports.Fragment, {
children: [!disableInjectingGlobalStyles && typeof InputGlobalStyles === 'function' && (// For Emotion/Styled-components, InputGlobalStyles will be a function
// For Pigment CSS, this has no effect because the InputGlobalStyles will be null.
_InputGlobalStyles || (_InputGlobalStyles = /*#__PURE__*/jsxRuntimeExports.jsx(InputGlobalStyles, {}))), /*#__PURE__*/jsxRuntimeExports.jsxs(Root, {
...rootProps,
ref: ref,
onClick: handleClick,
...other,
...(!isHostComponent(Root) && {
ownerState: {
...ownerState,
...rootProps.ownerState
}
}),
className: clsx(classes.root, rootProps.className, className, readOnly && 'MuiInputBase-readOnly'),
children: [startAdornment, /*#__PURE__*/jsxRuntimeExports.jsx(FormControlContext.Provider, {
value: null,
children: /*#__PURE__*/jsxRuntimeExports.jsx(Input, {
"aria-invalid": fcs.error,
"aria-describedby": ariaDescribedby,
autoComplete: autoComplete,
autoFocus: autoFocus,
defaultValue: defaultValue,
disabled: fcs.disabled,
id: id,
onAnimationStart: handleAutoFill,
name: name,
placeholder: placeholder,
readOnly: readOnly,
required: fcs.required,
rows: rows,
value: value,
onKeyDown: onKeyDown,
onKeyUp: onKeyUp,
type: type,
...inputProps,
...(!isHostComponent(Input) && {
as: InputComponent,
ownerState: {
...ownerState,
...inputProps.ownerState
}
}),
ref: handleInputRef,
className: clsx(classes.input, inputProps.className, readOnly && 'MuiInputBase-readOnly'),
onBlur: handleBlur,
onChange: handleChange,
onFocus: handleFocus
})
}), endAdornment, renderSuffix ? renderSuffix({
...fcs,
startAdornment
}) : null]
})]
});
});
function getOutlinedInputUtilityClass(slot) {
return generateUtilityClass('MuiOutlinedInput', slot);
}
const outlinedInputClasses = {
...inputBaseClasses,
...generateUtilityClasses('MuiOutlinedInput', ['root', 'notchedOutline', 'input'])
};
const styles$1 = {
entering: {
opacity: 1
},
entered: {
opacity: 1
}
};
/**
* The Fade transition is used by the [Modal](/material-ui/react-modal/) component.
* It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.
*/
const Fade = /*#__PURE__*/reactExports.forwardRef(function Fade(props, ref) {
const theme = useTheme$1();
const defaultTimeout = {
enter: theme.transitions.duration.enteringScreen,
exit: theme.transitions.duration.leavingScreen
};
const {
addEndListener,
appear = true,
children,
easing,
in: inProp,
onEnter,
onEntered,
onEntering,
onExit,
onExited,
onExiting,
style,
timeout = defaultTimeout,
// eslint-disable-next-line react/prop-types
TransitionComponent = Transition,
...other
} = props;
const nodeRef = reactExports.useRef(null);
const handleRef = useForkRef(nodeRef, getReactElementRef(children), ref);
const normalizedTransitionCallback = callback => maybeIsAppearing => {
if (callback) {
const node = nodeRef.current;
// onEnterXxx and onExitXxx callbacks have a different arguments.length value.
if (maybeIsAppearing === undefined) {
callback(node);
} else {
callback(node, maybeIsAppearing);
}
}
};
const handleEntering = normalizedTransitionCallback(onEntering);
const handleEnter = normalizedTransitionCallback((node, isAppearing) => {
reflow(node); // So the animation always start from the start.
const transitionProps = getTransitionProps({
style,
timeout,
easing
}, {
mode: 'enter'
});
node.style.webkitTransition = theme.transitions.create('opacity', transitionProps);
node.style.transition = theme.transitions.create('opacity', transitionProps);
if (onEnter) {
onEnter(node, isAppearing);
}
});
const handleEntered = normalizedTransitionCallback(onEntered);
const handleExiting = normalizedTransitionCallback(onExiting);
const handleExit = normalizedTransitionCallback(node => {
const transitionProps = getTransitionProps({
style,
timeout,
easing
}, {
mode: 'exit'
});
node.style.webkitTransition = theme.transitions.create('opacity', transitionProps);
node.style.transition = theme.transitions.create('opacity', transitionProps);
if (onExit) {
onExit(node);
}
});
const handleExited = normalizedTransitionCallback(onExited);
const handleAddEndListener = next => {
if (addEndListener) {
// Old call signature before `react-transition-group` implemented `nodeRef`
addEndListener(nodeRef.current, next);
}
};
return /*#__PURE__*/jsxRuntimeExports.jsx(TransitionComponent, {
appear: appear,
in: inProp,
nodeRef: nodeRef ,
onEnter: handleEnter,
onEntered: handleEntered,
onEntering: handleEntering,
onExit: handleExit,
onExited: handleExited,
onExiting: handleExiting,
addEndListener: handleAddEndListener,
timeout: timeout,
...other,
children: (state, {
ownerState,
...restChildProps
}) => {
return /*#__PURE__*/reactExports.cloneElement(children, {
style: {
opacity: 0,
visibility: state === 'exited' && !inProp ? 'hidden' : undefined,
...styles$1[state],
...style,
...children.props.style
},
ref: handleRef,
...restChildProps
});
}
});
});
function getBackdropUtilityClass(slot) {
return generateUtilityClass('MuiBackdrop', slot);
}
generateUtilityClasses('MuiBackdrop', ['root', 'invisible']);
const useUtilityClasses$i = ownerState => {
const {
classes,
invisible
} = ownerState;
const slots = {
root: ['root', invisible && 'invisible']
};
return composeClasses(slots, getBackdropUtilityClass, classes);
};
const BackdropRoot = styled('div', {
name: 'MuiBackdrop',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, ownerState.invisible && styles.invisible];
}
})({
position: 'fixed',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
right: 0,
bottom: 0,
top: 0,
left: 0,
backgroundColor: 'rgba(0, 0, 0, 0.5)',
WebkitTapHighlightColor: 'transparent',
variants: [{
props: {
invisible: true
},
style: {
backgroundColor: 'transparent'
}
}]
});
const Backdrop = /*#__PURE__*/reactExports.forwardRef(function Backdrop(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiBackdrop'
});
const {
children,
className,
component = 'div',
invisible = false,
open,
components = {},
componentsProps = {},
slotProps = {},
slots = {},
TransitionComponent: TransitionComponentProp,
transitionDuration,
...other
} = props;
const ownerState = {
...props,
component,
invisible
};
const classes = useUtilityClasses$i(ownerState);
const backwardCompatibleSlots = {
transition: TransitionComponentProp,
root: components.Root,
...slots
};
const backwardCompatibleSlotProps = {
...componentsProps,
...slotProps
};
const externalForwardedProps = {
slots: backwardCompatibleSlots,
slotProps: backwardCompatibleSlotProps
};
const [RootSlot, rootProps] = useSlot('root', {
elementType: BackdropRoot,
externalForwardedProps,
className: clsx(classes.root, className),
ownerState
});
const [TransitionSlot, transitionProps] = useSlot('transition', {
elementType: Fade,
externalForwardedProps,
ownerState
});
return /*#__PURE__*/jsxRuntimeExports.jsx(TransitionSlot, {
in: open,
timeout: transitionDuration,
...other,
...transitionProps,
children: /*#__PURE__*/jsxRuntimeExports.jsx(RootSlot, {
"aria-hidden": true,
...rootProps,
classes: classes,
ref: ref,
children: children
})
});
});
/**
*
* Demos:
*
* - [Badge](https://mui.com/base-ui/react-badge/#hook)
*
* API:
*
* - [useBadge API](https://mui.com/base-ui/react-badge/hooks-api/#use-badge)
*/
function useBadge(parameters) {
const {
badgeContent: badgeContentProp,
invisible: invisibleProp = false,
max: maxProp = 99,
showZero = false
} = parameters;
const prevProps = usePreviousProps({
badgeContent: badgeContentProp,
max: maxProp
});
let invisible = invisibleProp;
if (invisibleProp === false && badgeContentProp === 0 && !showZero) {
invisible = true;
}
const {
badgeContent,
max = maxProp
} = invisible ? prevProps : parameters;
const displayValue = badgeContent && Number(badgeContent) > max ? `${max}+` : badgeContent;
return {
badgeContent,
invisible,
max,
displayValue
};
}
function getBadgeUtilityClass(slot) {
return generateUtilityClass('MuiBadge', slot);
}
const badgeClasses = generateUtilityClasses('MuiBadge', ['root', 'badge', 'dot', 'standard', 'anchorOriginTopRight', 'anchorOriginBottomRight', 'anchorOriginTopLeft', 'anchorOriginBottomLeft', 'invisible', 'colorError', 'colorInfo', 'colorPrimary', 'colorSecondary', 'colorSuccess', 'colorWarning', 'overlapRectangular', 'overlapCircular',
// TODO: v6 remove the overlap value from these class keys
'anchorOriginTopLeftCircular', 'anchorOriginTopLeftRectangular', 'anchorOriginTopRightCircular', 'anchorOriginTopRightRectangular', 'anchorOriginBottomLeftCircular', 'anchorOriginBottomLeftRectangular', 'anchorOriginBottomRightCircular', 'anchorOriginBottomRightRectangular']);
const RADIUS_STANDARD = 10;
const RADIUS_DOT = 4;
const useUtilityClasses$h = ownerState => {
const {
color,
anchorOrigin,
invisible,
overlap,
variant,
classes = {}
} = ownerState;
const slots = {
root: ['root'],
badge: ['badge', variant, invisible && 'invisible', `anchorOrigin${capitalize(anchorOrigin.vertical)}${capitalize(anchorOrigin.horizontal)}`, `anchorOrigin${capitalize(anchorOrigin.vertical)}${capitalize(anchorOrigin.horizontal)}${capitalize(overlap)}`, `overlap${capitalize(overlap)}`, color !== 'default' && `color${capitalize(color)}`]
};
return composeClasses(slots, getBadgeUtilityClass, classes);
};
const BadgeRoot = styled('span', {
name: 'MuiBadge',
slot: 'Root',
overridesResolver: (props, styles) => styles.root
})({
position: 'relative',
display: 'inline-flex',
// For correct alignment with the text.
verticalAlign: 'middle',
flexShrink: 0
});
const BadgeBadge = styled('span', {
name: 'MuiBadge',
slot: 'Badge',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.badge, styles[ownerState.variant], styles[`anchorOrigin${capitalize(ownerState.anchorOrigin.vertical)}${capitalize(ownerState.anchorOrigin.horizontal)}${capitalize(ownerState.overlap)}`], ownerState.color !== 'default' && styles[`color${capitalize(ownerState.color)}`], ownerState.invisible && styles.invisible];
}
})(memoTheme(({
theme
}) => ({
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
alignContent: 'center',
alignItems: 'center',
position: 'absolute',
boxSizing: 'border-box',
fontFamily: theme.typography.fontFamily,
fontWeight: theme.typography.fontWeightMedium,
fontSize: theme.typography.pxToRem(12),
minWidth: RADIUS_STANDARD * 2,
lineHeight: 1,
padding: '0 6px',
height: RADIUS_STANDARD * 2,
borderRadius: RADIUS_STANDARD,
zIndex: 1,
// Render the badge on top of potential ripples.
transition: theme.transitions.create('transform', {
easing: theme.transitions.easing.easeInOut,
duration: theme.transitions.duration.enteringScreen
}),
variants: [...Object.entries(theme.palette).filter(createSimplePaletteValueFilter(['contrastText'])).map(([color]) => ({
props: {
color
},
style: {
backgroundColor: (theme.vars || theme).palette[color].main,
color: (theme.vars || theme).palette[color].contrastText
}
})), {
props: {
variant: 'dot'
},
style: {
borderRadius: RADIUS_DOT,
height: RADIUS_DOT * 2,
minWidth: RADIUS_DOT * 2,
padding: 0
}
}, {
props: ({
ownerState
}) => ownerState.anchorOrigin.vertical === 'top' && ownerState.anchorOrigin.horizontal === 'right' && ownerState.overlap === 'rectangular',
style: {
top: 0,
right: 0,
transform: 'scale(1) translate(50%, -50%)',
transformOrigin: '100% 0%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(50%, -50%)'
}
}
}, {
props: ({
ownerState
}) => ownerState.anchorOrigin.vertical === 'bottom' && ownerState.anchorOrigin.horizontal === 'right' && ownerState.overlap === 'rectangular',
style: {
bottom: 0,
right: 0,
transform: 'scale(1) translate(50%, 50%)',
transformOrigin: '100% 100%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(50%, 50%)'
}
}
}, {
props: ({
ownerState
}) => ownerState.anchorOrigin.vertical === 'top' && ownerState.anchorOrigin.horizontal === 'left' && ownerState.overlap === 'rectangular',
style: {
top: 0,
left: 0,
transform: 'scale(1) translate(-50%, -50%)',
transformOrigin: '0% 0%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(-50%, -50%)'
}
}
}, {
props: ({
ownerState
}) => ownerState.anchorOrigin.vertical === 'bottom' && ownerState.anchorOrigin.horizontal === 'left' && ownerState.overlap === 'rectangular',
style: {
bottom: 0,
left: 0,
transform: 'scale(1) translate(-50%, 50%)',
transformOrigin: '0% 100%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(-50%, 50%)'
}
}
}, {
props: ({
ownerState
}) => ownerState.anchorOrigin.vertical === 'top' && ownerState.anchorOrigin.horizontal === 'right' && ownerState.overlap === 'circular',
style: {
top: '14%',
right: '14%',
transform: 'scale(1) translate(50%, -50%)',
transformOrigin: '100% 0%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(50%, -50%)'
}
}
}, {
props: ({
ownerState
}) => ownerState.anchorOrigin.vertical === 'bottom' && ownerState.anchorOrigin.horizontal === 'right' && ownerState.overlap === 'circular',
style: {
bottom: '14%',
right: '14%',
transform: 'scale(1) translate(50%, 50%)',
transformOrigin: '100% 100%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(50%, 50%)'
}
}
}, {
props: ({
ownerState
}) => ownerState.anchorOrigin.vertical === 'top' && ownerState.anchorOrigin.horizontal === 'left' && ownerState.overlap === 'circular',
style: {
top: '14%',
left: '14%',
transform: 'scale(1) translate(-50%, -50%)',
transformOrigin: '0% 0%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(-50%, -50%)'
}
}
}, {
props: ({
ownerState
}) => ownerState.anchorOrigin.vertical === 'bottom' && ownerState.anchorOrigin.horizontal === 'left' && ownerState.overlap === 'circular',
style: {
bottom: '14%',
left: '14%',
transform: 'scale(1) translate(-50%, 50%)',
transformOrigin: '0% 100%',
[`&.${badgeClasses.invisible}`]: {
transform: 'scale(0) translate(-50%, 50%)'
}
}
}, {
props: {
invisible: true
},
style: {
transition: theme.transitions.create('transform', {
easing: theme.transitions.easing.easeInOut,
duration: theme.transitions.duration.leavingScreen
})
}
}]
})));
function getAnchorOrigin(anchorOrigin) {
return {
vertical: anchorOrigin?.vertical ?? 'top',
horizontal: anchorOrigin?.horizontal ?? 'right'
};
}
const Badge = /*#__PURE__*/reactExports.forwardRef(function Badge(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiBadge'
});
const {
anchorOrigin: anchorOriginProp,
className,
classes: classesProp,
component,
components = {},
componentsProps = {},
children,
overlap: overlapProp = 'rectangular',
color: colorProp = 'default',
invisible: invisibleProp = false,
max: maxProp = 99,
badgeContent: badgeContentProp,
slots,
slotProps,
showZero = false,
variant: variantProp = 'standard',
...other
} = props;
const {
badgeContent,
invisible: invisibleFromHook,
max,
displayValue: displayValueFromHook
} = useBadge({
max: maxProp,
invisible: invisibleProp,
badgeContent: badgeContentProp,
showZero
});
const prevProps = usePreviousProps({
anchorOrigin: getAnchorOrigin(anchorOriginProp),
color: colorProp,
overlap: overlapProp,
variant: variantProp,
badgeContent: badgeContentProp
});
const invisible = invisibleFromHook || badgeContent == null && variantProp !== 'dot';
const {
color = colorProp,
overlap = overlapProp,
anchorOrigin: anchorOriginPropProp,
variant = variantProp
} = invisible ? prevProps : props;
const anchorOrigin = getAnchorOrigin(anchorOriginPropProp);
const displayValue = variant !== 'dot' ? displayValueFromHook : undefined;
const ownerState = {
...props,
badgeContent,
invisible,
max,
displayValue,
showZero,
anchorOrigin,
color,
overlap,
variant
};
const classes = useUtilityClasses$h(ownerState);
// support both `slots` and `components` for backward compatibility
const externalForwardedProps = {
slots: {
root: slots?.root ?? components.Root,
badge: slots?.badge ?? components.Badge
},
slotProps: {
root: slotProps?.root ?? componentsProps.root,
badge: slotProps?.badge ?? componentsProps.badge
}
};
const [RootSlot, rootProps] = useSlot('root', {
elementType: BadgeRoot,
externalForwardedProps: {
...externalForwardedProps,
...other
},
ownerState,
className: clsx(classes.root, className),
ref,
additionalProps: {
as: component
}
});
const [BadgeSlot, badgeProps] = useSlot('badge', {
elementType: BadgeBadge,
externalForwardedProps,
ownerState,
className: classes.badge
});
return /*#__PURE__*/jsxRuntimeExports.jsxs(RootSlot, {
...rootProps,
children: [children, /*#__PURE__*/jsxRuntimeExports.jsx(BadgeSlot, {
...badgeProps,
children: displayValue
})]
});
});
const boxClasses = generateUtilityClasses('MuiBox', ['root']);
const defaultTheme = createTheme();
const Box = createBox({
themeId: THEME_ID,
defaultTheme,
defaultClassName: boxClasses.root,
generateClassName: ClassNameGenerator.generate
});
function getSwitchBaseUtilityClass(slot) {
return generateUtilityClass('PrivateSwitchBase', slot);
}
generateUtilityClasses('PrivateSwitchBase', ['root', 'checked', 'disabled', 'input', 'edgeStart', 'edgeEnd']);
const useUtilityClasses$g = ownerState => {
const {
classes,
checked,
disabled,
edge
} = ownerState;
const slots = {
root: ['root', checked && 'checked', disabled && 'disabled', edge && `edge${capitalize(edge)}`],
input: ['input']
};
return composeClasses(slots, getSwitchBaseUtilityClass, classes);
};
const SwitchBaseRoot = styled(ButtonBase, {
name: 'MuiSwitchBase'
})({
padding: 9,
borderRadius: '50%',
variants: [{
props: {
edge: 'start',
size: 'small'
},
style: {
marginLeft: -3
}
}, {
props: ({
edge,
ownerState
}) => edge === 'start' && ownerState.size !== 'small',
style: {
marginLeft: -12
}
}, {
props: {
edge: 'end',
size: 'small'
},
style: {
marginRight: -3
}
}, {
props: ({
edge,
ownerState
}) => edge === 'end' && ownerState.size !== 'small',
style: {
marginRight: -12
}
}]
});
const SwitchBaseInput = styled('input', {
name: 'MuiSwitchBase',
shouldForwardProp: rootShouldForwardProp
})({
cursor: 'inherit',
position: 'absolute',
opacity: 0,
width: '100%',
height: '100%',
top: 0,
left: 0,
margin: 0,
padding: 0,
zIndex: 1
});
/**
* @ignore - internal component.
*/
const SwitchBase = /*#__PURE__*/reactExports.forwardRef(function SwitchBase(props, ref) {
const {
autoFocus,
checked: checkedProp,
checkedIcon,
defaultChecked,
disabled: disabledProp,
disableFocusRipple = false,
edge = false,
icon,
id,
inputProps,
inputRef,
name,
onBlur,
onChange,
onFocus,
readOnly,
required = false,
tabIndex,
type,
value,
slots = {},
slotProps = {},
...other
} = props;
const [checked, setCheckedState] = useControlled({
controlled: checkedProp,
default: Boolean(defaultChecked),
name: 'SwitchBase',
state: 'checked'
});
const muiFormControl = useFormControl();
const handleFocus = event => {
if (onFocus) {
onFocus(event);
}
if (muiFormControl && muiFormControl.onFocus) {
muiFormControl.onFocus(event);
}
};
const handleBlur = event => {
if (onBlur) {
onBlur(event);
}
if (muiFormControl && muiFormControl.onBlur) {
muiFormControl.onBlur(event);
}
};
const handleInputChange = event => {
// Workaround for https://github.com/facebook/react/issues/9023
if (event.nativeEvent.defaultPrevented) {
return;
}
const newChecked = event.target.checked;
setCheckedState(newChecked);
if (onChange) {
// TODO v6: remove the second argument.
onChange(event, newChecked);
}
};
let disabled = disabledProp;
if (muiFormControl) {
if (typeof disabled === 'undefined') {
disabled = muiFormControl.disabled;
}
}
const hasLabelFor = type === 'checkbox' || type === 'radio';
const ownerState = {
...props,
checked,
disabled,
disableFocusRipple,
edge
};
const classes = useUtilityClasses$g(ownerState);
const externalForwardedProps = {
slots,
slotProps: {
input: inputProps,
...slotProps
}
};
const [RootSlot, rootSlotProps] = useSlot('root', {
ref,
elementType: SwitchBaseRoot,
className: classes.root,
shouldForwardComponentProp: true,
externalForwardedProps: {
...externalForwardedProps,
component: 'span',
...other
},
getSlotProps: handlers => ({
...handlers,
onFocus: event => {
handlers.onFocus?.(event);
handleFocus(event);
},
onBlur: event => {
handlers.onBlur?.(event);
handleBlur(event);
}
}),
ownerState,
additionalProps: {
centerRipple: true,
focusRipple: !disableFocusRipple,
disabled,
role: undefined,
tabIndex: null
}
});
const [InputSlot, inputSlotProps] = useSlot('input', {
ref: inputRef,
elementType: SwitchBaseInput,
className: classes.input,
externalForwardedProps,
getSlotProps: handlers => ({
onChange: event => {
handlers.onChange?.(event);
handleInputChange(event);
}
}),
ownerState,
additionalProps: {
autoFocus,
checked: checkedProp,
defaultChecked,
disabled,
id: hasLabelFor ? id : undefined,
name,
readOnly,
required,
tabIndex,
type,
...(type === 'checkbox' && value === undefined ? {} : {
value
})
}
});
return /*#__PURE__*/jsxRuntimeExports.jsxs(RootSlot, {
...rootSlotProps,
children: [/*#__PURE__*/jsxRuntimeExports.jsx(InputSlot, {
...inputSlotProps
}), checked ? checkedIcon : icon]
});
});
var CheckBoxOutlineBlankIcon = createSvgIcon(/*#__PURE__*/jsxRuntimeExports.jsx("path", {
d: "M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"
}), 'CheckBoxOutlineBlank');
var CheckBoxIcon = createSvgIcon(/*#__PURE__*/jsxRuntimeExports.jsx("path", {
d: "M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"
}), 'CheckBox');
var IndeterminateCheckBoxIcon = createSvgIcon(/*#__PURE__*/jsxRuntimeExports.jsx("path", {
d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-2 10H7v-2h10v2z"
}), 'IndeterminateCheckBox');
function getCheckboxUtilityClass(slot) {
return generateUtilityClass('MuiCheckbox', slot);
}
const checkboxClasses = generateUtilityClasses('MuiCheckbox', ['root', 'checked', 'disabled', 'indeterminate', 'colorPrimary', 'colorSecondary', 'sizeSmall', 'sizeMedium']);
const useUtilityClasses$f = ownerState => {
const {
classes,
indeterminate,
color,
size
} = ownerState;
const slots = {
root: ['root', indeterminate && 'indeterminate', `color${capitalize(color)}`, `size${capitalize(size)}`]
};
const composedClasses = composeClasses(slots, getCheckboxUtilityClass, classes);
return {
...classes,
// forward the disabled and checked classes to the SwitchBase
...composedClasses
};
};
const CheckboxRoot = styled(SwitchBase, {
shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
name: 'MuiCheckbox',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, ownerState.indeterminate && styles.indeterminate, styles[`size${capitalize(ownerState.size)}`], ownerState.color !== 'default' && styles[`color${capitalize(ownerState.color)}`]];
}
})(memoTheme(({
theme
}) => ({
color: (theme.vars || theme).palette.text.secondary,
variants: [{
props: {
color: 'default',
disableRipple: false
},
style: {
'&:hover': {
backgroundColor: theme.vars ? `rgba(${theme.vars.palette.action.activeChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette.action.active, theme.palette.action.hoverOpacity)
}
}
}, ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()).map(([color]) => ({
props: {
color,
disableRipple: false
},
style: {
'&:hover': {
backgroundColor: theme.vars ? `rgba(${theme.vars.palette[color].mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette[color].main, theme.palette.action.hoverOpacity)
}
}
})), ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()).map(([color]) => ({
props: {
color
},
style: {
[`&.${checkboxClasses.checked}, &.${checkboxClasses.indeterminate}`]: {
color: (theme.vars || theme).palette[color].main
},
[`&.${checkboxClasses.disabled}`]: {
color: (theme.vars || theme).palette.action.disabled
}
}
})), {
// Should be last to override other colors
props: {
disableRipple: false
},
style: {
// Reset on touch devices, it doesn't add specificity
'&:hover': {
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
}
}]
})));
const defaultCheckedIcon$1 = /*#__PURE__*/jsxRuntimeExports.jsx(CheckBoxIcon, {});
const defaultIcon$1 = /*#__PURE__*/jsxRuntimeExports.jsx(CheckBoxOutlineBlankIcon, {});
const defaultIndeterminateIcon = /*#__PURE__*/jsxRuntimeExports.jsx(IndeterminateCheckBoxIcon, {});
const Checkbox = /*#__PURE__*/reactExports.forwardRef(function Checkbox(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiCheckbox'
});
const {
checkedIcon = defaultCheckedIcon$1,
color = 'primary',
icon: iconProp = defaultIcon$1,
indeterminate = false,
indeterminateIcon: indeterminateIconProp = defaultIndeterminateIcon,
inputProps,
size = 'medium',
disableRipple = false,
className,
slots = {},
slotProps = {},
...other
} = props;
const icon = indeterminate ? indeterminateIconProp : iconProp;
const indeterminateIcon = indeterminate ? indeterminateIconProp : checkedIcon;
const ownerState = {
...props,
disableRipple,
color,
indeterminate,
size
};
const classes = useUtilityClasses$f(ownerState);
const externalInputProps = slotProps.input ?? inputProps;
const [RootSlot, rootSlotProps] = useSlot('root', {
ref,
elementType: CheckboxRoot,
className: clsx(classes.root, className),
shouldForwardComponentProp: true,
externalForwardedProps: {
slots,
slotProps,
...other
},
ownerState,
additionalProps: {
type: 'checkbox',
icon: /*#__PURE__*/reactExports.cloneElement(icon, {
fontSize: icon.props.fontSize ?? size
}),
checkedIcon: /*#__PURE__*/reactExports.cloneElement(indeterminateIcon, {
fontSize: indeterminateIcon.props.fontSize ?? size
}),
disableRipple,
slots,
slotProps: {
input: mergeSlotProps(typeof externalInputProps === 'function' ? externalInputProps(ownerState) : externalInputProps, {
'data-indeterminate': indeterminate
})
}
}
});
return /*#__PURE__*/jsxRuntimeExports.jsx(RootSlot, {
...rootSlotProps,
classes: classes
});
});
// Is a vertical scrollbar displayed?
function isOverflowing(container) {
const doc = ownerDocument(container);
if (doc.body === container) {
return ownerWindow(container).innerWidth > doc.documentElement.clientWidth;
}
return container.scrollHeight > container.clientHeight;
}
function ariaHidden(element, hide) {
if (hide) {
element.setAttribute('aria-hidden', 'true');
} else {
element.removeAttribute('aria-hidden');
}
}
function getPaddingRight(element) {
return parseInt(ownerWindow(element).getComputedStyle(element).paddingRight, 10) || 0;
}
function isAriaHiddenForbiddenOnElement(element) {
// The forbidden HTML tags are the ones from ARIA specification that
// can be children of body and can't have aria-hidden attribute.
// cf. https://www.w3.org/TR/html-aria/#docconformance
const forbiddenTagNames = ['TEMPLATE', 'SCRIPT', 'STYLE', 'LINK', 'MAP', 'META', 'NOSCRIPT', 'PICTURE', 'COL', 'COLGROUP', 'PARAM', 'SLOT', 'SOURCE', 'TRACK'];
const isForbiddenTagName = forbiddenTagNames.includes(element.tagName);
const isInputHidden = element.tagName === 'INPUT' && element.getAttribute('type') === 'hidden';
return isForbiddenTagName || isInputHidden;
}
function ariaHiddenSiblings(container, mountElement, currentElement, elementsToExclude, hide) {
const blacklist = [mountElement, currentElement, ...elementsToExclude];
[].forEach.call(container.children, element => {
const isNotExcludedElement = !blacklist.includes(element);
const isNotForbiddenElement = !isAriaHiddenForbiddenOnElement(element);
if (isNotExcludedElement && isNotForbiddenElement) {
ariaHidden(element, hide);
}
});
}
function findIndexOf(items, callback) {
let idx = -1;
items.some((item, index) => {
if (callback(item)) {
idx = index;
return true;
}
return false;
});
return idx;
}
function handleContainer(containerInfo, props) {
const restoreStyle = [];
const container = containerInfo.container;
if (!props.disableScrollLock) {
if (isOverflowing(container)) {
// Compute the size before applying overflow hidden to avoid any scroll jumps.
const scrollbarSize = getScrollbarSize$1(ownerWindow(container));
restoreStyle.push({
value: container.style.paddingRight,
property: 'padding-right',
el: container
});
// Use computed style, here to get the real padding to add our scrollbar width.
container.style.paddingRight = `${getPaddingRight(container) + scrollbarSize}px`;
// .mui-fixed is a global helper.
const fixedElements = ownerDocument(container).querySelectorAll('.mui-fixed');
[].forEach.call(fixedElements, element => {
restoreStyle.push({
value: element.style.paddingRight,
property: 'padding-right',
el: element
});
element.style.paddingRight = `${getPaddingRight(element) + scrollbarSize}px`;
});
}
let scrollContainer;
if (container.parentNode instanceof DocumentFragment) {
scrollContainer = ownerDocument(container).body;
} else {
// Support html overflow-y: auto for scroll stability between pages
// https://css-tricks.com/snippets/css/force-vertical-scrollbar/
const parent = container.parentElement;
const containerWindow = ownerWindow(container);
scrollContainer = parent?.nodeName === 'HTML' && containerWindow.getComputedStyle(parent).overflowY === 'scroll' ? parent : container;
}
// Block the scroll even if no scrollbar is visible to account for mobile keyboard
// screensize shrink.
restoreStyle.push({
value: scrollContainer.style.overflow,
property: 'overflow',
el: scrollContainer
}, {
value: scrollContainer.style.overflowX,
property: 'overflow-x',
el: scrollContainer
}, {
value: scrollContainer.style.overflowY,
property: 'overflow-y',
el: scrollContainer
});
scrollContainer.style.overflow = 'hidden';
}
const restore = () => {
restoreStyle.forEach(({
value,
el,
property
}) => {
if (value) {
el.style.setProperty(property, value);
} else {
el.style.removeProperty(property);
}
});
};
return restore;
}
function getHiddenSiblings(container) {
const hiddenSiblings = [];
[].forEach.call(container.children, element => {
if (element.getAttribute('aria-hidden') === 'true') {
hiddenSiblings.push(element);
}
});
return hiddenSiblings;
}
/**
* @ignore - do not document.
*
* Proper state management for containers and the modals in those containers.
* Simplified, but inspired by react-overlay's ModalManager class.
* Used by the Modal to ensure proper styling of containers.
*/
class ModalManager {
constructor() {
this.modals = [];
this.containers = [];
}
add(modal, container) {
let modalIndex = this.modals.indexOf(modal);
if (modalIndex !== -1) {
return modalIndex;
}
modalIndex = this.modals.length;
this.modals.push(modal);
// If the modal we are adding is already in the DOM.
if (modal.modalRef) {
ariaHidden(modal.modalRef, false);
}
const hiddenSiblings = getHiddenSiblings(container);
ariaHiddenSiblings(container, modal.mount, modal.modalRef, hiddenSiblings, true);
const containerIndex = findIndexOf(this.containers, item => item.container === container);
if (containerIndex !== -1) {
this.containers[containerIndex].modals.push(modal);
return modalIndex;
}
this.containers.push({
modals: [modal],
container,
restore: null,
hiddenSiblings
});
return modalIndex;
}
mount(modal, props) {
const containerIndex = findIndexOf(this.containers, item => item.modals.includes(modal));
const containerInfo = this.containers[containerIndex];
if (!containerInfo.restore) {
containerInfo.restore = handleContainer(containerInfo, props);
}
}
remove(modal, ariaHiddenState = true) {
const modalIndex = this.modals.indexOf(modal);
if (modalIndex === -1) {
return modalIndex;
}
const containerIndex = findIndexOf(this.containers, item => item.modals.includes(modal));
const containerInfo = this.containers[containerIndex];
containerInfo.modals.splice(containerInfo.modals.indexOf(modal), 1);
this.modals.splice(modalIndex, 1);
// If that was the last modal in a container, clean up the container.
if (containerInfo.modals.length === 0) {
// The modal might be closed before it had the chance to be mounted in the DOM.
if (containerInfo.restore) {
containerInfo.restore();
}
if (modal.modalRef) {
// In case the modal wasn't in the DOM yet.
ariaHidden(modal.modalRef, ariaHiddenState);
}
ariaHiddenSiblings(containerInfo.container, modal.mount, modal.modalRef, containerInfo.hiddenSiblings, false);
this.containers.splice(containerIndex, 1);
} else {
// Otherwise make sure the next top modal is visible to a screen reader.
const nextTop = containerInfo.modals[containerInfo.modals.length - 1];
// as soon as a modal is adding its modalRef is undefined. it can't set
// aria-hidden because the dom element doesn't exist either
// when modal was unmounted before modalRef gets null
if (nextTop.modalRef) {
ariaHidden(nextTop.modalRef, false);
}
}
return modalIndex;
}
isTopModal(modal) {
return this.modals.length > 0 && this.modals[this.modals.length - 1] === modal;
}
}
// Inspired by https://github.com/focus-trap/tabbable
const candidatesSelector = ['input', 'select', 'textarea', 'a[href]', 'button', '[tabindex]', 'audio[controls]', 'video[controls]', '[contenteditable]:not([contenteditable="false"])'].join(',');
function getTabIndex(node) {
const tabindexAttr = parseInt(node.getAttribute('tabindex') || '', 10);
if (!Number.isNaN(tabindexAttr)) {
return tabindexAttr;
}
// Browsers do not return `tabIndex` correctly for contentEditable nodes;
// https://issues.chromium.org/issues/41283952
// so if they don't have a tabindex attribute specifically set, assume it's 0.
// in Chrome, <details/>, <audio controls/> and <video controls/> elements get a default
// `tabIndex` of -1 when the 'tabindex' attribute isn't specified in the DOM,
// yet they are still part of the regular tab order; in FF, they get a default
// `tabIndex` of 0; since Chrome still puts those elements in the regular tab
// order, consider their tab index to be 0.
if (node.contentEditable === 'true' || (node.nodeName === 'AUDIO' || node.nodeName === 'VIDEO' || node.nodeName === 'DETAILS') && node.getAttribute('tabindex') === null) {
return 0;
}
return node.tabIndex;
}
function isNonTabbableRadio(node) {
if (node.tagName !== 'INPUT' || node.type !== 'radio') {
return false;
}
if (!node.name) {
return false;
}
const getRadio = selector => node.ownerDocument.querySelector(`input[type="radio"]${selector}`);
let roving = getRadio(`[name="${node.name}"]:checked`);
if (!roving) {
roving = getRadio(`[name="${node.name}"]`);
}
return roving !== node;
}
function isNodeMatchingSelectorFocusable(node) {
if (node.disabled || node.tagName === 'INPUT' && node.type === 'hidden' || isNonTabbableRadio(node)) {
return false;
}
return true;
}
function defaultGetTabbable(root) {
const regularTabNodes = [];
const orderedTabNodes = [];
Array.from(root.querySelectorAll(candidatesSelector)).forEach((node, i) => {
const nodeTabIndex = getTabIndex(node);
if (nodeTabIndex === -1 || !isNodeMatchingSelectorFocusable(node)) {
return;
}
if (nodeTabIndex === 0) {
regularTabNodes.push(node);
} else {
orderedTabNodes.push({
documentOrder: i,
tabIndex: nodeTabIndex,
node: node
});
}
});
return orderedTabNodes.sort((a, b) => a.tabIndex === b.tabIndex ? a.documentOrder - b.documentOrder : a.tabIndex - b.tabIndex).map(a => a.node).concat(regularTabNodes);
}
function defaultIsEnabled() {
return true;
}
/**
* @ignore - internal component.
*/
function FocusTrap(props) {
const {
children,
disableAutoFocus = false,
disableEnforceFocus = false,
disableRestoreFocus = false,
getTabbable = defaultGetTabbable,
isEnabled = defaultIsEnabled,
open
} = props;
const ignoreNextEnforceFocus = reactExports.useRef(false);
const sentinelStart = reactExports.useRef(null);
const sentinelEnd = reactExports.useRef(null);
const nodeToRestore = reactExports.useRef(null);
const reactFocusEventTarget = reactExports.useRef(null);
// This variable is useful when disableAutoFocus is true.
// It waits for the active element to move into the component to activate.
const activated = reactExports.useRef(false);
const rootRef = reactExports.useRef(null);
const handleRef = useForkRef(getReactElementRef(children), rootRef);
const lastKeydown = reactExports.useRef(null);
reactExports.useEffect(() => {
// We might render an empty child.
if (!open || !rootRef.current) {
return;
}
activated.current = !disableAutoFocus;
}, [disableAutoFocus, open]);
reactExports.useEffect(() => {
// We might render an empty child.
if (!open || !rootRef.current) {
return;
}
const doc = ownerDocument(rootRef.current);
if (!rootRef.current.contains(doc.activeElement)) {
if (!rootRef.current.hasAttribute('tabIndex')) {
rootRef.current.setAttribute('tabIndex', '-1');
}
if (activated.current) {
rootRef.current.focus();
}
}
return () => {
// restoreLastFocus()
if (!disableRestoreFocus) {
// In IE11 it is possible for document.activeElement to be null resulting
// in nodeToRestore.current being null.
// Not all elements in IE11 have a focus method.
// Once IE11 support is dropped the focus() call can be unconditional.
if (nodeToRestore.current && nodeToRestore.current.focus) {
ignoreNextEnforceFocus.current = true;
nodeToRestore.current.focus();
}
nodeToRestore.current = null;
}
};
// Missing `disableRestoreFocus` which is fine.
// We don't support changing that prop on an open FocusTrap
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
reactExports.useEffect(() => {
// We might render an empty child.
if (!open || !rootRef.current) {
return;
}
const doc = ownerDocument(rootRef.current);
const loopFocus = nativeEvent => {
lastKeydown.current = nativeEvent;
if (disableEnforceFocus || !isEnabled() || nativeEvent.key !== 'Tab') {
return;
}
// Make sure the next tab starts from the right place.
// doc.activeElement refers to the origin.
if (doc.activeElement === rootRef.current && nativeEvent.shiftKey) {
// We need to ignore the next contain as
// it will try to move the focus back to the rootRef element.
ignoreNextEnforceFocus.current = true;
if (sentinelEnd.current) {
sentinelEnd.current.focus();
}
}
};
const contain = () => {
const rootElement = rootRef.current;
// Cleanup functions are executed lazily in React 17.
// Contain can be called between the component being unmounted and its cleanup function being run.
if (rootElement === null) {
return;
}
if (!doc.hasFocus() || !isEnabled() || ignoreNextEnforceFocus.current) {
ignoreNextEnforceFocus.current = false;
return;
}
// The focus is already inside
if (rootElement.contains(doc.activeElement)) {
return;
}
// The disableEnforceFocus is set and the focus is outside of the focus trap (and sentinel nodes)
if (disableEnforceFocus && doc.activeElement !== sentinelStart.current && doc.activeElement !== sentinelEnd.current) {
return;
}
// if the focus event is not coming from inside the children's react tree, reset the refs
if (doc.activeElement !== reactFocusEventTarget.current) {
reactFocusEventTarget.current = null;
} else if (reactFocusEventTarget.current !== null) {
return;
}
if (!activated.current) {
return;
}
let tabbable = [];
if (doc.activeElement === sentinelStart.current || doc.activeElement === sentinelEnd.current) {
tabbable = getTabbable(rootRef.current);
}
// one of the sentinel nodes was focused, so move the focus
// to the first/last tabbable element inside the focus trap
if (tabbable.length > 0) {
const isShiftTab = Boolean(lastKeydown.current?.shiftKey && lastKeydown.current?.key === 'Tab');
const focusNext = tabbable[0];
const focusPrevious = tabbable[tabbable.length - 1];
if (typeof focusNext !== 'string' && typeof focusPrevious !== 'string') {
if (isShiftTab) {
focusPrevious.focus();
} else {
focusNext.focus();
}
}
// no tabbable elements in the trap focus or the focus was outside of the focus trap
} else {
rootElement.focus();
}
};
doc.addEventListener('focusin', contain);
doc.addEventListener('keydown', loopFocus, true);
// With Edge, Safari and Firefox, no focus related events are fired when the focused area stops being a focused area.
// for example https://bugzilla.mozilla.org/show_bug.cgi?id=559561.
// Instead, we can look if the active element was restored on the BODY element.
//
// The whatwg spec defines how the browser should behave but does not explicitly mention any events:
// https://html.spec.whatwg.org/multipage/interaction.html#focus-fixup-rule.
const interval = setInterval(() => {
if (doc.activeElement && doc.activeElement.tagName === 'BODY') {
contain();
}
}, 50);
return () => {
clearInterval(interval);
doc.removeEventListener('focusin', contain);
doc.removeEventListener('keydown', loopFocus, true);
};
}, [disableAutoFocus, disableEnforceFocus, disableRestoreFocus, isEnabled, open, getTabbable]);
const onFocus = event => {
if (nodeToRestore.current === null) {
nodeToRestore.current = event.relatedTarget;
}
activated.current = true;
reactFocusEventTarget.current = event.target;
const childrenPropsHandler = children.props.onFocus;
if (childrenPropsHandler) {
childrenPropsHandler(event);
}
};
const handleFocusSentinel = event => {
if (nodeToRestore.current === null) {
nodeToRestore.current = event.relatedTarget;
}
activated.current = true;
};
return /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports.Fragment, {
children: [/*#__PURE__*/jsxRuntimeExports.jsx("div", {
tabIndex: open ? 0 : -1,
onFocus: handleFocusSentinel,
ref: sentinelStart,
"data-testid": "sentinelStart"
}), /*#__PURE__*/reactExports.cloneElement(children, {
ref: handleRef,
onFocus
}), /*#__PURE__*/jsxRuntimeExports.jsx("div", {
tabIndex: open ? 0 : -1,
onFocus: handleFocusSentinel,
ref: sentinelEnd,
"data-testid": "sentinelEnd"
})]
});
}
function getContainer(container) {
return typeof container === 'function' ? container() : container;
}
function getHasTransition(children) {
return children ? children.props.hasOwnProperty('in') : false;
}
const noop$1 = () => {};
// A modal manager used to track and manage the state of open Modals.
// Modals don't open on the server so this won't conflict with concurrent requests.
const manager = new ModalManager();
/**
*
* Demos:
*
* - [Modal](https://mui.com/base-ui/react-modal/#hook)
*
* API:
*
* - [useModal API](https://mui.com/base-ui/react-modal/hooks-api/#use-modal)
*/
function useModal(parameters) {
const {
container,
disableEscapeKeyDown = false,
disableScrollLock = false,
closeAfterTransition = false,
onTransitionEnter,
onTransitionExited,
children,
onClose,
open,
rootRef
} = parameters;
// @ts-ignore internal logic
const modal = reactExports.useRef({});
const mountNodeRef = reactExports.useRef(null);
const modalRef = reactExports.useRef(null);
const handleRef = useForkRef(modalRef, rootRef);
const [exited, setExited] = reactExports.useState(!open);
const hasTransition = getHasTransition(children);
let ariaHiddenProp = true;
if (parameters['aria-hidden'] === 'false' || parameters['aria-hidden'] === false) {
ariaHiddenProp = false;
}
const getDoc = () => ownerDocument(mountNodeRef.current);
const getModal = () => {
modal.current.modalRef = modalRef.current;
modal.current.mount = mountNodeRef.current;
return modal.current;
};
const handleMounted = () => {
manager.mount(getModal(), {
disableScrollLock
});
// Fix a bug on Chrome where the scroll isn't initially 0.
if (modalRef.current) {
modalRef.current.scrollTop = 0;
}
};
const handleOpen = useEventCallback(() => {
const resolvedContainer = getContainer(container) || getDoc().body;
manager.add(getModal(), resolvedContainer);
// The element was already mounted.
if (modalRef.current) {
handleMounted();
}
});
const isTopModal = () => manager.isTopModal(getModal());
const handlePortalRef = useEventCallback(node => {
mountNodeRef.current = node;
if (!node) {
return;
}
if (open && isTopModal()) {
handleMounted();
} else if (modalRef.current) {
ariaHidden(modalRef.current, ariaHiddenProp);
}
});
const handleClose = reactExports.useCallback(() => {
manager.remove(getModal(), ariaHiddenProp);
}, [ariaHiddenProp]);
reactExports.useEffect(() => {
return () => {
handleClose();
};
}, [handleClose]);
reactExports.useEffect(() => {
if (open) {
handleOpen();
} else if (!hasTransition || !closeAfterTransition) {
handleClose();
}
}, [open, handleClose, hasTransition, closeAfterTransition, handleOpen]);
const createHandleKeyDown = otherHandlers => event => {
otherHandlers.onKeyDown?.(event);
// The handler doesn't take event.defaultPrevented into account:
//
// event.preventDefault() is meant to stop default behaviors like
// clicking a checkbox to check it, hitting a button to submit a form,
// and hitting left arrow to move the cursor in a text input etc.
// Only special HTML elements have these default behaviors.
if (event.key !== 'Escape' || event.which === 229 ||
// Wait until IME is settled.
!isTopModal()) {
return;
}
if (!disableEscapeKeyDown) {
// Swallow the event, in case someone is listening for the escape key on the body.
event.stopPropagation();
if (onClose) {
onClose(event, 'escapeKeyDown');
}
}
};
const createHandleBackdropClick = otherHandlers => event => {
otherHandlers.onClick?.(event);
if (event.target !== event.currentTarget) {
return;
}
if (onClose) {
onClose(event, 'backdropClick');
}
};
const getRootProps = (otherHandlers = {}) => {
const propsEventHandlers = extractEventHandlers(parameters);
// The custom event handlers shouldn't be spread on the root element
delete propsEventHandlers.onTransitionEnter;
delete propsEventHandlers.onTransitionExited;
const externalEventHandlers = {
...propsEventHandlers,
...otherHandlers
};
return {
/*
* Marking an element with the role presentation indicates to assistive technology
* that this element should be ignored; it exists to support the web application and
* is not meant for humans to interact with directly.
* https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-static-element-interactions.md
*/
role: 'presentation',
...externalEventHandlers,
onKeyDown: createHandleKeyDown(externalEventHandlers),
ref: handleRef
};
};
const getBackdropProps = (otherHandlers = {}) => {
const externalEventHandlers = otherHandlers;
return {
'aria-hidden': true,
...externalEventHandlers,
onClick: createHandleBackdropClick(externalEventHandlers),
open
};
};
const getTransitionProps = () => {
const handleEnter = () => {
setExited(false);
if (onTransitionEnter) {
onTransitionEnter();
}
};
const handleExited = () => {
setExited(true);
if (onTransitionExited) {
onTransitionExited();
}
if (closeAfterTransition) {
handleClose();
}
};
return {
onEnter: createChainedFunction(handleEnter, children?.props.onEnter ?? noop$1),
onExited: createChainedFunction(handleExited, children?.props.onExited ?? noop$1)
};
};
return {
getRootProps,
getBackdropProps,
getTransitionProps,
rootRef: handleRef,
portalRef: handlePortalRef,
isTopModal,
exited,
hasTransition
};
}
function getModalUtilityClass(slot) {
return generateUtilityClass('MuiModal', slot);
}
generateUtilityClasses('MuiModal', ['root', 'hidden', 'backdrop']);
const useUtilityClasses$e = ownerState => {
const {
open,
exited,
classes
} = ownerState;
const slots = {
root: ['root', !open && exited && 'hidden'],
backdrop: ['backdrop']
};
return composeClasses(slots, getModalUtilityClass, classes);
};
const ModalRoot = styled('div', {
name: 'MuiModal',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, !ownerState.open && ownerState.exited && styles.hidden];
}
})(memoTheme(({
theme
}) => ({
position: 'fixed',
zIndex: (theme.vars || theme).zIndex.modal,
right: 0,
bottom: 0,
top: 0,
left: 0,
variants: [{
props: ({
ownerState
}) => !ownerState.open && ownerState.exited,
style: {
visibility: 'hidden'
}
}]
})));
const ModalBackdrop = styled(Backdrop, {
name: 'MuiModal',
slot: 'Backdrop',
overridesResolver: (props, styles) => {
return styles.backdrop;
}
})({
zIndex: -1
});
/**
* Modal is a lower-level construct that is leveraged by the following components:
*
* - [Dialog](/material-ui/api/dialog/)
* - [Drawer](/material-ui/api/drawer/)
* - [Menu](/material-ui/api/menu/)
* - [Popover](/material-ui/api/popover/)
*
* If you are creating a modal dialog, you probably want to use the [Dialog](/material-ui/api/dialog/) component
* rather than directly using Modal.
*
* This component shares many concepts with [react-overlays](https://react-bootstrap.github.io/react-overlays/#modals).
*/
const Modal = /*#__PURE__*/reactExports.forwardRef(function Modal(inProps, ref) {
const props = useDefaultProps({
name: 'MuiModal',
props: inProps
});
const {
BackdropComponent = ModalBackdrop,
BackdropProps,
classes: classesProp,
className,
closeAfterTransition = false,
children,
container,
component,
components = {},
componentsProps = {},
disableAutoFocus = false,
disableEnforceFocus = false,
disableEscapeKeyDown = false,
disablePortal = false,
disableRestoreFocus = false,
disableScrollLock = false,
hideBackdrop = false,
keepMounted = false,
onBackdropClick,
onClose,
onTransitionEnter,
onTransitionExited,
open,
slotProps = {},
slots = {},
// eslint-disable-next-line react/prop-types
theme,
...other
} = props;
const propsWithDefaults = {
...props,
closeAfterTransition,
disableAutoFocus,
disableEnforceFocus,
disableEscapeKeyDown,
disablePortal,
disableRestoreFocus,
disableScrollLock,
hideBackdrop,
keepMounted
};
const {
getRootProps,
getBackdropProps,
getTransitionProps,
portalRef,
isTopModal,
exited,
hasTransition
} = useModal({
...propsWithDefaults,
rootRef: ref
});
const ownerState = {
...propsWithDefaults,
exited
};
const classes = useUtilityClasses$e(ownerState);
const childProps = {};
if (children.props.tabIndex === undefined) {
childProps.tabIndex = '-1';
}
// It's a Transition like component
if (hasTransition) {
const {
onEnter,
onExited
} = getTransitionProps();
childProps.onEnter = onEnter;
childProps.onExited = onExited;
}
const externalForwardedProps = {
slots: {
root: components.Root,
backdrop: components.Backdrop,
...slots
},
slotProps: {
...componentsProps,
...slotProps
}
};
const [RootSlot, rootProps] = useSlot('root', {
ref,
elementType: ModalRoot,
externalForwardedProps: {
...externalForwardedProps,
...other,
component
},
getSlotProps: getRootProps,
ownerState,
className: clsx(className, classes?.root, !ownerState.open && ownerState.exited && classes?.hidden)
});
const [BackdropSlot, backdropProps] = useSlot('backdrop', {
ref: BackdropProps?.ref,
elementType: BackdropComponent,
externalForwardedProps,
shouldForwardComponentProp: true,
additionalProps: BackdropProps,
getSlotProps: otherHandlers => {
return getBackdropProps({
...otherHandlers,
onClick: event => {
if (onBackdropClick) {
onBackdropClick(event);
}
if (otherHandlers?.onClick) {
otherHandlers.onClick(event);
}
}
});
},
className: clsx(BackdropProps?.className, classes?.backdrop),
ownerState
});
if (!keepMounted && !open && (!hasTransition || exited)) {
return null;
}
return /*#__PURE__*/jsxRuntimeExports.jsx(Portal, {
ref: portalRef,
container: container,
disablePortal: disablePortal,
children: /*#__PURE__*/jsxRuntimeExports.jsxs(RootSlot, {
...rootProps,
children: [!hideBackdrop && BackdropComponent ? /*#__PURE__*/jsxRuntimeExports.jsx(BackdropSlot, {
...backdropProps
}) : null, /*#__PURE__*/jsxRuntimeExports.jsx(FocusTrap, {
disableEnforceFocus: disableEnforceFocus,
disableAutoFocus: disableAutoFocus,
disableRestoreFocus: disableRestoreFocus,
isEnabled: isTopModal,
open: open,
children: /*#__PURE__*/reactExports.cloneElement(children, childProps)
})]
})
});
});
function getDividerUtilityClass(slot) {
return generateUtilityClass('MuiDivider', slot);
}
const dividerClasses = generateUtilityClasses('MuiDivider', ['root', 'absolute', 'fullWidth', 'inset', 'middle', 'flexItem', 'light', 'vertical', 'withChildren', 'withChildrenVertical', 'textAlignRight', 'textAlignLeft', 'wrapper', 'wrapperVertical']);
const useUtilityClasses$d = ownerState => {
const {
absolute,
children,
classes,
flexItem,
light,
orientation,
textAlign,
variant
} = ownerState;
const slots = {
root: ['root', absolute && 'absolute', variant, light && 'light', orientation === 'vertical' && 'vertical', flexItem && 'flexItem', children && 'withChildren', children && orientation === 'vertical' && 'withChildrenVertical', textAlign === 'right' && orientation !== 'vertical' && 'textAlignRight', textAlign === 'left' && orientation !== 'vertical' && 'textAlignLeft'],
wrapper: ['wrapper', orientation === 'vertical' && 'wrapperVertical']
};
return composeClasses(slots, getDividerUtilityClass, classes);
};
const DividerRoot = styled('div', {
name: 'MuiDivider',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, ownerState.absolute && styles.absolute, styles[ownerState.variant], ownerState.light && styles.light, ownerState.orientation === 'vertical' && styles.vertical, ownerState.flexItem && styles.flexItem, ownerState.children && styles.withChildren, ownerState.children && ownerState.orientation === 'vertical' && styles.withChildrenVertical, ownerState.textAlign === 'right' && ownerState.orientation !== 'vertical' && styles.textAlignRight, ownerState.textAlign === 'left' && ownerState.orientation !== 'vertical' && styles.textAlignLeft];
}
})(memoTheme(({
theme
}) => ({
margin: 0,
// Reset browser default style.
flexShrink: 0,
borderWidth: 0,
borderStyle: 'solid',
borderColor: (theme.vars || theme).palette.divider,
borderBottomWidth: 'thin',
variants: [{
props: {
absolute: true
},
style: {
position: 'absolute',
bottom: 0,
left: 0,
width: '100%'
}
}, {
props: {
light: true
},
style: {
borderColor: theme.vars ? `rgba(${theme.vars.palette.dividerChannel} / 0.08)` : alpha(theme.palette.divider, 0.08)
}
}, {
props: {
variant: 'inset'
},
style: {
marginLeft: 72
}
}, {
props: {
variant: 'middle',
orientation: 'horizontal'
},
style: {
marginLeft: theme.spacing(2),
marginRight: theme.spacing(2)
}
}, {
props: {
variant: 'middle',
orientation: 'vertical'
},
style: {
marginTop: theme.spacing(1),
marginBottom: theme.spacing(1)
}
}, {
props: {
orientation: 'vertical'
},
style: {
height: '100%',
borderBottomWidth: 0,
borderRightWidth: 'thin'
}
}, {
props: {
flexItem: true
},
style: {
alignSelf: 'stretch',
height: 'auto'
}
}, {
props: ({
ownerState
}) => !!ownerState.children,
style: {
display: 'flex',
textAlign: 'center',
border: 0,
borderTopStyle: 'solid',
borderLeftStyle: 'solid',
'&::before, &::after': {
content: '""',
alignSelf: 'center'
}
}
}, {
props: ({
ownerState
}) => ownerState.children && ownerState.orientation !== 'vertical',
style: {
'&::before, &::after': {
width: '100%',
borderTop: `thin solid ${(theme.vars || theme).palette.divider}`,
borderTopStyle: 'inherit'
}
}
}, {
props: ({
ownerState
}) => ownerState.orientation === 'vertical' && ownerState.children,
style: {
flexDirection: 'column',
'&::before, &::after': {
height: '100%',
borderLeft: `thin solid ${(theme.vars || theme).palette.divider}`,
borderLeftStyle: 'inherit'
}
}
}, {
props: ({
ownerState
}) => ownerState.textAlign === 'right' && ownerState.orientation !== 'vertical',
style: {
'&::before': {
width: '90%'
},
'&::after': {
width: '10%'
}
}
}, {
props: ({
ownerState
}) => ownerState.textAlign === 'left' && ownerState.orientation !== 'vertical',
style: {
'&::before': {
width: '10%'
},
'&::after': {
width: '90%'
}
}
}]
})));
const DividerWrapper = styled('span', {
name: 'MuiDivider',
slot: 'Wrapper',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.wrapper, ownerState.orientation === 'vertical' && styles.wrapperVertical];
}
})(memoTheme(({
theme
}) => ({
display: 'inline-block',
paddingLeft: `calc(${theme.spacing(1)} * 1.2)`,
paddingRight: `calc(${theme.spacing(1)} * 1.2)`,
whiteSpace: 'nowrap',
variants: [{
props: {
orientation: 'vertical'
},
style: {
paddingTop: `calc(${theme.spacing(1)} * 1.2)`,
paddingBottom: `calc(${theme.spacing(1)} * 1.2)`
}
}]
})));
const Divider = /*#__PURE__*/reactExports.forwardRef(function Divider(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiDivider'
});
const {
absolute = false,
children,
className,
orientation = 'horizontal',
component = children || orientation === 'vertical' ? 'div' : 'hr',
flexItem = false,
light = false,
role = component !== 'hr' ? 'separator' : undefined,
textAlign = 'center',
variant = 'fullWidth',
...other
} = props;
const ownerState = {
...props,
absolute,
component,
flexItem,
light,
orientation,
role,
textAlign,
variant
};
const classes = useUtilityClasses$d(ownerState);
return /*#__PURE__*/jsxRuntimeExports.jsx(DividerRoot, {
as: component,
className: clsx(classes.root, className),
role: role,
ref: ref,
ownerState: ownerState,
"aria-orientation": role === 'separator' && (component !== 'hr' || orientation === 'vertical') ? orientation : undefined,
...other,
children: children ? /*#__PURE__*/jsxRuntimeExports.jsx(DividerWrapper, {
className: classes.wrapper,
ownerState: ownerState,
children: children
}) : null
});
});
/**
* The following flag is used to ensure that this component isn't tabbable i.e.
* does not get highlight/focus inside of MUI List.
*/
if (Divider) {
Divider.muiSkipListHighlight = true;
}
function getFormControlLabelUtilityClasses(slot) {
return generateUtilityClass('MuiFormControlLabel', slot);
}
const formControlLabelClasses = generateUtilityClasses('MuiFormControlLabel', ['root', 'labelPlacementStart', 'labelPlacementTop', 'labelPlacementBottom', 'disabled', 'label', 'error', 'required', 'asterisk']);
const useUtilityClasses$c = ownerState => {
const {
classes,
disabled,
labelPlacement,
error,
required
} = ownerState;
const slots = {
root: ['root', disabled && 'disabled', `labelPlacement${capitalize(labelPlacement)}`, error && 'error', required && 'required'],
label: ['label', disabled && 'disabled'],
asterisk: ['asterisk', error && 'error']
};
return composeClasses(slots, getFormControlLabelUtilityClasses, classes);
};
const FormControlLabelRoot = styled('label', {
name: 'MuiFormControlLabel',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [{
[`& .${formControlLabelClasses.label}`]: styles.label
}, styles.root, styles[`labelPlacement${capitalize(ownerState.labelPlacement)}`]];
}
})(memoTheme(({
theme
}) => ({
display: 'inline-flex',
alignItems: 'center',
cursor: 'pointer',
// For correct alignment with the text.
verticalAlign: 'middle',
WebkitTapHighlightColor: 'transparent',
marginLeft: -11,
marginRight: 16,
// used for row presentation of radio/checkbox
[`&.${formControlLabelClasses.disabled}`]: {
cursor: 'default'
},
[`& .${formControlLabelClasses.label}`]: {
[`&.${formControlLabelClasses.disabled}`]: {
color: (theme.vars || theme).palette.text.disabled
}
},
variants: [{
props: {
labelPlacement: 'start'
},
style: {
flexDirection: 'row-reverse',
marginRight: -11
}
}, {
props: {
labelPlacement: 'top'
},
style: {
flexDirection: 'column-reverse'
}
}, {
props: {
labelPlacement: 'bottom'
},
style: {
flexDirection: 'column'
}
}, {
props: ({
labelPlacement
}) => labelPlacement === 'start' || labelPlacement === 'top' || labelPlacement === 'bottom',
style: {
marginLeft: 16 // used for row presentation of radio/checkbox
}
}]
})));
const AsteriskComponent = styled('span', {
name: 'MuiFormControlLabel',
slot: 'Asterisk',
overridesResolver: (props, styles) => styles.asterisk
})(memoTheme(({
theme
}) => ({
[`&.${formControlLabelClasses.error}`]: {
color: (theme.vars || theme).palette.error.main
}
})));
/**
* Drop-in replacement of the `Radio`, `Switch` and `Checkbox` component.
* Use this component if you want to display an extra label.
*/
const FormControlLabel = /*#__PURE__*/reactExports.forwardRef(function FormControlLabel(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiFormControlLabel'
});
const {
checked,
className,
componentsProps = {},
control,
disabled: disabledProp,
disableTypography,
inputRef,
label: labelProp,
labelPlacement = 'end',
name,
onChange,
required: requiredProp,
slots = {},
slotProps = {},
value,
...other
} = props;
const muiFormControl = useFormControl();
const disabled = disabledProp ?? control.props.disabled ?? muiFormControl?.disabled;
const required = requiredProp ?? control.props.required;
const controlProps = {
disabled,
required
};
['checked', 'name', 'onChange', 'value', 'inputRef'].forEach(key => {
if (typeof control.props[key] === 'undefined' && typeof props[key] !== 'undefined') {
controlProps[key] = props[key];
}
});
const fcs = formControlState({
props,
muiFormControl,
states: ['error']
});
const ownerState = {
...props,
disabled,
labelPlacement,
required,
error: fcs.error
};
const classes = useUtilityClasses$c(ownerState);
const externalForwardedProps = {
slots,
slotProps: {
...componentsProps,
...slotProps
}
};
const [TypographySlot, typographySlotProps] = useSlot('typography', {
elementType: Typography,
externalForwardedProps,
ownerState
});
let label = labelProp;
if (label != null && label.type !== Typography && !disableTypography) {
label = /*#__PURE__*/jsxRuntimeExports.jsx(TypographySlot, {
component: "span",
...typographySlotProps,
className: clsx(classes.label, typographySlotProps?.className),
children: label
});
}
return /*#__PURE__*/jsxRuntimeExports.jsxs(FormControlLabelRoot, {
className: clsx(classes.root, className),
ownerState: ownerState,
ref: ref,
...other,
children: [/*#__PURE__*/reactExports.cloneElement(control, controlProps), required ? /*#__PURE__*/jsxRuntimeExports.jsxs("div", {
children: [label, /*#__PURE__*/jsxRuntimeExports.jsxs(AsteriskComponent, {
ownerState: ownerState,
"aria-hidden": true,
className: classes.asterisk,
children: ["\u2009", '*']
})]
}) : label]
});
});
/**
* @ignore - internal component.
*/
const GridContext = /*#__PURE__*/reactExports.createContext();
function getGridUtilityClass(slot) {
return generateUtilityClass('MuiGrid', slot);
}
const SPACINGS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const DIRECTIONS = ['column-reverse', 'column', 'row-reverse', 'row'];
const WRAPS = ['nowrap', 'wrap-reverse', 'wrap'];
const GRID_SIZES = ['auto', true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
const gridClasses = generateUtilityClasses('MuiGrid', ['root', 'container', 'item', 'zeroMinWidth',
// spacings
...SPACINGS.map(spacing => `spacing-xs-${spacing}`),
// direction values
...DIRECTIONS.map(direction => `direction-xs-${direction}`),
// wrap values
...WRAPS.map(wrap => `wrap-xs-${wrap}`),
// grid sizes for all breakpoints
...GRID_SIZES.map(size => `grid-xs-${size}`), ...GRID_SIZES.map(size => `grid-sm-${size}`), ...GRID_SIZES.map(size => `grid-md-${size}`), ...GRID_SIZES.map(size => `grid-lg-${size}`), ...GRID_SIZES.map(size => `grid-xl-${size}`)]);
function generateGrid({
theme,
ownerState
}) {
let size;
return theme.breakpoints.keys.reduce((globalStyles, breakpoint) => {
// Use side effect over immutability for better performance.
let styles = {};
if (ownerState[breakpoint]) {
size = ownerState[breakpoint];
}
if (!size) {
return globalStyles;
}
if (size === true) {
// For the auto layouting
styles = {
flexBasis: 0,
flexGrow: 1,
maxWidth: '100%'
};
} else if (size === 'auto') {
styles = {
flexBasis: 'auto',
flexGrow: 0,
flexShrink: 0,
maxWidth: 'none',
width: 'auto'
};
} else {
const columnsBreakpointValues = resolveBreakpointValues({
values: ownerState.columns,
breakpoints: theme.breakpoints.values
});
const columnValue = typeof columnsBreakpointValues === 'object' ? columnsBreakpointValues[breakpoint] : columnsBreakpointValues;
if (columnValue === undefined || columnValue === null) {
return globalStyles;
}
// Keep 7 significant numbers.
const width = `${Math.round(size / columnValue * 10e7) / 10e5}%`;
let more = {};
if (ownerState.container && ownerState.item && ownerState.columnSpacing !== 0) {
const themeSpacing = theme.spacing(ownerState.columnSpacing);
if (themeSpacing !== '0px') {
const fullWidth = `calc(${width} + ${themeSpacing})`;
more = {
flexBasis: fullWidth,
maxWidth: fullWidth
};
}
}
// Close to the bootstrap implementation:
// https://github.com/twbs/bootstrap/blob/8fccaa2439e97ec72a4b7dc42ccc1f649790adb0/scss/mixins/_grid.scss#L41
styles = {
flexBasis: width,
flexGrow: 0,
maxWidth: width,
...more
};
}
// No need for a media query for the first size.
if (theme.breakpoints.values[breakpoint] === 0) {
Object.assign(globalStyles, styles);
} else {
globalStyles[theme.breakpoints.up(breakpoint)] = styles;
}
return globalStyles;
}, {});
}
function generateDirection({
theme,
ownerState
}) {
const directionValues = resolveBreakpointValues({
values: ownerState.direction,
breakpoints: theme.breakpoints.values
});
return handleBreakpoints({
theme
}, directionValues, propValue => {
const output = {
flexDirection: propValue
};
if (propValue.startsWith('column')) {
output[`& > .${gridClasses.item}`] = {
maxWidth: 'none'
};
}
return output;
});
}
/**
* Extracts zero value breakpoint keys before a non-zero value breakpoint key.
* @example { xs: 0, sm: 0, md: 2, lg: 0, xl: 0 } or [0, 0, 2, 0, 0]
* @returns [xs, sm]
*/
function extractZeroValueBreakpointKeys({
breakpoints,
values
}) {
let nonZeroKey = '';
Object.keys(values).forEach(key => {
if (nonZeroKey !== '') {
return;
}
if (values[key] !== 0) {
nonZeroKey = key;
}
});
const sortedBreakpointKeysByValue = Object.keys(breakpoints).sort((a, b) => {
return breakpoints[a] - breakpoints[b];
});
return sortedBreakpointKeysByValue.slice(0, sortedBreakpointKeysByValue.indexOf(nonZeroKey));
}
function generateRowGap({
theme,
ownerState
}) {
const {
container,
rowSpacing
} = ownerState;
let styles = {};
if (container && rowSpacing !== 0) {
const rowSpacingValues = resolveBreakpointValues({
values: rowSpacing,
breakpoints: theme.breakpoints.values
});
let zeroValueBreakpointKeys;
if (typeof rowSpacingValues === 'object') {
zeroValueBreakpointKeys = extractZeroValueBreakpointKeys({
breakpoints: theme.breakpoints.values,
values: rowSpacingValues
});
}
styles = handleBreakpoints({
theme
}, rowSpacingValues, (propValue, breakpoint) => {
const themeSpacing = theme.spacing(propValue);
if (themeSpacing !== '0px') {
return {
marginTop: `calc(-1 * ${themeSpacing})`,
[`& > .${gridClasses.item}`]: {
paddingTop: themeSpacing
}
};
}
if (zeroValueBreakpointKeys?.includes(breakpoint)) {
return {};
}
return {
marginTop: 0,
[`& > .${gridClasses.item}`]: {
paddingTop: 0
}
};
});
}
return styles;
}
function generateColumnGap({
theme,
ownerState
}) {
const {
container,
columnSpacing
} = ownerState;
let styles = {};
if (container && columnSpacing !== 0) {
const columnSpacingValues = resolveBreakpointValues({
values: columnSpacing,
breakpoints: theme.breakpoints.values
});
let zeroValueBreakpointKeys;
if (typeof columnSpacingValues === 'object') {
zeroValueBreakpointKeys = extractZeroValueBreakpointKeys({
breakpoints: theme.breakpoints.values,
values: columnSpacingValues
});
}
styles = handleBreakpoints({
theme
}, columnSpacingValues, (propValue, breakpoint) => {
const themeSpacing = theme.spacing(propValue);
if (themeSpacing !== '0px') {
const negativeValue = `calc(-1 * ${themeSpacing})`;
return {
width: `calc(100% + ${themeSpacing})`,
marginLeft: negativeValue,
[`& > .${gridClasses.item}`]: {
paddingLeft: themeSpacing
}
};
}
if (zeroValueBreakpointKeys?.includes(breakpoint)) {
return {};
}
return {
width: '100%',
marginLeft: 0,
[`& > .${gridClasses.item}`]: {
paddingLeft: 0
}
};
});
}
return styles;
}
function resolveSpacingStyles(spacing, breakpoints, styles = {}) {
// undefined/null or `spacing` <= 0
if (!spacing || spacing <= 0) {
return [];
}
// in case of string/number `spacing`
if (typeof spacing === 'string' && !Number.isNaN(Number(spacing)) || typeof spacing === 'number') {
return [styles[`spacing-xs-${String(spacing)}`]];
}
// in case of object `spacing`
const spacingStyles = [];
breakpoints.forEach(breakpoint => {
const value = spacing[breakpoint];
if (Number(value) > 0) {
spacingStyles.push(styles[`spacing-${breakpoint}-${String(value)}`]);
}
});
return spacingStyles;
}
// Default CSS values
// flex: '0 1 auto',
// flexDirection: 'row',
// alignItems: 'flex-start',
// flexWrap: 'nowrap',
// justifyContent: 'flex-start',
const GridRoot = styled('div', {
name: 'MuiGrid',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
const {
container,
direction,
item,
spacing,
wrap,
zeroMinWidth,
breakpoints
} = ownerState;
let spacingStyles = [];
// in case of grid item
if (container) {
spacingStyles = resolveSpacingStyles(spacing, breakpoints, styles);
}
const breakpointsStyles = [];
breakpoints.forEach(breakpoint => {
const value = ownerState[breakpoint];
if (value) {
breakpointsStyles.push(styles[`grid-${breakpoint}-${String(value)}`]);
}
});
return [styles.root, container && styles.container, item && styles.item, zeroMinWidth && styles.zeroMinWidth, ...spacingStyles, direction !== 'row' && styles[`direction-xs-${String(direction)}`], wrap !== 'wrap' && styles[`wrap-xs-${String(wrap)}`], ...breakpointsStyles];
}
})(
// FIXME(romgrk): Can't use memoTheme here
({
ownerState
}) => ({
boxSizing: 'border-box',
...(ownerState.container && {
display: 'flex',
flexWrap: 'wrap',
width: '100%'
}),
...(ownerState.item && {
margin: 0 // For instance, it's useful when used with a `figure` element.
}),
...(ownerState.zeroMinWidth && {
minWidth: 0
}),
...(ownerState.wrap !== 'wrap' && {
flexWrap: ownerState.wrap
})
}), generateDirection, generateRowGap, generateColumnGap, generateGrid);
function resolveSpacingClasses(spacing, breakpoints) {
// undefined/null or `spacing` <= 0
if (!spacing || spacing <= 0) {
return [];
}
// in case of string/number `spacing`
if (typeof spacing === 'string' && !Number.isNaN(Number(spacing)) || typeof spacing === 'number') {
return [`spacing-xs-${String(spacing)}`];
}
// in case of object `spacing`
const classes = [];
breakpoints.forEach(breakpoint => {
const value = spacing[breakpoint];
if (Number(value) > 0) {
const className = `spacing-${breakpoint}-${String(value)}`;
classes.push(className);
}
});
return classes;
}
const useUtilityClasses$b = ownerState => {
const {
classes,
container,
direction,
item,
spacing,
wrap,
zeroMinWidth,
breakpoints
} = ownerState;
let spacingClasses = [];
// in case of grid item
if (container) {
spacingClasses = resolveSpacingClasses(spacing, breakpoints);
}
const breakpointsClasses = [];
breakpoints.forEach(breakpoint => {
const value = ownerState[breakpoint];
if (value) {
breakpointsClasses.push(`grid-${breakpoint}-${String(value)}`);
}
});
const slots = {
root: ['root', container && 'container', item && 'item', zeroMinWidth && 'zeroMinWidth', ...spacingClasses, direction !== 'row' && `direction-xs-${String(direction)}`, wrap !== 'wrap' && `wrap-xs-${String(wrap)}`, ...breakpointsClasses]
};
return composeClasses(slots, getGridUtilityClass, classes);
};
/**
* @deprecated Use the [`Grid2`](https://mui.com/material-ui/react-grid2/) component instead.
*/
const Grid = /*#__PURE__*/reactExports.forwardRef(function Grid(inProps, ref) {
const themeProps = useDefaultProps({
props: inProps,
name: 'MuiGrid'
});
const {
breakpoints
} = useTheme$1();
const props = extendSxProp$1(themeProps);
const {
className,
columns: columnsProp,
columnSpacing: columnSpacingProp,
component = 'div',
container = false,
direction = 'row',
item = false,
rowSpacing: rowSpacingProp,
spacing = 0,
wrap = 'wrap',
zeroMinWidth = false,
...other
} = props;
const rowSpacing = rowSpacingProp || spacing;
const columnSpacing = columnSpacingProp || spacing;
const columnsContext = reactExports.useContext(GridContext);
// columns set with default breakpoint unit of 12
const columns = container ? columnsProp || 12 : columnsContext;
const breakpointsValues = {};
const otherFiltered = {
...other
};
breakpoints.keys.forEach(breakpoint => {
if (other[breakpoint] != null) {
breakpointsValues[breakpoint] = other[breakpoint];
delete otherFiltered[breakpoint];
}
});
const ownerState = {
...props,
columns,
container,
direction,
item,
rowSpacing,
columnSpacing,
wrap,
zeroMinWidth,
spacing,
...breakpointsValues,
breakpoints: breakpoints.keys
};
const classes = useUtilityClasses$b(ownerState);
return /*#__PURE__*/jsxRuntimeExports.jsx(GridContext.Provider, {
value: columns,
children: /*#__PURE__*/jsxRuntimeExports.jsx(GridRoot, {
ownerState: ownerState,
className: clsx(classes.root, className),
as: component,
ref: ref,
...otherFiltered
})
});
});
function getScale(value) {
return `scale(${value}, ${value ** 2})`;
}
const styles = {
entering: {
opacity: 1,
transform: getScale(1)
},
entered: {
opacity: 1,
transform: 'none'
}
};
/*
TODO v6: remove
Conditionally apply a workaround for the CSS transition bug in Safari 15.4 / WebKit browsers.
*/
const isWebKit154 = typeof navigator !== 'undefined' && /^((?!chrome|android).)*(safari|mobile)/i.test(navigator.userAgent) && /(os |version\/)15(.|_)4/i.test(navigator.userAgent);
/**
* The Grow transition is used by the [Tooltip](/material-ui/react-tooltip/) and
* [Popover](/material-ui/react-popover/) components.
* It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.
*/
const Grow = /*#__PURE__*/reactExports.forwardRef(function Grow(props, ref) {
const {
addEndListener,
appear = true,
children,
easing,
in: inProp,
onEnter,
onEntered,
onEntering,
onExit,
onExited,
onExiting,
style,
timeout = 'auto',
// eslint-disable-next-line react/prop-types
TransitionComponent = Transition,
...other
} = props;
const timer = useTimeout();
const autoTimeout = reactExports.useRef();
const theme = useTheme$1();
const nodeRef = reactExports.useRef(null);
const handleRef = useForkRef(nodeRef, getReactElementRef(children), ref);
const normalizedTransitionCallback = callback => maybeIsAppearing => {
if (callback) {
const node = nodeRef.current;
// onEnterXxx and onExitXxx callbacks have a different arguments.length value.
if (maybeIsAppearing === undefined) {
callback(node);
} else {
callback(node, maybeIsAppearing);
}
}
};
const handleEntering = normalizedTransitionCallback(onEntering);
const handleEnter = normalizedTransitionCallback((node, isAppearing) => {
reflow(node); // So the animation always start from the start.
const {
duration: transitionDuration,
delay,
easing: transitionTimingFunction
} = getTransitionProps({
style,
timeout,
easing
}, {
mode: 'enter'
});
let duration;
if (timeout === 'auto') {
duration = theme.transitions.getAutoHeightDuration(node.clientHeight);
autoTimeout.current = duration;
} else {
duration = transitionDuration;
}
node.style.transition = [theme.transitions.create('opacity', {
duration,
delay
}), theme.transitions.create('transform', {
duration: isWebKit154 ? duration : duration * 0.666,
delay,
easing: transitionTimingFunction
})].join(',');
if (onEnter) {
onEnter(node, isAppearing);
}
});
const handleEntered = normalizedTransitionCallback(onEntered);
const handleExiting = normalizedTransitionCallback(onExiting);
const handleExit = normalizedTransitionCallback(node => {
const {
duration: transitionDuration,
delay,
easing: transitionTimingFunction
} = getTransitionProps({
style,
timeout,
easing
}, {
mode: 'exit'
});
let duration;
if (timeout === 'auto') {
duration = theme.transitions.getAutoHeightDuration(node.clientHeight);
autoTimeout.current = duration;
} else {
duration = transitionDuration;
}
node.style.transition = [theme.transitions.create('opacity', {
duration,
delay
}), theme.transitions.create('transform', {
duration: isWebKit154 ? duration : duration * 0.666,
delay: isWebKit154 ? delay : delay || duration * 0.333,
easing: transitionTimingFunction
})].join(',');
node.style.opacity = 0;
node.style.transform = getScale(0.75);
if (onExit) {
onExit(node);
}
});
const handleExited = normalizedTransitionCallback(onExited);
const handleAddEndListener = next => {
if (timeout === 'auto') {
timer.start(autoTimeout.current || 0, next);
}
if (addEndListener) {
// Old call signature before `react-transition-group` implemented `nodeRef`
addEndListener(nodeRef.current, next);
}
};
return /*#__PURE__*/jsxRuntimeExports.jsx(TransitionComponent, {
appear: appear,
in: inProp,
nodeRef: nodeRef,
onEnter: handleEnter,
onEntered: handleEntered,
onEntering: handleEntering,
onExit: handleExit,
onExited: handleExited,
onExiting: handleExiting,
addEndListener: handleAddEndListener,
timeout: timeout === 'auto' ? null : timeout,
...other,
children: (state, {
ownerState,
...restChildProps
}) => {
return /*#__PURE__*/reactExports.cloneElement(children, {
style: {
opacity: 0,
transform: getScale(0.75),
visibility: state === 'exited' && !inProp ? 'hidden' : undefined,
...styles[state],
...style,
...children.props.style
},
ref: handleRef,
...restChildProps
});
}
});
});
if (Grow) {
Grow.muiSupportAuto = true;
}
function getIconUtilityClass(slot) {
return generateUtilityClass('MuiIcon', slot);
}
generateUtilityClasses('MuiIcon', ['root', 'colorPrimary', 'colorSecondary', 'colorAction', 'colorError', 'colorDisabled', 'fontSizeInherit', 'fontSizeSmall', 'fontSizeMedium', 'fontSizeLarge']);
const useUtilityClasses$a = ownerState => {
const {
color,
fontSize,
classes
} = ownerState;
const slots = {
root: ['root', color !== 'inherit' && `color${capitalize(color)}`, `fontSize${capitalize(fontSize)}`]
};
return composeClasses(slots, getIconUtilityClass, classes);
};
const IconRoot = styled('span', {
name: 'MuiIcon',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, ownerState.color !== 'inherit' && styles[`color${capitalize(ownerState.color)}`], styles[`fontSize${capitalize(ownerState.fontSize)}`]];
}
})(memoTheme(({
theme
}) => ({
userSelect: 'none',
width: '1em',
height: '1em',
// Chrome fix for https://issues.chromium.org/issues/41375697
// To remove at some point.
overflow: 'hidden',
display: 'inline-block',
// allow overflow hidden to take action
textAlign: 'center',
// support non-square icon
flexShrink: 0,
variants: [{
props: {
fontSize: 'inherit'
},
style: {
fontSize: 'inherit'
}
}, {
props: {
fontSize: 'small'
},
style: {
fontSize: theme.typography.pxToRem(20)
}
}, {
props: {
fontSize: 'medium'
},
style: {
fontSize: theme.typography.pxToRem(24)
}
}, {
props: {
fontSize: 'large'
},
style: {
fontSize: theme.typography.pxToRem(36)
}
}, {
props: {
color: 'action'
},
style: {
color: (theme.vars || theme).palette.action.active
}
}, {
props: {
color: 'disabled'
},
style: {
color: (theme.vars || theme).palette.action.disabled
}
}, {
props: {
color: 'inherit'
},
style: {
color: undefined
}
}, ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()).map(([color]) => ({
props: {
color
},
style: {
color: (theme.vars || theme).palette[color].main
}
}))]
})));
const Icon = /*#__PURE__*/reactExports.forwardRef(function Icon(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiIcon'
});
const {
baseClassName = 'material-icons',
className,
color = 'inherit',
component: Component = 'span',
fontSize = 'medium',
...other
} = props;
const ownerState = {
...props,
baseClassName,
color,
component: Component,
fontSize
};
const classes = useUtilityClasses$a(ownerState);
return /*#__PURE__*/jsxRuntimeExports.jsx(IconRoot, {
as: Component,
className: clsx(baseClassName,
// Prevent the translation of the text content.
// The font relies on the exact text content to render the icon.
'notranslate', classes.root, className),
ownerState: ownerState,
"aria-hidden": true,
ref: ref,
...other
});
});
Icon.muiName = 'Icon';
function getInputAdornmentUtilityClass(slot) {
return generateUtilityClass('MuiInputAdornment', slot);
}
const inputAdornmentClasses = generateUtilityClasses('MuiInputAdornment', ['root', 'filled', 'standard', 'outlined', 'positionStart', 'positionEnd', 'disablePointerEvents', 'hiddenLabel', 'sizeSmall']);
var _span$1;
const overridesResolver$2 = (props, styles) => {
const {
ownerState
} = props;
return [styles.root, styles[`position${capitalize(ownerState.position)}`], ownerState.disablePointerEvents === true && styles.disablePointerEvents, styles[ownerState.variant]];
};
const useUtilityClasses$9 = ownerState => {
const {
classes,
disablePointerEvents,
hiddenLabel,
position,
size,
variant
} = ownerState;
const slots = {
root: ['root', disablePointerEvents && 'disablePointerEvents', position && `position${capitalize(position)}`, variant, hiddenLabel && 'hiddenLabel', size && `size${capitalize(size)}`]
};
return composeClasses(slots, getInputAdornmentUtilityClass, classes);
};
const InputAdornmentRoot = styled('div', {
name: 'MuiInputAdornment',
slot: 'Root',
overridesResolver: overridesResolver$2
})(memoTheme(({
theme
}) => ({
display: 'flex',
maxHeight: '2em',
alignItems: 'center',
whiteSpace: 'nowrap',
color: (theme.vars || theme).palette.action.active,
variants: [{
props: {
variant: 'filled'
},
style: {
[`&.${inputAdornmentClasses.positionStart}&:not(.${inputAdornmentClasses.hiddenLabel})`]: {
marginTop: 16
}
}
}, {
props: {
position: 'start'
},
style: {
marginRight: 8
}
}, {
props: {
position: 'end'
},
style: {
marginLeft: 8
}
}, {
props: {
disablePointerEvents: true
},
style: {
pointerEvents: 'none'
}
}]
})));
const InputAdornment = /*#__PURE__*/reactExports.forwardRef(function InputAdornment(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiInputAdornment'
});
const {
children,
className,
component = 'div',
disablePointerEvents = false,
disableTypography = false,
position,
variant: variantProp,
...other
} = props;
const muiFormControl = useFormControl() || {};
let variant = variantProp;
if (variantProp && muiFormControl.variant) ;
if (muiFormControl && !variant) {
variant = muiFormControl.variant;
}
const ownerState = {
...props,
hiddenLabel: muiFormControl.hiddenLabel,
size: muiFormControl.size,
disablePointerEvents,
position,
variant
};
const classes = useUtilityClasses$9(ownerState);
return /*#__PURE__*/jsxRuntimeExports.jsx(FormControlContext.Provider, {
value: null,
children: /*#__PURE__*/jsxRuntimeExports.jsx(InputAdornmentRoot, {
as: component,
ownerState: ownerState,
className: clsx(classes.root, className),
ref: ref,
...other,
children: typeof children === 'string' && !disableTypography ? /*#__PURE__*/jsxRuntimeExports.jsx(Typography, {
color: "textSecondary",
children: children
}) : /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports.Fragment, {
children: [position === 'start' ? (/* notranslate needed while Google Translate will not fix zero-width space issue */_span$1 || (_span$1 = /*#__PURE__*/jsxRuntimeExports.jsx("span", {
className: "notranslate",
"aria-hidden": true,
children: "\u200B"
}))) : null, children]
})
})
});
});
/**
* @ignore - internal component.
*/
const ListContext = /*#__PURE__*/reactExports.createContext({});
function getListUtilityClass(slot) {
return generateUtilityClass('MuiList', slot);
}
generateUtilityClasses('MuiList', ['root', 'padding', 'dense', 'subheader']);
const useUtilityClasses$8 = ownerState => {
const {
classes,
disablePadding,
dense,
subheader
} = ownerState;
const slots = {
root: ['root', !disablePadding && 'padding', dense && 'dense', subheader && 'subheader']
};
return composeClasses(slots, getListUtilityClass, classes);
};
const ListRoot = styled('ul', {
name: 'MuiList',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, !ownerState.disablePadding && styles.padding, ownerState.dense && styles.dense, ownerState.subheader && styles.subheader];
}
})({
listStyle: 'none',
margin: 0,
padding: 0,
position: 'relative',
variants: [{
props: ({
ownerState
}) => !ownerState.disablePadding,
style: {
paddingTop: 8,
paddingBottom: 8
}
}, {
props: ({
ownerState
}) => ownerState.subheader,
style: {
paddingTop: 0
}
}]
});
const List = /*#__PURE__*/reactExports.forwardRef(function List(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiList'
});
const {
children,
className,
component = 'ul',
dense = false,
disablePadding = false,
subheader,
...other
} = props;
const context = reactExports.useMemo(() => ({
dense
}), [dense]);
const ownerState = {
...props,
component,
dense,
disablePadding
};
const classes = useUtilityClasses$8(ownerState);
return /*#__PURE__*/jsxRuntimeExports.jsx(ListContext.Provider, {
value: context,
children: /*#__PURE__*/jsxRuntimeExports.jsxs(ListRoot, {
as: component,
className: clsx(classes.root, className),
ref: ref,
ownerState: ownerState,
...other,
children: [subheader, children]
})
});
});
function getListItemUtilityClass(slot) {
return generateUtilityClass('MuiListItem', slot);
}
generateUtilityClasses('MuiListItem', ['root', 'container', 'dense', 'alignItemsFlexStart', 'divider', 'gutters', 'padding', 'secondaryAction']);
const listItemButtonClasses = generateUtilityClasses('MuiListItemButton', ['root', 'focusVisible', 'dense', 'alignItemsFlexStart', 'disabled', 'divider', 'gutters', 'selected']);
function getListItemSecondaryActionClassesUtilityClass(slot) {
return generateUtilityClass('MuiListItemSecondaryAction', slot);
}
generateUtilityClasses('MuiListItemSecondaryAction', ['root', 'disableGutters']);
const useUtilityClasses$7 = ownerState => {
const {
disableGutters,
classes
} = ownerState;
const slots = {
root: ['root', disableGutters && 'disableGutters']
};
return composeClasses(slots, getListItemSecondaryActionClassesUtilityClass, classes);
};
const ListItemSecondaryActionRoot = styled('div', {
name: 'MuiListItemSecondaryAction',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, ownerState.disableGutters && styles.disableGutters];
}
})({
position: 'absolute',
right: 16,
top: '50%',
transform: 'translateY(-50%)',
variants: [{
props: ({
ownerState
}) => ownerState.disableGutters,
style: {
right: 0
}
}]
});
/**
* Must be used as the last child of ListItem to function properly.
*
* @deprecated Use the `secondaryAction` prop in the `ListItem` component instead. This component will be removed in v7. See [Migrating from deprecated APIs](https://mui.com/material-ui/migration/migrating-from-deprecated-apis/) for more details.
*/
const ListItemSecondaryAction = /*#__PURE__*/reactExports.forwardRef(function ListItemSecondaryAction(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiListItemSecondaryAction'
});
const {
className,
...other
} = props;
const context = reactExports.useContext(ListContext);
const ownerState = {
...props,
disableGutters: context.disableGutters
};
const classes = useUtilityClasses$7(ownerState);
return /*#__PURE__*/jsxRuntimeExports.jsx(ListItemSecondaryActionRoot, {
className: clsx(classes.root, className),
ownerState: ownerState,
ref: ref,
...other
});
});
ListItemSecondaryAction.muiName = 'ListItemSecondaryAction';
const overridesResolver$1 = (props, styles) => {
const {
ownerState
} = props;
return [styles.root, ownerState.dense && styles.dense, ownerState.alignItems === 'flex-start' && styles.alignItemsFlexStart, ownerState.divider && styles.divider, !ownerState.disableGutters && styles.gutters, !ownerState.disablePadding && styles.padding, ownerState.hasSecondaryAction && styles.secondaryAction];
};
const useUtilityClasses$6 = ownerState => {
const {
alignItems,
classes,
dense,
disableGutters,
disablePadding,
divider,
hasSecondaryAction
} = ownerState;
const slots = {
root: ['root', dense && 'dense', !disableGutters && 'gutters', !disablePadding && 'padding', divider && 'divider', alignItems === 'flex-start' && 'alignItemsFlexStart', hasSecondaryAction && 'secondaryAction'],
container: ['container']
};
return composeClasses(slots, getListItemUtilityClass, classes);
};
const ListItemRoot = styled('div', {
name: 'MuiListItem',
slot: 'Root',
overridesResolver: overridesResolver$1
})(memoTheme(({
theme
}) => ({
display: 'flex',
justifyContent: 'flex-start',
alignItems: 'center',
position: 'relative',
textDecoration: 'none',
width: '100%',
boxSizing: 'border-box',
textAlign: 'left',
variants: [{
props: ({
ownerState
}) => !ownerState.disablePadding,
style: {
paddingTop: 8,
paddingBottom: 8
}
}, {
props: ({
ownerState
}) => !ownerState.disablePadding && ownerState.dense,
style: {
paddingTop: 4,
paddingBottom: 4
}
}, {
props: ({
ownerState
}) => !ownerState.disablePadding && !ownerState.disableGutters,
style: {
paddingLeft: 16,
paddingRight: 16
}
}, {
props: ({
ownerState
}) => !ownerState.disablePadding && !!ownerState.secondaryAction,
style: {
// Add some space to avoid collision as `ListItemSecondaryAction`
// is absolutely positioned.
paddingRight: 48
}
}, {
props: ({
ownerState
}) => !!ownerState.secondaryAction,
style: {
[`& > .${listItemButtonClasses.root}`]: {
paddingRight: 48
}
}
}, {
props: {
alignItems: 'flex-start'
},
style: {
alignItems: 'flex-start'
}
}, {
props: ({
ownerState
}) => ownerState.divider,
style: {
borderBottom: `1px solid ${(theme.vars || theme).palette.divider}`,
backgroundClip: 'padding-box'
}
}, {
props: ({
ownerState
}) => ownerState.button,
style: {
transition: theme.transitions.create('background-color', {
duration: theme.transitions.duration.shortest
}),
'&:hover': {
textDecoration: 'none',
backgroundColor: (theme.vars || theme).palette.action.hover,
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
}
}, {
props: ({
ownerState
}) => ownerState.hasSecondaryAction,
style: {
// Add some space to avoid collision as `ListItemSecondaryAction`
// is absolutely positioned.
paddingRight: 48
}
}]
})));
const ListItemContainer = styled('li', {
name: 'MuiListItem',
slot: 'Container',
overridesResolver: (props, styles) => styles.container
})({
position: 'relative'
});
/**
* Uses an additional container component if `ListItemSecondaryAction` is the last child.
*/
const ListItem = /*#__PURE__*/reactExports.forwardRef(function ListItem(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiListItem'
});
const {
alignItems = 'center',
children: childrenProp,
className,
component: componentProp,
components = {},
componentsProps = {},
ContainerComponent = 'li',
ContainerProps: {
className: ContainerClassName,
...ContainerProps
} = {},
dense = false,
disableGutters = false,
disablePadding = false,
divider = false,
secondaryAction,
slotProps = {},
slots = {},
...other
} = props;
const context = reactExports.useContext(ListContext);
const childContext = reactExports.useMemo(() => ({
dense: dense || context.dense || false,
alignItems,
disableGutters
}), [alignItems, context.dense, dense, disableGutters]);
const listItemRef = reactExports.useRef(null);
const children = reactExports.Children.toArray(childrenProp);
// v4 implementation, deprecated in v6, will be removed in v7
const hasSecondaryAction = children.length && isMuiElement(children[children.length - 1], ['ListItemSecondaryAction']);
const ownerState = {
...props,
alignItems,
dense: childContext.dense,
disableGutters,
disablePadding,
divider,
hasSecondaryAction
};
const classes = useUtilityClasses$6(ownerState);
const handleRef = useForkRef(listItemRef, ref);
const Root = slots.root || components.Root || ListItemRoot;
const rootProps = slotProps.root || componentsProps.root || {};
const componentProps = {
className: clsx(classes.root, rootProps.className, className),
...other
};
let Component = componentProp || 'li';
// v4 implementation, deprecated in v6, will be removed in v7
if (hasSecondaryAction) {
// Use div by default.
Component = !componentProps.component && !componentProp ? 'div' : Component;
// Avoid nesting of li > li.
if (ContainerComponent === 'li') {
if (Component === 'li') {
Component = 'div';
} else if (componentProps.component === 'li') {
componentProps.component = 'div';
}
}
return /*#__PURE__*/jsxRuntimeExports.jsx(ListContext.Provider, {
value: childContext,
children: /*#__PURE__*/jsxRuntimeExports.jsxs(ListItemContainer, {
as: ContainerComponent,
className: clsx(classes.container, ContainerClassName),
ref: handleRef,
ownerState: ownerState,
...ContainerProps,
children: [/*#__PURE__*/jsxRuntimeExports.jsx(Root, {
...rootProps,
...(!isHostComponent(Root) && {
as: Component,
ownerState: {
...ownerState,
...rootProps.ownerState
}
}),
...componentProps,
children: children
}), children.pop()]
})
});
}
return /*#__PURE__*/jsxRuntimeExports.jsx(ListContext.Provider, {
value: childContext,
children: /*#__PURE__*/jsxRuntimeExports.jsxs(Root, {
...rootProps,
as: Component,
ref: handleRef,
...(!isHostComponent(Root) && {
ownerState: {
...ownerState,
...rootProps.ownerState
}
}),
...componentProps,
children: [children, secondaryAction && /*#__PURE__*/jsxRuntimeExports.jsx(ListItemSecondaryAction, {
children: secondaryAction
})]
})
});
});
function getListItemIconUtilityClass(slot) {
return generateUtilityClass('MuiListItemIcon', slot);
}
const listItemIconClasses = generateUtilityClasses('MuiListItemIcon', ['root', 'alignItemsFlexStart']);
const useUtilityClasses$5 = ownerState => {
const {
alignItems,
classes
} = ownerState;
const slots = {
root: ['root', alignItems === 'flex-start' && 'alignItemsFlexStart']
};
return composeClasses(slots, getListItemIconUtilityClass, classes);
};
const ListItemIconRoot = styled('div', {
name: 'MuiListItemIcon',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, ownerState.alignItems === 'flex-start' && styles.alignItemsFlexStart];
}
})(memoTheme(({
theme
}) => ({
minWidth: 56,
color: (theme.vars || theme).palette.action.active,
flexShrink: 0,
display: 'inline-flex',
variants: [{
props: {
alignItems: 'flex-start'
},
style: {
marginTop: 8
}
}]
})));
/**
* A simple wrapper to apply `List` styles to an `Icon` or `SvgIcon`.
*/
const ListItemIcon = /*#__PURE__*/reactExports.forwardRef(function ListItemIcon(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiListItemIcon'
});
const {
className,
...other
} = props;
const context = reactExports.useContext(ListContext);
const ownerState = {
...props,
alignItems: context.alignItems
};
const classes = useUtilityClasses$5(ownerState);
return /*#__PURE__*/jsxRuntimeExports.jsx(ListItemIconRoot, {
className: clsx(classes.root, className),
ownerState: ownerState,
ref: ref,
...other
});
});
const listItemTextClasses = generateUtilityClasses('MuiListItemText', ['root', 'multiline', 'dense', 'inset', 'primary', 'secondary']);
function nextItem(list, item, disableListWrap) {
if (list === item) {
return list.firstChild;
}
if (item && item.nextElementSibling) {
return item.nextElementSibling;
}
return disableListWrap ? null : list.firstChild;
}
function previousItem(list, item, disableListWrap) {
if (list === item) {
return disableListWrap ? list.firstChild : list.lastChild;
}
if (item && item.previousElementSibling) {
return item.previousElementSibling;
}
return disableListWrap ? null : list.lastChild;
}
function textCriteriaMatches(nextFocus, textCriteria) {
if (textCriteria === undefined) {
return true;
}
let text = nextFocus.innerText;
if (text === undefined) {
// jsdom doesn't support innerText
text = nextFocus.textContent;
}
text = text.trim().toLowerCase();
if (text.length === 0) {
return false;
}
if (textCriteria.repeating) {
return text[0] === textCriteria.keys[0];
}
return text.startsWith(textCriteria.keys.join(''));
}
function moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, traversalFunction, textCriteria) {
let wrappedOnce = false;
let nextFocus = traversalFunction(list, currentFocus, currentFocus ? disableListWrap : false);
while (nextFocus) {
// Prevent infinite loop.
if (nextFocus === list.firstChild) {
if (wrappedOnce) {
return false;
}
wrappedOnce = true;
}
// Same logic as useAutocomplete.js
const nextFocusDisabled = disabledItemsFocusable ? false : nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true';
if (!nextFocus.hasAttribute('tabindex') || !textCriteriaMatches(nextFocus, textCriteria) || nextFocusDisabled) {
// Move to the next element.
nextFocus = traversalFunction(list, nextFocus, disableListWrap);
} else {
nextFocus.focus();
return true;
}
}
return false;
}
/**
* A permanently displayed menu following https://www.w3.org/WAI/ARIA/apg/patterns/menu-button/.
* It's exposed to help customization of the [`Menu`](/material-ui/api/menu/) component if you
* use it separately you need to move focus into the component manually. Once
* the focus is placed inside the component it is fully keyboard accessible.
*/
const MenuList = /*#__PURE__*/reactExports.forwardRef(function MenuList(props, ref) {
const {
// private
// eslint-disable-next-line react/prop-types
actions,
autoFocus = false,
autoFocusItem = false,
children,
className,
disabledItemsFocusable = false,
disableListWrap = false,
onKeyDown,
variant = 'selectedMenu',
...other
} = props;
const listRef = reactExports.useRef(null);
const textCriteriaRef = reactExports.useRef({
keys: [],
repeating: true,
previousKeyMatched: true,
lastTime: null
});
useEnhancedEffect(() => {
if (autoFocus) {
listRef.current.focus();
}
}, [autoFocus]);
reactExports.useImperativeHandle(actions, () => ({
adjustStyleForScrollbar: (containerElement, {
direction
}) => {
// Let's ignore that piece of logic if users are already overriding the width
// of the menu.
const noExplicitWidth = !listRef.current.style.width;
if (containerElement.clientHeight < listRef.current.clientHeight && noExplicitWidth) {
const scrollbarSize = `${getScrollbarSize$1(ownerWindow(containerElement))}px`;
listRef.current.style[direction === 'rtl' ? 'paddingLeft' : 'paddingRight'] = scrollbarSize;
listRef.current.style.width = `calc(100% + ${scrollbarSize})`;
}
return listRef.current;
}
}), []);
const handleKeyDown = event => {
const list = listRef.current;
const key = event.key;
const isModifierKeyPressed = event.ctrlKey || event.metaKey || event.altKey;
if (isModifierKeyPressed) {
if (onKeyDown) {
onKeyDown(event);
}
return;
}
/**
* @type {Element} - will always be defined since we are in a keydown handler
* attached to an element. A keydown event is either dispatched to the activeElement
* or document.body or document.documentElement. Only the first case will
* trigger this specific handler.
*/
const currentFocus = ownerDocument(list).activeElement;
if (key === 'ArrowDown') {
// Prevent scroll of the page
event.preventDefault();
moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, nextItem);
} else if (key === 'ArrowUp') {
event.preventDefault();
moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, previousItem);
} else if (key === 'Home') {
event.preventDefault();
moveFocus(list, null, disableListWrap, disabledItemsFocusable, nextItem);
} else if (key === 'End') {
event.preventDefault();
moveFocus(list, null, disableListWrap, disabledItemsFocusable, previousItem);
} else if (key.length === 1) {
const criteria = textCriteriaRef.current;
const lowerKey = key.toLowerCase();
const currTime = performance.now();
if (criteria.keys.length > 0) {
// Reset
if (currTime - criteria.lastTime > 500) {
criteria.keys = [];
criteria.repeating = true;
criteria.previousKeyMatched = true;
} else if (criteria.repeating && lowerKey !== criteria.keys[0]) {
criteria.repeating = false;
}
}
criteria.lastTime = currTime;
criteria.keys.push(lowerKey);
const keepFocusOnCurrent = currentFocus && !criteria.repeating && textCriteriaMatches(currentFocus, criteria);
if (criteria.previousKeyMatched && (keepFocusOnCurrent || moveFocus(list, currentFocus, false, disabledItemsFocusable, nextItem, criteria))) {
event.preventDefault();
} else {
criteria.previousKeyMatched = false;
}
}
if (onKeyDown) {
onKeyDown(event);
}
};
const handleRef = useForkRef(listRef, ref);
/**
* the index of the item should receive focus
* in a `variant="selectedMenu"` it's the first `selected` item
* otherwise it's the very first item.
*/
let activeItemIndex = -1;
// since we inject focus related props into children we have to do a lookahead
// to check if there is a `selected` item. We're looking for the last `selected`
// item and use the first valid item as a fallback
reactExports.Children.forEach(children, (child, index) => {
if (! /*#__PURE__*/reactExports.isValidElement(child)) {
if (activeItemIndex === index) {
activeItemIndex += 1;
if (activeItemIndex >= children.length) {
// there are no focusable items within the list.
activeItemIndex = -1;
}
}
return;
}
if (!child.props.disabled) {
if (variant === 'selectedMenu' && child.props.selected) {
activeItemIndex = index;
} else if (activeItemIndex === -1) {
activeItemIndex = index;
}
}
if (activeItemIndex === index && (child.props.disabled || child.props.muiSkipListHighlight || child.type.muiSkipListHighlight)) {
activeItemIndex += 1;
if (activeItemIndex >= children.length) {
// there are no focusable items within the list.
activeItemIndex = -1;
}
}
});
const items = reactExports.Children.map(children, (child, index) => {
if (index === activeItemIndex) {
const newChildProps = {};
if (autoFocusItem) {
newChildProps.autoFocus = true;
}
if (child.props.tabIndex === undefined && variant === 'selectedMenu') {
newChildProps.tabIndex = 0;
}
return /*#__PURE__*/reactExports.cloneElement(child, newChildProps);
}
return child;
});
return /*#__PURE__*/jsxRuntimeExports.jsx(List, {
role: "menu",
ref: handleRef,
className: className,
onKeyDown: handleKeyDown,
tabIndex: autoFocus ? 0 : -1,
...other,
children: items
});
});
function getPopoverUtilityClass(slot) {
return generateUtilityClass('MuiPopover', slot);
}
generateUtilityClasses('MuiPopover', ['root', 'paper']);
function getOffsetTop(rect, vertical) {
let offset = 0;
if (typeof vertical === 'number') {
offset = vertical;
} else if (vertical === 'center') {
offset = rect.height / 2;
} else if (vertical === 'bottom') {
offset = rect.height;
}
return offset;
}
function getOffsetLeft(rect, horizontal) {
let offset = 0;
if (typeof horizontal === 'number') {
offset = horizontal;
} else if (horizontal === 'center') {
offset = rect.width / 2;
} else if (horizontal === 'right') {
offset = rect.width;
}
return offset;
}
function getTransformOriginValue(transformOrigin) {
return [transformOrigin.horizontal, transformOrigin.vertical].map(n => typeof n === 'number' ? `${n}px` : n).join(' ');
}
function resolveAnchorEl(anchorEl) {
return typeof anchorEl === 'function' ? anchorEl() : anchorEl;
}
const useUtilityClasses$4 = ownerState => {
const {
classes
} = ownerState;
const slots = {
root: ['root'],
paper: ['paper']
};
return composeClasses(slots, getPopoverUtilityClass, classes);
};
const PopoverRoot = styled(Modal, {
name: 'MuiPopover',
slot: 'Root',
overridesResolver: (props, styles) => styles.root
})({});
const PopoverPaper = styled(Paper, {
name: 'MuiPopover',
slot: 'Paper',
overridesResolver: (props, styles) => styles.paper
})({
position: 'absolute',
overflowY: 'auto',
overflowX: 'hidden',
// So we see the popover when it's empty.
// It's most likely on issue on userland.
minWidth: 16,
minHeight: 16,
maxWidth: 'calc(100% - 32px)',
maxHeight: 'calc(100% - 32px)',
// We disable the focus ring for mouse, touch and keyboard users.
outline: 0
});
const Popover = /*#__PURE__*/reactExports.forwardRef(function Popover(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiPopover'
});
const {
action,
anchorEl,
anchorOrigin = {
vertical: 'top',
horizontal: 'left'
},
anchorPosition,
anchorReference = 'anchorEl',
children,
className,
container: containerProp,
elevation = 8,
marginThreshold = 16,
open,
PaperProps: PaperPropsProp = {},
// TODO: remove in v7
slots = {},
slotProps = {},
transformOrigin = {
vertical: 'top',
horizontal: 'left'
},
TransitionComponent,
// TODO: remove in v7
transitionDuration: transitionDurationProp = 'auto',
TransitionProps = {},
// TODO: remove in v7
disableScrollLock = false,
...other
} = props;
const paperRef = reactExports.useRef();
const ownerState = {
...props,
anchorOrigin,
anchorReference,
elevation,
marginThreshold,
transformOrigin,
TransitionComponent,
transitionDuration: transitionDurationProp,
TransitionProps
};
const classes = useUtilityClasses$4(ownerState);
// Returns the top/left offset of the position
// to attach to on the anchor element (or body if none is provided)
const getAnchorOffset = reactExports.useCallback(() => {
if (anchorReference === 'anchorPosition') {
return anchorPosition;
}
const resolvedAnchorEl = resolveAnchorEl(anchorEl);
// If an anchor element wasn't provided, just use the parent body element of this Popover
const anchorElement = resolvedAnchorEl && resolvedAnchorEl.nodeType === 1 ? resolvedAnchorEl : ownerDocument(paperRef.current).body;
const anchorRect = anchorElement.getBoundingClientRect();
return {
top: anchorRect.top + getOffsetTop(anchorRect, anchorOrigin.vertical),
left: anchorRect.left + getOffsetLeft(anchorRect, anchorOrigin.horizontal)
};
}, [anchorEl, anchorOrigin.horizontal, anchorOrigin.vertical, anchorPosition, anchorReference]);
// Returns the base transform origin using the element
const getTransformOrigin = reactExports.useCallback(elemRect => {
return {
vertical: getOffsetTop(elemRect, transformOrigin.vertical),
horizontal: getOffsetLeft(elemRect, transformOrigin.horizontal)
};
}, [transformOrigin.horizontal, transformOrigin.vertical]);
const getPositioningStyle = reactExports.useCallback(element => {
const elemRect = {
width: element.offsetWidth,
height: element.offsetHeight
};
// Get the transform origin point on the element itself
const elemTransformOrigin = getTransformOrigin(elemRect);
if (anchorReference === 'none') {
return {
top: null,
left: null,
transformOrigin: getTransformOriginValue(elemTransformOrigin)
};
}
// Get the offset of the anchoring element
const anchorOffset = getAnchorOffset();
// Calculate element positioning
let top = anchorOffset.top - elemTransformOrigin.vertical;
let left = anchorOffset.left - elemTransformOrigin.horizontal;
const bottom = top + elemRect.height;
const right = left + elemRect.width;
// Use the parent window of the anchorEl if provided
const containerWindow = ownerWindow(resolveAnchorEl(anchorEl));
// Window thresholds taking required margin into account
const heightThreshold = containerWindow.innerHeight - marginThreshold;
const widthThreshold = containerWindow.innerWidth - marginThreshold;
// Check if the vertical axis needs shifting
if (marginThreshold !== null && top < marginThreshold) {
const diff = top - marginThreshold;
top -= diff;
elemTransformOrigin.vertical += diff;
} else if (marginThreshold !== null && bottom > heightThreshold) {
const diff = bottom - heightThreshold;
top -= diff;
elemTransformOrigin.vertical += diff;
}
// Check if the horizontal axis needs shifting
if (marginThreshold !== null && left < marginThreshold) {
const diff = left - marginThreshold;
left -= diff;
elemTransformOrigin.horizontal += diff;
} else if (right > widthThreshold) {
const diff = right - widthThreshold;
left -= diff;
elemTransformOrigin.horizontal += diff;
}
return {
top: `${Math.round(top)}px`,
left: `${Math.round(left)}px`,
transformOrigin: getTransformOriginValue(elemTransformOrigin)
};
}, [anchorEl, anchorReference, getAnchorOffset, getTransformOrigin, marginThreshold]);
const [isPositioned, setIsPositioned] = reactExports.useState(open);
const setPositioningStyles = reactExports.useCallback(() => {
const element = paperRef.current;
if (!element) {
return;
}
const positioning = getPositioningStyle(element);
if (positioning.top !== null) {
element.style.setProperty('top', positioning.top);
}
if (positioning.left !== null) {
element.style.left = positioning.left;
}
element.style.transformOrigin = positioning.transformOrigin;
setIsPositioned(true);
}, [getPositioningStyle]);
reactExports.useEffect(() => {
if (disableScrollLock) {
window.addEventListener('scroll', setPositioningStyles);
}
return () => window.removeEventListener('scroll', setPositioningStyles);
}, [anchorEl, disableScrollLock, setPositioningStyles]);
const handleEntering = () => {
setPositioningStyles();
};
const handleExited = () => {
setIsPositioned(false);
};
reactExports.useEffect(() => {
if (open) {
setPositioningStyles();
}
});
reactExports.useImperativeHandle(action, () => open ? {
updatePosition: () => {
setPositioningStyles();
}
} : null, [open, setPositioningStyles]);
reactExports.useEffect(() => {
if (!open) {
return undefined;
}
const handleResize = debounce$1(() => {
setPositioningStyles();
});
const containerWindow = ownerWindow(resolveAnchorEl(anchorEl));
containerWindow.addEventListener('resize', handleResize);
return () => {
handleResize.clear();
containerWindow.removeEventListener('resize', handleResize);
};
}, [anchorEl, open, setPositioningStyles]);
let transitionDuration = transitionDurationProp;
const externalForwardedProps = {
slots: {
transition: TransitionComponent,
...slots
},
slotProps: {
transition: TransitionProps,
paper: PaperPropsProp,
...slotProps
}
};
const [TransitionSlot, transitionSlotProps] = useSlot('transition', {
elementType: Grow,
externalForwardedProps,
ownerState,
getSlotProps: handlers => ({
...handlers,
onEntering: (element, isAppearing) => {
handlers.onEntering?.(element, isAppearing);
handleEntering();
},
onExited: element => {
handlers.onExited?.(element);
handleExited();
}
}),
additionalProps: {
appear: true,
in: open
}
});
if (transitionDurationProp === 'auto' && !TransitionSlot.muiSupportAuto) {
transitionDuration = undefined;
}
// If the container prop is provided, use that
// If the anchorEl prop is provided, use its parent body element as the container
// If neither are provided let the Modal take care of choosing the container
const container = containerProp || (anchorEl ? ownerDocument(resolveAnchorEl(anchorEl)).body : undefined);
const [RootSlot, {
slots: rootSlotsProp,
slotProps: rootSlotPropsProp,
...rootProps
}] = useSlot('root', {
ref,
elementType: PopoverRoot,
externalForwardedProps: {
...externalForwardedProps,
...other
},
shouldForwardComponentProp: true,
additionalProps: {
slots: {
backdrop: slots.backdrop
},
slotProps: {
backdrop: mergeSlotProps(typeof slotProps.backdrop === 'function' ? slotProps.backdrop(ownerState) : slotProps.backdrop, {
invisible: true
})
},
container,
open
},
ownerState,
className: clsx(classes.root, className)
});
const [PaperSlot, paperProps] = useSlot('paper', {
ref: paperRef,
className: classes.paper,
elementType: PopoverPaper,
externalForwardedProps,
shouldForwardComponentProp: true,
additionalProps: {
elevation,
style: isPositioned ? undefined : {
opacity: 0
}
},
ownerState
});
return /*#__PURE__*/jsxRuntimeExports.jsx(RootSlot, {
...rootProps,
...(!isHostComponent(RootSlot) && {
slots: rootSlotsProp,
slotProps: rootSlotPropsProp,
disableScrollLock
}),
children: /*#__PURE__*/jsxRuntimeExports.jsx(TransitionSlot, {
...transitionSlotProps,
timeout: transitionDuration,
children: /*#__PURE__*/jsxRuntimeExports.jsx(PaperSlot, {
...paperProps,
children: children
})
})
});
});
function getMenuItemUtilityClass(slot) {
return generateUtilityClass('MuiMenuItem', slot);
}
const menuItemClasses = generateUtilityClasses('MuiMenuItem', ['root', 'focusVisible', 'dense', 'disabled', 'divider', 'gutters', 'selected']);
const overridesResolver = (props, styles) => {
const {
ownerState
} = props;
return [styles.root, ownerState.dense && styles.dense, ownerState.divider && styles.divider, !ownerState.disableGutters && styles.gutters];
};
const useUtilityClasses$3 = ownerState => {
const {
disabled,
dense,
divider,
disableGutters,
selected,
classes
} = ownerState;
const slots = {
root: ['root', dense && 'dense', disabled && 'disabled', !disableGutters && 'gutters', divider && 'divider', selected && 'selected']
};
const composedClasses = composeClasses(slots, getMenuItemUtilityClass, classes);
return {
...classes,
...composedClasses
};
};
const MenuItemRoot = styled(ButtonBase, {
shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
name: 'MuiMenuItem',
slot: 'Root',
overridesResolver
})(memoTheme(({
theme
}) => ({
...theme.typography.body1,
display: 'flex',
justifyContent: 'flex-start',
alignItems: 'center',
position: 'relative',
textDecoration: 'none',
minHeight: 48,
paddingTop: 6,
paddingBottom: 6,
boxSizing: 'border-box',
whiteSpace: 'nowrap',
'&:hover': {
textDecoration: 'none',
backgroundColor: (theme.vars || theme).palette.action.hover,
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
},
[`&.${menuItemClasses.selected}`]: {
backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity),
[`&.${menuItemClasses.focusVisible}`]: {
backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.focusOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)
}
},
[`&.${menuItemClasses.selected}:hover`]: {
backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity)
}
},
[`&.${menuItemClasses.focusVisible}`]: {
backgroundColor: (theme.vars || theme).palette.action.focus
},
[`&.${menuItemClasses.disabled}`]: {
opacity: (theme.vars || theme).palette.action.disabledOpacity
},
[`& + .${dividerClasses.root}`]: {
marginTop: theme.spacing(1),
marginBottom: theme.spacing(1)
},
[`& + .${dividerClasses.inset}`]: {
marginLeft: 52
},
[`& .${listItemTextClasses.root}`]: {
marginTop: 0,
marginBottom: 0
},
[`& .${listItemTextClasses.inset}`]: {
paddingLeft: 36
},
[`& .${listItemIconClasses.root}`]: {
minWidth: 36
},
variants: [{
props: ({
ownerState
}) => !ownerState.disableGutters,
style: {
paddingLeft: 16,
paddingRight: 16
}
}, {
props: ({
ownerState
}) => ownerState.divider,
style: {
borderBottom: `1px solid ${(theme.vars || theme).palette.divider}`,
backgroundClip: 'padding-box'
}
}, {
props: ({
ownerState
}) => !ownerState.dense,
style: {
[theme.breakpoints.up('sm')]: {
minHeight: 'auto'
}
}
}, {
props: ({
ownerState
}) => ownerState.dense,
style: {
minHeight: 32,
// https://m2.material.io/components/menus#specs > Dense
paddingTop: 4,
paddingBottom: 4,
...theme.typography.body2,
[`& .${listItemIconClasses.root} svg`]: {
fontSize: '1.25rem'
}
}
}]
})));
const MenuItem = /*#__PURE__*/reactExports.forwardRef(function MenuItem(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiMenuItem'
});
const {
autoFocus = false,
component = 'li',
dense = false,
divider = false,
disableGutters = false,
focusVisibleClassName,
role = 'menuitem',
tabIndex: tabIndexProp,
className,
...other
} = props;
const context = reactExports.useContext(ListContext);
const childContext = reactExports.useMemo(() => ({
dense: dense || context.dense || false,
disableGutters
}), [context.dense, dense, disableGutters]);
const menuItemRef = reactExports.useRef(null);
useEnhancedEffect(() => {
if (autoFocus) {
if (menuItemRef.current) {
menuItemRef.current.focus();
}
}
}, [autoFocus]);
const ownerState = {
...props,
dense: childContext.dense,
divider,
disableGutters
};
const classes = useUtilityClasses$3(props);
const handleRef = useForkRef(menuItemRef, ref);
let tabIndex;
if (!props.disabled) {
tabIndex = tabIndexProp !== undefined ? tabIndexProp : -1;
}
return /*#__PURE__*/jsxRuntimeExports.jsx(ListContext.Provider, {
value: childContext,
children: /*#__PURE__*/jsxRuntimeExports.jsx(MenuItemRoot, {
ref: handleRef,
role: role,
tabIndex: tabIndex,
component: component,
focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName),
className: clsx(classes.root, className),
...other,
ownerState: ownerState,
classes: classes
})
});
});
var _span;
const NotchedOutlineRoot$1 = styled('fieldset', {
name: 'MuiNotchedOutlined',
shouldForwardProp: rootShouldForwardProp
})({
textAlign: 'left',
position: 'absolute',
bottom: 0,
right: 0,
top: -5,
left: 0,
margin: 0,
padding: '0 8px',
pointerEvents: 'none',
borderRadius: 'inherit',
borderStyle: 'solid',
borderWidth: 1,
overflow: 'hidden',
minWidth: '0%'
});
const NotchedOutlineLegend = styled('legend', {
name: 'MuiNotchedOutlined',
shouldForwardProp: rootShouldForwardProp
})(memoTheme(({
theme
}) => ({
float: 'unset',
// Fix conflict with bootstrap
width: 'auto',
// Fix conflict with bootstrap
overflow: 'hidden',
// Fix Horizontal scroll when label too long
variants: [{
props: ({
ownerState
}) => !ownerState.withLabel,
style: {
padding: 0,
lineHeight: '11px',
// sync with `height` in `legend` styles
transition: theme.transitions.create('width', {
duration: 150,
easing: theme.transitions.easing.easeOut
})
}
}, {
props: ({
ownerState
}) => ownerState.withLabel,
style: {
display: 'block',
// Fix conflict with normalize.css and sanitize.css
padding: 0,
height: 11,
// sync with `lineHeight` in `legend` styles
fontSize: '0.75em',
visibility: 'hidden',
maxWidth: 0.01,
transition: theme.transitions.create('max-width', {
duration: 50,
easing: theme.transitions.easing.easeOut
}),
whiteSpace: 'nowrap',
'& > span': {
paddingLeft: 5,
paddingRight: 5,
display: 'inline-block',
opacity: 0,
visibility: 'visible'
}
}
}, {
props: ({
ownerState
}) => ownerState.withLabel && ownerState.notched,
style: {
maxWidth: '100%',
transition: theme.transitions.create('max-width', {
duration: 100,
easing: theme.transitions.easing.easeOut,
delay: 50
})
}
}]
})));
/**
* @ignore - internal component.
*/
function NotchedOutline(props) {
const {
children,
classes,
className,
label,
notched,
...other
} = props;
const withLabel = label != null && label !== '';
const ownerState = {
...props,
notched,
withLabel
};
return /*#__PURE__*/jsxRuntimeExports.jsx(NotchedOutlineRoot$1, {
"aria-hidden": true,
className: className,
ownerState: ownerState,
...other,
children: /*#__PURE__*/jsxRuntimeExports.jsx(NotchedOutlineLegend, {
ownerState: ownerState,
children: withLabel ? /*#__PURE__*/jsxRuntimeExports.jsx("span", {
children: label
}) : // notranslate needed while Google Translate will not fix zero-width space issue
_span || (_span = /*#__PURE__*/jsxRuntimeExports.jsx("span", {
className: "notranslate",
"aria-hidden": true,
children: "\u200B"
}))
})
});
}
const useUtilityClasses$2 = ownerState => {
const {
classes
} = ownerState;
const slots = {
root: ['root'],
notchedOutline: ['notchedOutline'],
input: ['input']
};
const composedClasses = composeClasses(slots, getOutlinedInputUtilityClass, classes);
return {
...classes,
// forward classes to the InputBase
...composedClasses
};
};
const OutlinedInputRoot = styled(InputBaseRoot, {
shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
name: 'MuiOutlinedInput',
slot: 'Root',
overridesResolver: rootOverridesResolver
})(memoTheme(({
theme
}) => {
const borderColor = theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)';
return {
position: 'relative',
borderRadius: (theme.vars || theme).shape.borderRadius,
[`&:hover .${outlinedInputClasses.notchedOutline}`]: {
borderColor: (theme.vars || theme).palette.text.primary
},
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
[`&:hover .${outlinedInputClasses.notchedOutline}`]: {
borderColor: theme.vars ? `rgba(${theme.vars.palette.common.onBackgroundChannel} / 0.23)` : borderColor
}
},
[`&.${outlinedInputClasses.focused} .${outlinedInputClasses.notchedOutline}`]: {
borderWidth: 2
},
variants: [...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()).map(([color]) => ({
props: {
color
},
style: {
[`&.${outlinedInputClasses.focused} .${outlinedInputClasses.notchedOutline}`]: {
borderColor: (theme.vars || theme).palette[color].main
}
}
})), {
props: {},
// to overide the above style
style: {
[`&.${outlinedInputClasses.error} .${outlinedInputClasses.notchedOutline}`]: {
borderColor: (theme.vars || theme).palette.error.main
},
[`&.${outlinedInputClasses.disabled} .${outlinedInputClasses.notchedOutline}`]: {
borderColor: (theme.vars || theme).palette.action.disabled
}
}
}, {
props: ({
ownerState
}) => ownerState.startAdornment,
style: {
paddingLeft: 14
}
}, {
props: ({
ownerState
}) => ownerState.endAdornment,
style: {
paddingRight: 14
}
}, {
props: ({
ownerState
}) => ownerState.multiline,
style: {
padding: '16.5px 14px'
}
}, {
props: ({
ownerState,
size
}) => ownerState.multiline && size === 'small',
style: {
padding: '8.5px 14px'
}
}]
};
}));
const NotchedOutlineRoot = styled(NotchedOutline, {
name: 'MuiOutlinedInput',
slot: 'NotchedOutline',
overridesResolver: (props, styles) => styles.notchedOutline
})(memoTheme(({
theme
}) => {
const borderColor = theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)';
return {
borderColor: theme.vars ? `rgba(${theme.vars.palette.common.onBackgroundChannel} / 0.23)` : borderColor
};
}));
const OutlinedInputInput = styled(InputBaseInput, {
name: 'MuiOutlinedInput',
slot: 'Input',
overridesResolver: inputOverridesResolver
})(memoTheme(({
theme
}) => ({
padding: '16.5px 14px',
...(!theme.vars && {
'&:-webkit-autofill': {
WebkitBoxShadow: theme.palette.mode === 'light' ? null : '0 0 0 100px #266798 inset',
WebkitTextFillColor: theme.palette.mode === 'light' ? null : '#fff',
caretColor: theme.palette.mode === 'light' ? null : '#fff',
borderRadius: 'inherit'
}
}),
...(theme.vars && {
'&:-webkit-autofill': {
borderRadius: 'inherit'
},
[theme.getColorSchemeSelector('dark')]: {
'&:-webkit-autofill': {
WebkitBoxShadow: '0 0 0 100px #266798 inset',
WebkitTextFillColor: '#fff',
caretColor: '#fff'
}
}
}),
variants: [{
props: {
size: 'small'
},
style: {
padding: '8.5px 14px'
}
}, {
props: ({
ownerState
}) => ownerState.multiline,
style: {
padding: 0
}
}, {
props: ({
ownerState
}) => ownerState.startAdornment,
style: {
paddingLeft: 0
}
}, {
props: ({
ownerState
}) => ownerState.endAdornment,
style: {
paddingRight: 0
}
}]
})));
const OutlinedInput = /*#__PURE__*/reactExports.forwardRef(function OutlinedInput(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiOutlinedInput'
});
const {
components = {},
fullWidth = false,
inputComponent = 'input',
label,
multiline = false,
notched,
slots = {},
slotProps = {},
type = 'text',
...other
} = props;
const classes = useUtilityClasses$2(props);
const muiFormControl = useFormControl();
const fcs = formControlState({
props,
muiFormControl,
states: ['color', 'disabled', 'error', 'focused', 'hiddenLabel', 'size', 'required']
});
const ownerState = {
...props,
color: fcs.color || 'primary',
disabled: fcs.disabled,
error: fcs.error,
focused: fcs.focused,
formControl: muiFormControl,
fullWidth,
hiddenLabel: fcs.hiddenLabel,
multiline,
size: fcs.size,
type
};
const RootSlot = slots.root ?? components.Root ?? OutlinedInputRoot;
const InputSlot = slots.input ?? components.Input ?? OutlinedInputInput;
const [NotchedSlot, notchedProps] = useSlot('notchedOutline', {
elementType: NotchedOutlineRoot,
className: classes.notchedOutline,
shouldForwardComponentProp: true,
ownerState,
externalForwardedProps: {
slots,
slotProps
},
additionalProps: {
label: label != null && label !== '' && fcs.required ? /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports.Fragment, {
children: [label, "\u2009", '*']
}) : label
}
});
return /*#__PURE__*/jsxRuntimeExports.jsx(InputBase, {
slots: {
root: RootSlot,
input: InputSlot
},
slotProps: slotProps,
renderSuffix: state => /*#__PURE__*/jsxRuntimeExports.jsx(NotchedSlot, {
...notchedProps,
notched: typeof notched !== 'undefined' ? notched : Boolean(state.startAdornment || state.filled || state.focused)
}),
fullWidth: fullWidth,
inputComponent: inputComponent,
multiline: multiline,
ref: ref,
type: type,
...other,
classes: {
...classes,
notchedOutline: null
}
});
});
OutlinedInput.muiName = 'Input';
var RadioButtonUncheckedIcon = createSvgIcon(/*#__PURE__*/jsxRuntimeExports.jsx("path", {
d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"
}), 'RadioButtonUnchecked');
var RadioButtonCheckedIcon = createSvgIcon(/*#__PURE__*/jsxRuntimeExports.jsx("path", {
d: "M8.465 8.465C9.37 7.56 10.62 7 12 7C14.76 7 17 9.24 17 12C17 13.38 16.44 14.63 15.535 15.535C14.63 16.44 13.38 17 12 17C9.24 17 7 14.76 7 12C7 10.62 7.56 9.37 8.465 8.465Z"
}), 'RadioButtonChecked');
const RadioButtonIconRoot = styled('span', {
name: 'MuiRadioButtonIcon',
shouldForwardProp: rootShouldForwardProp
})({
position: 'relative',
display: 'flex'
});
const RadioButtonIconBackground = styled(RadioButtonUncheckedIcon, {
name: 'MuiRadioButtonIcon'
})({
// Scale applied to prevent dot misalignment in Safari
transform: 'scale(1)'
});
const RadioButtonIconDot = styled(RadioButtonCheckedIcon, {
name: 'MuiRadioButtonIcon'
})(memoTheme(({
theme
}) => ({
left: 0,
position: 'absolute',
transform: 'scale(0)',
transition: theme.transitions.create('transform', {
easing: theme.transitions.easing.easeIn,
duration: theme.transitions.duration.shortest
}),
variants: [{
props: {
checked: true
},
style: {
transform: 'scale(1)',
transition: theme.transitions.create('transform', {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.shortest
})
}
}]
})));
/**
* @ignore - internal component.
*/
function RadioButtonIcon(props) {
const {
checked = false,
classes = {},
fontSize
} = props;
const ownerState = {
...props,
checked
};
return /*#__PURE__*/jsxRuntimeExports.jsxs(RadioButtonIconRoot, {
className: classes.root,
ownerState: ownerState,
children: [/*#__PURE__*/jsxRuntimeExports.jsx(RadioButtonIconBackground, {
fontSize: fontSize,
className: classes.background,
ownerState: ownerState
}), /*#__PURE__*/jsxRuntimeExports.jsx(RadioButtonIconDot, {
fontSize: fontSize,
className: classes.dot,
ownerState: ownerState
})]
});
}
/**
* @ignore - internal component.
*/
const RadioGroupContext = /*#__PURE__*/reactExports.createContext(undefined);
function useRadioGroup() {
return reactExports.useContext(RadioGroupContext);
}
function getRadioUtilityClass(slot) {
return generateUtilityClass('MuiRadio', slot);
}
const radioClasses = generateUtilityClasses('MuiRadio', ['root', 'checked', 'disabled', 'colorPrimary', 'colorSecondary', 'sizeSmall']);
const useUtilityClasses$1 = ownerState => {
const {
classes,
color,
size
} = ownerState;
const slots = {
root: ['root', `color${capitalize(color)}`, size !== 'medium' && `size${capitalize(size)}`]
};
return {
...classes,
...composeClasses(slots, getRadioUtilityClass, classes)
};
};
const RadioRoot = styled(SwitchBase, {
shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',
name: 'MuiRadio',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, ownerState.size !== 'medium' && styles[`size${capitalize(ownerState.size)}`], styles[`color${capitalize(ownerState.color)}`]];
}
})(memoTheme(({
theme
}) => ({
color: (theme.vars || theme).palette.text.secondary,
[`&.${radioClasses.disabled}`]: {
color: (theme.vars || theme).palette.action.disabled
},
variants: [{
props: {
color: 'default',
disabled: false,
disableRipple: false
},
style: {
'&:hover': {
backgroundColor: theme.vars ? `rgba(${theme.vars.palette.action.activeChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette.action.active, theme.palette.action.hoverOpacity)
}
}
}, ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()).map(([color]) => ({
props: {
color,
disabled: false,
disableRipple: false
},
style: {
'&:hover': {
backgroundColor: theme.vars ? `rgba(${theme.vars.palette[color].mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette[color].main, theme.palette.action.hoverOpacity)
}
}
})), ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()).map(([color]) => ({
props: {
color,
disabled: false
},
style: {
[`&.${radioClasses.checked}`]: {
color: (theme.vars || theme).palette[color].main
}
}
})), {
// Should be last to override other colors
props: {
disableRipple: false
},
style: {
// Reset on touch devices, it doesn't add specificity
'&:hover': {
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
}
}]
})));
function areEqualValues(a, b) {
if (typeof b === 'object' && b !== null) {
return a === b;
}
// The value could be a number, the DOM will stringify it anyway.
return String(a) === String(b);
}
const defaultCheckedIcon = /*#__PURE__*/jsxRuntimeExports.jsx(RadioButtonIcon, {
checked: true
});
const defaultIcon = /*#__PURE__*/jsxRuntimeExports.jsx(RadioButtonIcon, {});
const Radio = /*#__PURE__*/reactExports.forwardRef(function Radio(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiRadio'
});
const {
checked: checkedProp,
checkedIcon = defaultCheckedIcon,
color = 'primary',
icon = defaultIcon,
name: nameProp,
onChange: onChangeProp,
size = 'medium',
className,
disabled: disabledProp,
disableRipple = false,
slots = {},
slotProps = {},
inputProps,
...other
} = props;
const muiFormControl = useFormControl();
let disabled = disabledProp;
if (muiFormControl) {
if (typeof disabled === 'undefined') {
disabled = muiFormControl.disabled;
}
}
disabled ??= false;
const ownerState = {
...props,
disabled,
disableRipple,
color,
size
};
const classes = useUtilityClasses$1(ownerState);
const radioGroup = useRadioGroup();
let checked = checkedProp;
const onChange = createChainedFunction(onChangeProp, radioGroup && radioGroup.onChange);
let name = nameProp;
if (radioGroup) {
if (typeof checked === 'undefined') {
checked = areEqualValues(radioGroup.value, props.value);
}
if (typeof name === 'undefined') {
name = radioGroup.name;
}
}
const externalInputProps = slotProps.input ?? inputProps;
const [RootSlot, rootSlotProps] = useSlot('root', {
ref,
elementType: RadioRoot,
className: clsx(classes.root, className),
shouldForwardComponentProp: true,
externalForwardedProps: {
slots,
slotProps,
...other
},
getSlotProps: handlers => ({
...handlers,
onChange: (event, ...args) => {
handlers.onChange?.(event, ...args);
onChange(event, ...args);
}
}),
ownerState,
additionalProps: {
type: 'radio',
icon: /*#__PURE__*/reactExports.cloneElement(icon, {
fontSize: icon.props.fontSize ?? size
}),
checkedIcon: /*#__PURE__*/reactExports.cloneElement(checkedIcon, {
fontSize: checkedIcon.props.fontSize ?? size
}),
disabled,
name,
checked,
slots,
slotProps: {
// Do not forward `slotProps.root` again because it's already handled by the `RootSlot` in this file.
input: typeof externalInputProps === 'function' ? externalInputProps(ownerState) : externalInputProps
}
}
});
return /*#__PURE__*/jsxRuntimeExports.jsx(RootSlot, {
...rootSlotProps,
classes: classes
});
});
function getTooltipUtilityClass(slot) {
return generateUtilityClass('MuiTooltip', slot);
}
const tooltipClasses = generateUtilityClasses('MuiTooltip', ['popper', 'popperInteractive', 'popperArrow', 'popperClose', 'tooltip', 'tooltipArrow', 'touch', 'tooltipPlacementLeft', 'tooltipPlacementRight', 'tooltipPlacementTop', 'tooltipPlacementBottom', 'arrow']);
function round(value) {
return Math.round(value * 1e5) / 1e5;
}
const useUtilityClasses = ownerState => {
const {
classes,
disableInteractive,
arrow,
touch,
placement
} = ownerState;
const slots = {
popper: ['popper', !disableInteractive && 'popperInteractive', arrow && 'popperArrow'],
tooltip: ['tooltip', arrow && 'tooltipArrow', touch && 'touch', `tooltipPlacement${capitalize(placement.split('-')[0])}`],
arrow: ['arrow']
};
return composeClasses(slots, getTooltipUtilityClass, classes);
};
const TooltipPopper = styled(Popper, {
name: 'MuiTooltip',
slot: 'Popper',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.popper, !ownerState.disableInteractive && styles.popperInteractive, ownerState.arrow && styles.popperArrow, !ownerState.open && styles.popperClose];
}
})(memoTheme(({
theme
}) => ({
zIndex: (theme.vars || theme).zIndex.tooltip,
pointerEvents: 'none',
variants: [{
props: ({
ownerState
}) => !ownerState.disableInteractive,
style: {
pointerEvents: 'auto'
}
}, {
props: ({
open
}) => !open,
style: {
pointerEvents: 'none'
}
}, {
props: ({
ownerState
}) => ownerState.arrow,
style: {
[`&[data-popper-placement*="bottom"] .${tooltipClasses.arrow}`]: {
top: 0,
marginTop: '-0.71em',
'&::before': {
transformOrigin: '0 100%'
}
},
[`&[data-popper-placement*="top"] .${tooltipClasses.arrow}`]: {
bottom: 0,
marginBottom: '-0.71em',
'&::before': {
transformOrigin: '100% 0'
}
},
[`&[data-popper-placement*="right"] .${tooltipClasses.arrow}`]: {
height: '1em',
width: '0.71em',
'&::before': {
transformOrigin: '100% 100%'
}
},
[`&[data-popper-placement*="left"] .${tooltipClasses.arrow}`]: {
height: '1em',
width: '0.71em',
'&::before': {
transformOrigin: '0 0'
}
}
}
}, {
props: ({
ownerState
}) => ownerState.arrow && !ownerState.isRtl,
style: {
[`&[data-popper-placement*="right"] .${tooltipClasses.arrow}`]: {
left: 0,
marginLeft: '-0.71em'
}
}
}, {
props: ({
ownerState
}) => ownerState.arrow && !!ownerState.isRtl,
style: {
[`&[data-popper-placement*="right"] .${tooltipClasses.arrow}`]: {
right: 0,
marginRight: '-0.71em'
}
}
}, {
props: ({
ownerState
}) => ownerState.arrow && !ownerState.isRtl,
style: {
[`&[data-popper-placement*="left"] .${tooltipClasses.arrow}`]: {
right: 0,
marginRight: '-0.71em'
}
}
}, {
props: ({
ownerState
}) => ownerState.arrow && !!ownerState.isRtl,
style: {
[`&[data-popper-placement*="left"] .${tooltipClasses.arrow}`]: {
left: 0,
marginLeft: '-0.71em'
}
}
}]
})));
const TooltipTooltip = styled('div', {
name: 'MuiTooltip',
slot: 'Tooltip',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.tooltip, ownerState.touch && styles.touch, ownerState.arrow && styles.tooltipArrow, styles[`tooltipPlacement${capitalize(ownerState.placement.split('-')[0])}`]];
}
})(memoTheme(({
theme
}) => ({
backgroundColor: theme.vars ? theme.vars.palette.Tooltip.bg : alpha(theme.palette.grey[700], 0.92),
borderRadius: (theme.vars || theme).shape.borderRadius,
color: (theme.vars || theme).palette.common.white,
fontFamily: theme.typography.fontFamily,
padding: '4px 8px',
fontSize: theme.typography.pxToRem(11),
maxWidth: 300,
margin: 2,
wordWrap: 'break-word',
fontWeight: theme.typography.fontWeightMedium,
[`.${tooltipClasses.popper}[data-popper-placement*="left"] &`]: {
transformOrigin: 'right center'
},
[`.${tooltipClasses.popper}[data-popper-placement*="right"] &`]: {
transformOrigin: 'left center'
},
[`.${tooltipClasses.popper}[data-popper-placement*="top"] &`]: {
transformOrigin: 'center bottom',
marginBottom: '14px'
},
[`.${tooltipClasses.popper}[data-popper-placement*="bottom"] &`]: {
transformOrigin: 'center top',
marginTop: '14px'
},
variants: [{
props: ({
ownerState
}) => ownerState.arrow,
style: {
position: 'relative',
margin: 0
}
}, {
props: ({
ownerState
}) => ownerState.touch,
style: {
padding: '8px 16px',
fontSize: theme.typography.pxToRem(14),
lineHeight: `${round(16 / 14)}em`,
fontWeight: theme.typography.fontWeightRegular
}
}, {
props: ({
ownerState
}) => !ownerState.isRtl,
style: {
[`.${tooltipClasses.popper}[data-popper-placement*="left"] &`]: {
marginRight: '14px'
},
[`.${tooltipClasses.popper}[data-popper-placement*="right"] &`]: {
marginLeft: '14px'
}
}
}, {
props: ({
ownerState
}) => !ownerState.isRtl && ownerState.touch,
style: {
[`.${tooltipClasses.popper}[data-popper-placement*="left"] &`]: {
marginRight: '24px'
},
[`.${tooltipClasses.popper}[data-popper-placement*="right"] &`]: {
marginLeft: '24px'
}
}
}, {
props: ({
ownerState
}) => !!ownerState.isRtl,
style: {
[`.${tooltipClasses.popper}[data-popper-placement*="left"] &`]: {
marginLeft: '14px'
},
[`.${tooltipClasses.popper}[data-popper-placement*="right"] &`]: {
marginRight: '14px'
}
}
}, {
props: ({
ownerState
}) => !!ownerState.isRtl && ownerState.touch,
style: {
[`.${tooltipClasses.popper}[data-popper-placement*="left"] &`]: {
marginLeft: '24px'
},
[`.${tooltipClasses.popper}[data-popper-placement*="right"] &`]: {
marginRight: '24px'
}
}
}, {
props: ({
ownerState
}) => ownerState.touch,
style: {
[`.${tooltipClasses.popper}[data-popper-placement*="top"] &`]: {
marginBottom: '24px'
}
}
}, {
props: ({
ownerState
}) => ownerState.touch,
style: {
[`.${tooltipClasses.popper}[data-popper-placement*="bottom"] &`]: {
marginTop: '24px'
}
}
}]
})));
const TooltipArrow = styled('span', {
name: 'MuiTooltip',
slot: 'Arrow',
overridesResolver: (props, styles) => styles.arrow
})(memoTheme(({
theme
}) => ({
overflow: 'hidden',
position: 'absolute',
width: '1em',
height: '0.71em' /* = width / sqrt(2) = (length of the hypotenuse) */,
boxSizing: 'border-box',
color: theme.vars ? theme.vars.palette.Tooltip.bg : alpha(theme.palette.grey[700], 0.9),
'&::before': {
content: '""',
margin: 'auto',
display: 'block',
width: '100%',
height: '100%',
backgroundColor: 'currentColor',
transform: 'rotate(45deg)'
}
})));
let hystersisOpen = false;
const hystersisTimer = new Timeout();
let cursorPosition = {
x: 0,
y: 0
};
function composeEventHandler(handler, eventHandler) {
return (event, ...params) => {
if (eventHandler) {
eventHandler(event, ...params);
}
handler(event, ...params);
};
}
// TODO v6: Remove PopperComponent, PopperProps, TransitionComponent and TransitionProps.
const Tooltip = /*#__PURE__*/reactExports.forwardRef(function Tooltip(inProps, ref) {
const props = useDefaultProps({
props: inProps,
name: 'MuiTooltip'
});
const {
arrow = false,
children: childrenProp,
classes: classesProp,
components = {},
componentsProps = {},
describeChild = false,
disableFocusListener = false,
disableHoverListener = false,
disableInteractive: disableInteractiveProp = false,
disableTouchListener = false,
enterDelay = 100,
enterNextDelay = 0,
enterTouchDelay = 700,
followCursor = false,
id: idProp,
leaveDelay = 0,
leaveTouchDelay = 1500,
onClose,
onOpen,
open: openProp,
placement = 'bottom',
PopperComponent: PopperComponentProp,
PopperProps = {},
slotProps = {},
slots = {},
title,
TransitionComponent: TransitionComponentProp,
TransitionProps,
...other
} = props;
// to prevent runtime errors, developers will need to provide a child as a React element anyway.
const children = /*#__PURE__*/reactExports.isValidElement(childrenProp) ? childrenProp : /*#__PURE__*/jsxRuntimeExports.jsx("span", {
children: childrenProp
});
const theme = useTheme$1();
const isRtl = useRtl();
const [childNode, setChildNode] = reactExports.useState();
const [arrowRef, setArrowRef] = reactExports.useState(null);
const ignoreNonTouchEvents = reactExports.useRef(false);
const disableInteractive = disableInteractiveProp || followCursor;
const closeTimer = useTimeout();
const enterTimer = useTimeout();
const leaveTimer = useTimeout();
const touchTimer = useTimeout();
const [openState, setOpenState] = useControlled({
controlled: openProp,
default: false,
name: 'Tooltip',
state: 'open'
});
let open = openState;
const id = useId(idProp);
const prevUserSelect = reactExports.useRef();
const stopTouchInteraction = useEventCallback(() => {
if (prevUserSelect.current !== undefined) {
document.body.style.WebkitUserSelect = prevUserSelect.current;
prevUserSelect.current = undefined;
}
touchTimer.clear();
});
reactExports.useEffect(() => stopTouchInteraction, [stopTouchInteraction]);
const handleOpen = event => {
hystersisTimer.clear();
hystersisOpen = true;
// The mouseover event will trigger for every nested element in the tooltip.
// We can skip rerendering when the tooltip is already open.
// We are using the mouseover event instead of the mouseenter event to fix a hide/show issue.
setOpenState(true);
if (onOpen && !open) {
onOpen(event);
}
};
const handleClose = useEventCallback(
/**
* @param {React.SyntheticEvent | Event} event
*/
event => {
hystersisTimer.start(800 + leaveDelay, () => {
hystersisOpen = false;
});
setOpenState(false);
if (onClose && open) {
onClose(event);
}
closeTimer.start(theme.transitions.duration.shortest, () => {
ignoreNonTouchEvents.current = false;
});
});
const handleMouseOver = event => {
if (ignoreNonTouchEvents.current && event.type !== 'touchstart') {
return;
}
// Remove the title ahead of time.
// We don't want to wait for the next render commit.
// We would risk displaying two tooltips at the same time (native + this one).
if (childNode) {
childNode.removeAttribute('title');
}
enterTimer.clear();
leaveTimer.clear();
if (enterDelay || hystersisOpen && enterNextDelay) {
enterTimer.start(hystersisOpen ? enterNextDelay : enterDelay, () => {
handleOpen(event);
});
} else {
handleOpen(event);
}
};
const handleMouseLeave = event => {
enterTimer.clear();
leaveTimer.start(leaveDelay, () => {
handleClose(event);
});
};
const [, setChildIsFocusVisible] = reactExports.useState(false);
const handleBlur = event => {
if (!isFocusVisible(event.target)) {
setChildIsFocusVisible(false);
handleMouseLeave(event);
}
};
const handleFocus = event => {
// Workaround for https://github.com/facebook/react/issues/7769
// The autoFocus of React might trigger the event before the componentDidMount.
// We need to account for this eventuality.
if (!childNode) {
setChildNode(event.currentTarget);
}
if (isFocusVisible(event.target)) {
setChildIsFocusVisible(true);
handleMouseOver(event);
}
};
const detectTouchStart = event => {
ignoreNonTouchEvents.current = true;
const childrenProps = children.props;
if (childrenProps.onTouchStart) {
childrenProps.onTouchStart(event);
}
};
const handleTouchStart = event => {
detectTouchStart(event);
leaveTimer.clear();
closeTimer.clear();
stopTouchInteraction();
prevUserSelect.current = document.body.style.WebkitUserSelect;
// Prevent iOS text selection on long-tap.
document.body.style.WebkitUserSelect = 'none';
touchTimer.start(enterTouchDelay, () => {
document.body.style.WebkitUserSelect = prevUserSelect.current;
handleMouseOver(event);
});
};
const handleTouchEnd = event => {
if (children.props.onTouchEnd) {
children.props.onTouchEnd(event);
}
stopTouchInteraction();
leaveTimer.start(leaveTouchDelay, () => {
handleClose(event);
});
};
reactExports.useEffect(() => {
if (!open) {
return undefined;
}
/**
* @param {KeyboardEvent} nativeEvent
*/
function handleKeyDown(nativeEvent) {
if (nativeEvent.key === 'Escape') {
handleClose(nativeEvent);
}
}
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [handleClose, open]);
const handleRef = useForkRef(getReactElementRef(children), setChildNode, ref);
// There is no point in displaying an empty tooltip.
// So we exclude all falsy values, except 0, which is valid.
if (!title && title !== 0) {
open = false;
}
const popperRef = reactExports.useRef();
const handleMouseMove = event => {
const childrenProps = children.props;
if (childrenProps.onMouseMove) {
childrenProps.onMouseMove(event);
}
cursorPosition = {
x: event.clientX,
y: event.clientY
};
if (popperRef.current) {
popperRef.current.update();
}
};
const nameOrDescProps = {};
const titleIsString = typeof title === 'string';
if (describeChild) {
nameOrDescProps.title = !open && titleIsString && !disableHoverListener ? title : null;
nameOrDescProps['aria-describedby'] = open ? id : null;
} else {
nameOrDescProps['aria-label'] = titleIsString ? title : null;
nameOrDescProps['aria-labelledby'] = open && !titleIsString ? id : null;
}
const childrenProps = {
...nameOrDescProps,
...other,
...children.props,
className: clsx(other.className, children.props.className),
onTouchStart: detectTouchStart,
ref: handleRef,
...(followCursor ? {
onMouseMove: handleMouseMove
} : {})
};
const interactiveWrapperListeners = {};
if (!disableTouchListener) {
childrenProps.onTouchStart = handleTouchStart;
childrenProps.onTouchEnd = handleTouchEnd;
}
if (!disableHoverListener) {
childrenProps.onMouseOver = composeEventHandler(handleMouseOver, childrenProps.onMouseOver);
childrenProps.onMouseLeave = composeEventHandler(handleMouseLeave, childrenProps.onMouseLeave);
if (!disableInteractive) {
interactiveWrapperListeners.onMouseOver = handleMouseOver;
interactiveWrapperListeners.onMouseLeave = handleMouseLeave;
}
}
if (!disableFocusListener) {
childrenProps.onFocus = composeEventHandler(handleFocus, childrenProps.onFocus);
childrenProps.onBlur = composeEventHandler(handleBlur, childrenProps.onBlur);
if (!disableInteractive) {
interactiveWrapperListeners.onFocus = handleFocus;
interactiveWrapperListeners.onBlur = handleBlur;
}
}
const ownerState = {
...props,
isRtl,
arrow,
disableInteractive,
placement,
PopperComponentProp,
touch: ignoreNonTouchEvents.current
};
const resolvedPopperProps = typeof slotProps.popper === 'function' ? slotProps.popper(ownerState) : slotProps.popper;
const popperOptions = reactExports.useMemo(() => {
let tooltipModifiers = [{
name: 'arrow',
enabled: Boolean(arrowRef),
options: {
element: arrowRef,
padding: 4
}
}];
if (PopperProps.popperOptions?.modifiers) {
tooltipModifiers = tooltipModifiers.concat(PopperProps.popperOptions.modifiers);
}
if (resolvedPopperProps?.popperOptions?.modifiers) {
tooltipModifiers = tooltipModifiers.concat(resolvedPopperProps.popperOptions.modifiers);
}
return {
...PopperProps.popperOptions,
...resolvedPopperProps?.popperOptions,
modifiers: tooltipModifiers
};
}, [arrowRef, PopperProps.popperOptions, resolvedPopperProps?.popperOptions]);
const classes = useUtilityClasses(ownerState);
const resolvedTransitionProps = typeof slotProps.transition === 'function' ? slotProps.transition(ownerState) : slotProps.transition;
const externalForwardedProps = {
slots: {
popper: components.Popper,
transition: components.Transition ?? TransitionComponentProp,
tooltip: components.Tooltip,
arrow: components.Arrow,
...slots
},
slotProps: {
arrow: slotProps.arrow ?? componentsProps.arrow,
popper: {
...PopperProps,
...(resolvedPopperProps ?? componentsProps.popper)
},
// resolvedPopperProps can be spread because it's already an object
tooltip: slotProps.tooltip ?? componentsProps.tooltip,
transition: {
...TransitionProps,
...(resolvedTransitionProps ?? componentsProps.transition)
}
}
};
const [PopperSlot, popperSlotProps] = useSlot('popper', {
elementType: TooltipPopper,
externalForwardedProps,
ownerState,
className: clsx(classes.popper, PopperProps?.className)
});
const [TransitionSlot, transitionSlotProps] = useSlot('transition', {
elementType: Grow,
externalForwardedProps,
ownerState
});
const [TooltipSlot, tooltipSlotProps] = useSlot('tooltip', {
elementType: TooltipTooltip,
className: classes.tooltip,
externalForwardedProps,
ownerState
});
const [ArrowSlot, arrowSlotProps] = useSlot('arrow', {
elementType: TooltipArrow,
className: classes.arrow,
externalForwardedProps,
ownerState,
ref: setArrowRef
});
return /*#__PURE__*/jsxRuntimeExports.jsxs(reactExports.Fragment, {
children: [/*#__PURE__*/reactExports.cloneElement(children, childrenProps), /*#__PURE__*/jsxRuntimeExports.jsx(PopperSlot, {
as: PopperComponentProp ?? Popper,
placement: placement,
anchorEl: followCursor ? {
getBoundingClientRect: () => ({
top: cursorPosition.y,
left: cursorPosition.x,
right: cursorPosition.x,
bottom: cursorPosition.y,
width: 0,
height: 0
})
} : childNode,
popperRef: popperRef,
open: childNode ? open : false,
id: id,
transition: true,
...interactiveWrapperListeners,
...popperSlotProps,
popperOptions: popperOptions,
children: ({
TransitionProps: TransitionPropsInner
}) => /*#__PURE__*/jsxRuntimeExports.jsx(TransitionSlot, {
timeout: theme.transitions.duration.shorter,
...TransitionPropsInner,
...transitionSlotProps,
children: /*#__PURE__*/jsxRuntimeExports.jsxs(TooltipSlot, {
...tooltipSlotProps,
children: [title, arrow ? /*#__PURE__*/jsxRuntimeExports.jsx(ArrowSlot, {
...arrowSlotProps
}) : null]
})
})
})]
});
});
function useModelStore() {
const {
useModelStore: useFunc
} = reactExports.useContext(InstanceContext).modelStore;
return useFunc();
}
function useModelChangedStore() {
const {
useModelChangedStore: useFunc
} = reactExports.useContext(InstanceContext).modelStore;
return useFunc();
}
function useRpcResultStore() {
const {
useRpcResultStore: useFunc
} = reactExports.useContext(InstanceContext).modelStore;
return useFunc();
}
function useRpcRequestStore() {
const {
useRpcRequestStore: useFunc
} = reactExports.useContext(InstanceContext).modelStore;
return useFunc();
}
function useRpcRequestSessionModelStore() {
const {
useRpcRequestSessionModelStore: useFunc
} = reactExports.useContext(InstanceContext).modelStore;
return useFunc();
}
function useSessionModel(definition, app) {
const key = app ? "".concat(app.id, "/").concat(JSON.stringify(definition)) : null;
const [modelStore] = useModelStore();
const [rpcRequestSessionModelStore] = useRpcRequestSessionModelStore();
const [model, setModel] = reactExports.useState();
for (var _len = arguments.length, deps = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
deps[_key - 2] = arguments[_key];
}
reactExports.useEffect(() => {
if (!app) {
return;
}
// Create new session object
const create = async () => {
let rpcShared = rpcRequestSessionModelStore.get(key);
if (!rpcShared) {
rpcShared = app.createSessionObject(definition);
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 sleep = delay => new Promise(resolve => {
setTimeout(resolve, delay);
});
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] = reactExports.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 {
// To avoid possible race condition causing an infinite loop.
// Problem has been observed for mocked models appeared after switching to react 18 (reactDOM render -> createRoot).
await sleep(0);
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();
}
};
reactExports.useEffect(() => {
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) {
const [layout, {
validating,
canCancel,
canRetry
}, longrunning] = useRpc(model, 'getLayout');
if (model !== null && model !== void 0 && model.pureLayout && layout) {
return [model.pureLayout, {
validating,
canCancel,
canRetry
}, longrunning];
}
return [layout, {
validating,
canCancel,
canRetry
}, longrunning];
}
function useAppLayout$1(model) {
return useRpc(model, 'getAppLayout');
}
function useRect$1() {
const [node, setNode] = reactExports.useState();
const [rect, setRect] = reactExports.useState();
const callbackRef = reactExports.useCallback(ref => {
if (!ref) {
return;
}
setNode(ref);
}, []);
const handleResize = () => {
const {
left,
top,
width,
height
} = node.getBoundingClientRect();
setRect({
left,
top,
width,
height
});
};
reactExports.useLayoutEffect(() => {
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$1({
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: 'M8 10a1 1 0 0 1 .5 1.866v.634a.5.5 0 0 1-1 0v-.634A1 1 0 0 1 8 10ZM3.625 7.035A2 2 0 0 0 2 9v5a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V9a2 2 0 0 0-1.625-1.965V5.383a4.375 4.375 0 0 0-8.75 0v1.652ZM3 9a1 1 0 0 1 .931-.998h8.138A1 1 0 0 1 13 9v5a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V9Zm8.375-3.617V7h-6.75V5.383a3.375 3.375 0 0 1 6.75 0Z'
}
}]
});
var Lock = props => SvgIcon(lock(props));
const unlock = props => _objectSpread2(_objectSpread2({}, props), {}, {
viewBox: '0 0 12 16',
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 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 = 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 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 InfiniteLoader = function (_PureComponent) {
inherits(InfiniteLoader, _PureComponent);
function InfiniteLoader() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, InfiniteLoader);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(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(_this, _ret);
}
createClass(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;
}(reactExports.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 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);
}
async function selectValues(_ref) {
let {
selections,
elemNumbers,
toggle,
isSingleSelect
} = _ref;
if (elemNumbers.length === 0) {
return false;
}
const hasNanValues = elemNumbers.some(elemNumber => Number.isNaN(elemNumber));
let success = false;
if (!hasNanValues) {
const elemNumbersToSelect = elemNumbers;
try {
const response = await selections.select({
method: 'selectListObjectValues',
params: ['/qListObjectDef', elemNumbersToSelect, toggle]
});
success = response !== false;
} catch (_unused) {
success = false;
}
if (!success) {
if (isSingleSelect) {
selections.cancel(); // revert selection
} else {
selections.clear();
}
}
}
return success;
}
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);
}
const PREFIX$c = 'RowColumn';
const rowColClasses = {
row: "".concat(PREFIX$c, "-row"),
rowBorderBottom: "".concat(PREFIX$c, "-rowBorderBottom"),
column: "".concat(PREFIX$c, "-column"),
fieldRoot: "".concat(PREFIX$c, "-fieldRoot"),
cell: "".concat(PREFIX$c, "-cell"),
labelText: "".concat(PREFIX$c, "-labelText"),
labelDense: "".concat(PREFIX$c, "-labelDense"),
highlighted: "".concat(PREFIX$c, "-highlighted"),
checkboxLabel: "".concat(PREFIX$c, "-checkboxLabel"),
icon: "".concat(PREFIX$c, "-icon"),
S: "".concat(PREFIX$c, "-S"),
XS: "".concat(PREFIX$c, "-XS"),
A: "".concat(PREFIX$c, "-A"),
X: "".concat(PREFIX$c, "-X"),
frequencyCount: "".concat(PREFIX$c, "-frequencyCount"),
barContainer: "".concat(PREFIX$c, "-barContainer"),
bar: "".concat(PREFIX$c, "-bar"),
barSelected: "".concat(PREFIX$c, "-barSelected"),
barWithCheckbox: "".concat(PREFIX$c, "-barWithCheckbox"),
barSelectedWithCheckbox: "".concat(PREFIX$c, "-barSelectedWithCheckbox"),
excludedTextWithCheckbox: "".concat(PREFIX$c, "-excludedTextWithCheckbox")
};
/* eslint-disable no-underscore-dangle */
const dataItemSelector = ".".concat(rowColClasses.fieldRoot);
const getKeyAsToggleSelected = event => !(event !== null && event !== void 0 && event.metaKey || event !== null && event !== void 0 && event.ctrlKey);
function useSelectionsInteractions(_ref) {
var _loaderRef$current2;
let {
selectionState,
selections,
checkboxes = false,
doc = document,
loaderRef
} = _ref;
const currentSelect = reactExports.useRef({
startElemNumber: undefined,
elemNumbers: [],
isRange: false,
toggle: false,
active: false,
touchElemNumbers: [],
touchRangeSmall: false
});
reactExports.useEffect(() => {
var _loaderRef$current;
if (!((_loaderRef$current = loaderRef.current) !== null && _loaderRef$current !== void 0 && (_loaderRef$current = _loaderRef$current._listRef) !== null && _loaderRef$current !== void 0 && _loaderRef$current._outerRef)) {
return undefined;
}
const preventGestureStart = e => e.preventDefault();
const preventGestureChange = e => e.preventDefault();
const preventGestureEnd = e => e.preventDefault();
const listRef = loaderRef.current._listRef._outerRef;
listRef.addEventListener('gesturestart', preventGestureStart);
listRef.addEventListener('gesturechange', preventGestureChange);
listRef.addEventListener('gestureend', preventGestureEnd);
return () => {
listRef.removeEventListener('gesturestart', preventGestureStart);
listRef.removeEventListener('gesturechange', preventGestureChange);
listRef.removeEventListener('gestureend', preventGestureEnd);
};
}, [(_loaderRef$current2 = loaderRef.current) === null || _loaderRef$current2 === void 0 || (_loaderRef$current2 = _loaderRef$current2._listRef) === null || _loaderRef$current2 === void 0 ? void 0 : _loaderRef$current2._outerRef]);
// eslint-disable-next-line arrow-body-style
const doSelect = async () => {
var _selectionState$selec;
if ((_selectionState$selec = selectionState.selectDisabled) !== null && _selectionState$selec !== void 0 && _selectionState$selec.call(selectionState)) {
return false;
}
selectionState.setSelectableValuesUpdating();
return selectValues({
selections,
elemNumbers: currentSelect.current.elemNumbers,
isSingleSelect: selectionState.isSingleSelect,
toggle: currentSelect.current.toggle
});
};
const getRange = (start, end) => {
const elemNumbersOrdered = getElemNumbersFromPages(selectionState.enginePages);
return fillRange([start, end], elemNumbersOrdered);
};
const addToRange = elemNumber => {
const {
startElemNumber
} = currentSelect.current;
if (startElemNumber === elemNumber) {
return;
}
const toMaybeAdd = getRange(currentSelect.current.startElemNumber, elemNumber);
selectionState.updateItems(toMaybeAdd, true, currentSelect.current.elemNumbers);
};
const selectManually = async function () {
var _selectionState$selec2;
let elementIds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let additive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
let event = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
if ((_selectionState$selec2 = selectionState.selectDisabled) !== null && _selectionState$selec2 !== void 0 && _selectionState$selec2.call(selectionState)) {
return false;
}
const toggle = !selectionState.isSingleSelect && getKeyAsToggleSelected(event === null || event === void 0 ? void 0 : event.nativeEvent);
if (!toggle) {
selectionState.clearItemStates(true);
}
const elemNumbers = [];
selectionState.updateItems(elementIds, additive, elemNumbers);
selectionState.setSelectableValuesUpdating();
return selectValues({
selections,
elemNumbers: additive ? elemNumbers : elementIds,
isSingleSelect: selectionState.isSingleSelect,
toggle
});
};
const handleSingleSelectKey = (event, target) => {
if (event.ctrlKey || event.metaKey) {
target.focus(); // will not be focused otherwise
event.preventDefault();
}
};
const onChange = reactExports.useCallback(event => {
if (selectionState.selectDisabled()) {
return;
}
const elemNumber = +event.target.getAttribute('data-n');
const toggle = !selectionState.isSingleSelect && getKeyAsToggleSelected(event.nativeEvent);
currentSelect.current.elemNumbers = [elemNumber];
currentSelect.current.toggle = toggle;
if (!toggle) {
selectionState.clearItemStates(true);
}
selectionState.updateItem(elemNumber);
currentSelect.current.active = false;
doSelect();
}, []);
const onMouseDown = reactExports.useCallback(event => {
if (event.button !== 0 || selectionState.selectDisabled()) {
return;
}
const elemNumber = +event.currentTarget.getAttribute('data-n');
const toggle = !selectionState.isSingleSelect && getKeyAsToggleSelected(event);
currentSelect.current.isRange = false;
currentSelect.current.startElemNumber = elemNumber;
currentSelect.current.elemNumbers = [elemNumber];
currentSelect.current.toggle = toggle;
currentSelect.current.active = true;
if (!toggle) {
selectionState.clearItemStates(true);
}
selectionState.updateItem(elemNumber);
if (selectionState.isSingleSelect) {
currentSelect.current.active = false;
doSelect();
}
handleSingleSelectKey(event, event.currentTarget);
}, []);
const onMouseUp = reactExports.useCallback(event => {
if (event.button !== 0 || !currentSelect.current.active) {
return;
}
currentSelect.current.active = false;
if (currentSelect.current.isRange) {
const elemNumber = +event.currentTarget.getAttribute('data-n');
addToRange(elemNumber);
}
doSelect();
}, []);
const onMouseUpDoc = reactExports.useCallback(event => {
// Ensure we end interactions when mouseup happens outside the Listbox.
if (event.button !== 0 || !currentSelect.current.active) {
return;
}
currentSelect.current.active = false;
doSelect();
}, []);
const onMouseEnter = reactExports.useCallback(event => {
if (!currentSelect.current.active) {
return;
}
if (!currentSelect.current.isRange) {
currentSelect.current.isRange = true;
if (!selectionState.isSelected(currentSelect.current.startElemNumber)) {
selectionState.updateItem(currentSelect.current.startElemNumber, true);
currentSelect.current.elemNumbers = [];
}
}
const elemNumber = +event.currentTarget.getAttribute('data-n');
addToRange(elemNumber);
}, []);
const onTouchStart = reactExports.useCallback(event => {
var _event$touches$0$targ, _event$touches$1$targ;
// Handle range selection with two finger touch
if (currentSelect.current.active || currentSelect.current.isRange || selectionState.isSingleSelect || event.touches.length <= 1) {
return;
}
if (event.touches.length > 2) {
doSelect();
return;
}
const startTouchElemNumber = Number((_event$touches$0$targ = event.touches[0].target) === null || _event$touches$0$targ === void 0 || (_event$touches$0$targ = _event$touches$0$targ.closest(dataItemSelector)) === null || _event$touches$0$targ === void 0 ? void 0 : _event$touches$0$targ.getAttribute('data-n'));
const endTouchElemNumber = Number((_event$touches$1$targ = event.touches[1].target) === null || _event$touches$1$targ === void 0 || (_event$touches$1$targ = _event$touches$1$targ.closest(dataItemSelector)) === null || _event$touches$1$targ === void 0 ? void 0 : _event$touches$1$targ.getAttribute('data-n'));
if (Number.isNaN(startTouchElemNumber) || Number.isNaN(startTouchElemNumber)) {
doSelect();
return;
}
currentSelect.current.active = true;
const range = getRange(startTouchElemNumber, endTouchElemNumber);
if (range.length < 7) {
currentSelect.current.touchRangeSmall = true;
}
currentSelect.current.elemNumbers = [];
currentSelect.current.touchElemNumbers = [startTouchElemNumber, endTouchElemNumber];
}, []);
const onTouchEnd = reactExports.useCallback(() => {
if (currentSelect.current.touchElemNumbers.length !== 2) {
return;
}
if (currentSelect.current.touchRangeSmall) {
currentSelect.current.touchRangeSmall = false;
currentSelect.current.touchElemNumbers = [];
currentSelect.current.active = false;
return;
}
const [startTouchElemNumber, endTouchElemNumber] = currentSelect.current.touchElemNumbers;
currentSelect.current.startElemNumber = startTouchElemNumber;
addToRange(endTouchElemNumber);
currentSelect.current.touchElemNumbers = [];
currentSelect.current.active = false;
currentSelect.current.toggle = true;
doSelect();
}, []);
reactExports.useEffect(() => {
doc.addEventListener('mouseup', onMouseUpDoc);
return () => {
doc.removeEventListener('mouseup', onMouseUpDoc);
};
}, [onMouseUpDoc]);
reactExports.useEffect(() => {
const clearItemStates = () => {
selectionState.clearItemStates(false);
};
const onCleared = () => {
selectionState.clearItemStates(true);
selectionState.triggerStateChanged();
};
selections.on('clearItemStates', clearItemStates);
selections.on('deactivated', clearItemStates);
selections.on('cleared', onCleared);
return () => {
selections.removeListener('clearItemStates', clearItemStates);
selections.removeListener('deactivated', clearItemStates);
selections.removeListener('cleared', onCleared);
};
}, [selections]);
const interactionEvents = {};
if (checkboxes) {
Object.assign(interactionEvents, {
onChange
});
} else {
Object.assign(interactionEvents, {
onMouseUp,
onMouseDown,
onMouseEnter,
onTouchStart,
onTouchEnd
});
}
return {
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));
/**
* @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 isExcluded = c => c ? c.qState === 'X' || c.qState === 'XS' || c.qState === 'XL' : null;
const isAlternative = c => c ? c.qState === 'A' : null;
const excludedOrAlternative = _ref => {
let {
cell,
checkboxes
} = _ref;
return (isAlternative(cell) || isExcluded(cell)) && checkboxes;
};
function getSelectionStateClass(_ref2) {
let {
cell,
showGray
} = _ref2;
let selectionStateClass;
switch (cell.qState) {
case 'XS':
selectionStateClass = showGray ? rowColClasses.XS : rowColClasses.S;
break;
case 'S':
case 'L':
selectionStateClass = rowColClasses.S;
break;
case 'A':
selectionStateClass = showGray ? rowColClasses.A : false;
break;
case 'X':
case 'XL':
selectionStateClass = showGray ? rowColClasses.X : false;
break;
default:
selectionStateClass = false;
}
return selectionStateClass;
}
const getValueStateClasses = _ref3 => {
let {
column,
histogram,
cell,
showGray
} = _ref3;
if (!cell) {
return [];
}
const clazzArr = [column ? rowColClasses.column : rowColClasses.row];
if (!histogram) {
clazzArr.push(rowColClasses.rowBorderBottom);
}
const selectionStateClass = getSelectionStateClass({
cell,
showGray
});
if (selectionStateClass) {
clazzArr.push(selectionStateClass);
}
return clazzArr;
};
const CELL_PADDING_LEFT = 9;
const HEADER_PADDING_RIGHT = 4;
const ICON_WIDTH = 12;
const ICON_PADDING = 7;
const BUTTON_ICON_WIDTH = ICON_WIDTH + (ICON_PADDING + 1) * 2; // 1 is border width
const REMOVE_TICK_LIMIT = 80; // an item width equal to or less than this, will hide the select tick
const SCROLL_BAR_WIDTH = 10; // TODO: ignore this - instead set the styling only show on hover...
const ITEM_MAX_WIDTH = 150;
const ITEM_MIN_WIDTH = 56;
const CHECKBOX_WIDTH = 20;
const frequencyTextNone = '-';
const barPadPx = 4;
const barBorderWidthPx = 1;
const barWithCheckboxLeftPadPx = 29;
const GRID_ROW_HEIGHT = 32;
const LIST_ROW_HEIGHT = 29;
const DENSE_ROW_HEIGHT = 20; // same for both list and grid in dense mode
const GRID_ITEM_PADDING = 4;
const joinClassNames = namesArray => namesArray.filter(c => !!c).join(' ').trim();
const getBarWidth = _ref => {
let {
qFrequency,
frequencyMax
} = _ref;
const freqStr = String(qFrequency);
const isPercent = freqStr.substring(freqStr.length - 1) === '%';
const freq = parseFloat(isPercent ? freqStr : qFrequency);
const width = isPercent ? freq : freq / frequencyMax * 100;
return "".concat(width, "%");
};
const getFrequencyText = qFrequency => qFrequency || frequencyTextNone;
const _excluded$5 = ["backgroundColor"];
const getFreqFlexBasis = _ref => {
let {
sizes,
frequencyMode,
isGridMode,
freqHitsValue
} = _ref;
if (frequencyMode === 'P') {
return "".concat(sizes.freqMinWidth, "px");
}
const flexBasis = isGridMode && !freqHitsValue ? 'max-content' : '25%';
return flexBasis;
};
const getMaxFreqWidth = _ref2 => {
let {
sizes,
frequencyMode,
isGridMode
} = _ref2;
if (isGridMode) {
// This makes the neighbouring value stretch farther than when using a fixed freuency width.
return 'max-content';
}
if (frequencyMode === 'P') {
return sizes.freqMinWidth; // because it will never grow beyond "100.0%"
}
return sizes.freqMaxWidth;
};
const getRowSelectionStyle = _ref3 => {
let {
theme,
checkboxes,
styles,
selectionState
} = _ref3;
if (checkboxes) {
if (selectionState === 'selected') {
return {
["& .".concat(rowColClasses.labelText)]: {
// Override labels (value and frequency count) color when selected.
color: styles.selections.selected
}
};
}
return {};
}
const selectionStyles = styles.selections;
const backgroundColor = selectionStyles[selectionState];
const contrastTextColor = selectionStyles["".concat(selectionState, "Contrast")];
return {
background: backgroundColor,
color: contrastTextColor,
'&:focus': {
boxShadow: "inset 0 0 0 2px ".concat(theme.palette.custom.focusBorder),
outline: 'none'
},
'& $cell': {
paddingRight: 0
},
// Override default label text style for selection states
// when contrasting text is needed.
["& .".concat(rowColClasses.labelText)]: {
color: contrastTextColor
},
["& .".concat(rowColClasses.icon)]: {
color: contrastTextColor
}
};
};
const ellipsis = {
width: '100%',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
};
const iconWidth = 24; // tick and lock icon width in px
const RowColRoot = styled('div', {
shouldForwardProp: prop => !['checkboxes', 'isGridMode', 'isGridCol', 'dense', 'direction', 'sizes', 'frequencyMode', 'freqHitsValue', 'layout', 'styles'].includes(prop)
})(_ref4 => {
let {
theme,
checkboxes,
isGridMode,
isGridCol,
dense,
direction,
sizes,
frequencyMode,
freqHitsValue,
styles
} = _ref4;
// eslint-disable-next-line no-unused-vars
const _styles$content = styles.content,
{
backgroundColor: _
} = _styles$content,
contentFontStyles = _objectWithoutProperties(_styles$content, _excluded$5);
const rowSelectionStyle = getRowSelectionStyle({
theme,
styles,
checkboxes,
selectionState: 'selected'
});
const rowExcludedStyle = getRowSelectionStyle({
theme,
styles,
checkboxes,
selectionState: 'excluded'
});
const barDefaultFilledStyle = {
height: '100%',
transition: 'width 0.2s',
border: "".concat(barBorderWidthPx, "px solid"),
borderColor: '#D9D9D9',
// overridden by selected color (classes.S),
backgroundColor: '#FAFAFA'
};
const barSelectedFilledStyle = {
opacity: '30%'
};
return {
'&:focus': {
boxShadow: "inset 0 0 0 2px ".concat(theme.palette.custom.focusBorder, " !important")
},
'&:focus-visible': {
outline: 'none'
},
'& .value': {
'&:focus': {
boxShadow: "inset 0 0 0 2px ".concat(theme.palette.custom.focusBorder, " !important")
},
'&:focus-visible': {
outline: 'none'
}
},
["& .".concat(rowColClasses.row)]: _objectSpread2({
flexWrap: 'nowrap'
}, styles.content),
["& .".concat(rowColClasses.rowBorderBottom)]: {
borderBottom: isGridCol ? 'none' : "1px solid ".concat(theme.palette.divider),
borderLeft: isGridCol ? "1px solid ".concat(theme.palette.divider) : 'none'
},
["& .".concat(rowColClasses.column)]: _objectSpread2({
flexWrap: 'nowrap',
borderRight: "1px solid ".concat(theme.palette.divider)
}, styles.content),
// The interior wrapper for all field content.
["& .".concat(rowColClasses.cell)]: {
zIndex: 2,
display: 'flex',
alignItems: 'center',
flexGrow: 1,
minWidth: checkboxes ? '52px' : '26px',
// these numbers are just enough to show one letter and ellipsis: A…
flexBasis: checkboxes ? 'auto' : 'max-content',
// Note that this padding is overridden when using checkboxes.
paddingLeft: "".concat(CELL_PADDING_LEFT, "px"),
paddingRight: 0
},
// The leaf node, containing the label text.
["& .".concat(rowColClasses.labelText)]: _objectSpread2(_objectSpread2({
lineHeight: '24px',
userSelect: 'none',
paddingRight: '1px'
}, ellipsis), contentFontStyles),
["& .".concat(rowColClasses.labelDense)]: {
lineHeight: '18px'
},
// Highlight is added to labelText spans, which are created as children to original labelText,
// when a search string is matched.
["& .".concat(rowColClasses.highlighted)]: {
backgroundColor: '#FFC72A'
},
// Checkbox and label container.
["& .".concat(rowColClasses.checkboxLabel)]: {
margin: 0,
width: '100%',
height: '100%',
overflow: 'hidden',
// The checkbox's span
'& > span:nth-of-type(1)': {
paddingRight: '8px'
},
// The checkbox's label container.
'& > span:nth-of-type(2)': _objectSpread2(_objectSpread2({}, ellipsis), {}, {
display: 'flex',
alignItems: 'center',
paddingLeft: 0,
paddingRight: '2px'
})
},
// The icons container holding tick and lock, shown inside fields.
["& .".concat(rowColClasses.icon)]: {
display: 'flex',
justifyContent: 'center',
width: iconWidth,
minWidth: iconWidth,
maxWidth: iconWidth,
color: contentFontStyles.color
},
// Selection styles (S=Selected, XS=ExcludedSelected, A=Alternative, X=Excluded).
["& .".concat(rowColClasses.S)]: _objectSpread2(_objectSpread2({}, rowSelectionStyle), {}, {
border: isGridMode ? 'none' : undefined
}),
["& .".concat(rowColClasses.XS)]: _objectSpread2(_objectSpread2({}, getRowSelectionStyle({
theme,
styles,
checkboxes,
selectionState: 'selectedExcluded'
})), {}, {
border: isGridMode ? 'none' : undefined
}),
["& .".concat(rowColClasses.A)]: _objectSpread2(_objectSpread2({}, getRowSelectionStyle({
theme,
styles,
checkboxes,
selectionState: 'alternative'
})), {}, {
border: isGridMode ? 'none' : undefined
}),
["& .".concat(rowColClasses.X)]: _objectSpread2(_objectSpread2({}, rowExcludedStyle), {}, {
border: isGridMode ? 'none' : undefined
}),
["& .".concat(rowColClasses.X, ", & .").concat(rowColClasses.XS)]: {
// Override the selected color for bar-filled, when the value is selected and excluded.
border: isGridMode ? 'none' : undefined,
["& .".concat(rowColClasses.barSelected, " .bar-filled")]: _objectSpread2({}, barDefaultFilledStyle)
},
["& .".concat(rowColClasses.frequencyCount)]: _objectSpread2(_objectSpread2({
zIndex: 3,
justifyContent: 'flex-end'
}, ellipsis), {}, {
flex: "0 0 ".concat(getFreqFlexBasis({
sizes,
frequencyMode,
isGridMode,
freqHitsValue
})),
minWidth: !isGridMode && frequencyMode !== 'P' && freqHitsValue ? sizes.freqMinWidth : 'max-content',
maxWidth: getMaxFreqWidth({
sizes,
frequencyMode,
isGridMode
}),
textAlign: direction === 'rtl' ? 'left' : 'right',
// In RTL, we already get the 8px from the value element's padding and for
// percent mode we have already adapted the width (fixed width) to the max number.
paddingLeft: direction !== 'rtl' ? '8px' : 0
}),
["&.".concat(rowColClasses.barContainer)]: {
height: '100%',
display: 'flex',
alignItems: 'center'
},
["& .".concat(rowColClasses.bar)]: {
height: dense ? '16px' : '20px',
position: 'absolute',
zIndex: 1,
alignSelf: 'center',
left: barPadPx,
width: "calc(100% - ".concat(barPadPx * 2, "px)"),
display: 'flex',
alignItems: 'center',
'& .bar-filled': _objectSpread2({}, barDefaultFilledStyle)
},
["& .".concat(rowColClasses.barSelected)]: {
'& .bar-filled': _objectSpread2({}, barSelectedFilledStyle)
},
["& .".concat(rowColClasses.barWithCheckbox)]: {
left: direction === 'rtl' ? barPadPx : barWithCheckboxLeftPadPx,
width: "calc(100% - ".concat(barWithCheckboxLeftPadPx + barPadPx, "px)")
},
["& .".concat(rowColClasses.barSelectedWithCheckbox)]: {
'& .bar-filled': _objectSpread2(_objectSpread2({}, barSelectedFilledStyle), {}, {
backgroundColor: styles.selections.selected || '#BFE5D0',
borderColor: styles.selections.selected
})
},
["& .".concat(rowColClasses.excludedTextWithCheckbox)]: {
color: styles.content.color,
fontStyle: 'italic'
}
};
});
var RowColRoot$1 = React.memo(RowColRoot);
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 PREFIX$b = 'ListBoxCheckbox';
const borderRadius = 3;
const classes$b = {
cbIcon: "".concat(PREFIX$b, "-cbIcon"),
cbIconChecked: "".concat(PREFIX$b, "-cbIconChecked"),
cbIconExcluded: "".concat(PREFIX$b, "-cbIconExcluded"),
cbIconAlternative: "".concat(PREFIX$b, "-cbIconAlternative"),
checkbox: "".concat(PREFIX$b, "-checkbox"),
dense: "".concat(PREFIX$b, "-dense")
};
const StyledCheckbox = styled(Checkbox, {
shouldForwardProp: p => p !== 'styles'
})(_ref => {
let {
styles
} = _ref;
return {
["& .".concat(classes$b.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'
},
["& .".concat(classes$b.cbIconChecked)]: {
borderRadius,
backgroundColor: styles.selections.selected,
backgroundImage: 'linear-gradient(180deg,hsla(0,0%,100%,.1),hsla(0,0%,100%,0))',
'&:before': {
display: 'block',
width: 16,
height: 16,
backgroundImage: CheckboxChecked,
content: '""'
}
},
["& .".concat(classes$b.cbIconExcluded)]: {
borderRadius: borderRadius - 1,
width: 12,
height: 12,
backgroundColor: styles.selections.excluded
},
["& .".concat(classes$b.cbIconAlternative)]: {
borderRadius: borderRadius - 1,
width: 12,
height: 12,
backgroundColor: styles.selections.alternative
},
["&.".concat(classes$b.checkbox)]: {
margin: 0,
'&:hover': {
backgroundColor: 'inherit !important'
}
},
["&.".concat(classes$b.dense)]: {
padding: '4px 8px'
}
};
});
const getIcon = function (cls) {
let showGray = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
let excluded = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return /*#__PURE__*/React.createElement("span", {
className: cls.cbIcon
}, excluded && /*#__PURE__*/React.createElement("span", {
className: showGray && excluded ? cls.cbIconExcluded : ''
}));
};
function ListboxCheckbox(_ref2) {
let {
onChange,
checked,
label,
dense,
excluded,
styles,
showGray = true,
dataN
} = _ref2;
return /*#__PURE__*/React.createElement(StyledCheckbox, {
edge: "start",
onChange: onChange,
checked: checked,
disableRipple: true,
className: [classes$b.checkbox, dense && classes$b.dense].filter(Boolean).join(' '),
inputProps: {
'aria-labelledby': label,
'data-n': dataN
},
name: label,
icon: getIcon(classes$b, showGray, excluded),
checkedIcon: /*#__PURE__*/React.createElement("span", {
className: classes$b.cbIconChecked
}),
styles: styles
});
}
const PREFIX$a = 'ListBoxRadioButton';
const classes$a = {
radioButton: "".concat(PREFIX$a, "-radioButton")
};
const StyledRadio = styled(Radio, {
shouldForwardProp: p => !['dense', 'styles'].includes(p)
})(_ref => {
let {
checked,
styles,
dense
} = _ref;
return {
["&.".concat(classes$a.radioButton)]: {
right: '5px',
color: checked ? styles.selections.selected : styles.content.color,
padding: dense ? '0px 0px 0px 12px' : undefined,
backgroundColor: 'transparent'
}
};
});
function ListBoxRadioButton(_ref2) {
let {
onChange,
checked,
label,
dense,
dataN,
styles
} = _ref2;
return /*#__PURE__*/React.createElement(StyledRadio, {
checked: checked,
onChange: onChange,
value: label,
name: label,
className: classes$a.radioButton,
inputProps: {
'data-n': dataN
},
disableRipple: true,
size: dense ? 'small' : 'medium',
dense: dense,
styles: styles
});
}
function ValueField(_ref) {
let {
label,
dense,
showGray = true,
checkboxes,
cell,
valueTextAlign
} = _ref;
return /*#__PURE__*/React.createElement(Typography, {
component: "span",
variant: "body2",
className: joinClassNames([rowColClasses.labelText, dense && rowColClasses.labelDense, showGray && excludedOrAlternative({
cell,
checkboxes
}) && rowColClasses.excludedTextWithCheckbox]),
align: valueTextAlign,
dir: "auto"
}, /*#__PURE__*/React.createElement("span", null, label));
}
function LabelTag(_ref) {
let {
label,
color,
dense,
showGray,
checkboxes,
cell,
valueTextAlign
} = _ref;
if (typeof label === 'string') {
return /*#__PURE__*/React.createElement(ValueField, {
label: label,
color: color,
dense: dense,
showGray: showGray,
checkboxes: checkboxes,
cell: cell,
valueTextAlign: valueTextAlign
});
}
return label;
}
function CheckboxField(_ref) {
let {
onChange,
label,
qElemNumber,
isSelected,
dense,
cell,
isGridCol,
showGray,
isSingleSelect,
checkboxes,
valueTextAlign,
styles
} = _ref;
const cb = /*#__PURE__*/React.createElement(ListboxCheckbox, {
onChange: onChange,
label: label,
checked: isSelected,
dense: dense,
excluded: isExcluded(cell),
isGridCol: isGridCol,
showGray: showGray,
dataN: qElemNumber,
styles: styles
});
const rb = /*#__PURE__*/React.createElement(ListBoxRadioButton, {
onChange: onChange,
label: label,
checked: isSelected,
dense: dense,
dataN: qElemNumber,
styles: styles
});
return /*#__PURE__*/React.createElement(FormControlLabel, {
control: isSingleSelect ? rb : cb,
className: rowColClasses.checkboxLabel,
label: /*#__PURE__*/React.createElement(LabelTag, {
label: label,
dense: dense,
showGray: showGray,
checkboxes: checkboxes,
cell: cell,
valueTextAlign: valueTextAlign
}),
key: qElemNumber
});
}
function LabelsWithRanges(_ref) {
let {
labels,
dense,
showGray,
checkboxes
} = _ref;
const text = labels.map((_ref2, index) => {
let [label, highlighted] = _ref2;
return /*#__PURE__*/React.createElement("span", {
id: index,
className: highlighted ? rowColClasses.highlighted : ''
}, label);
});
return /*#__PURE__*/React.createElement(ValueField, {
label: text,
dense: dense,
showGray: showGray,
checkboxes: checkboxes
});
}
function FieldWithRanges(_ref3) {
let {
onChange,
labels,
checkboxes,
dense,
showGray,
qElemNumber,
isSelected,
cell,
isGridCol,
isSingleSelect,
valueTextAlign,
styles
} = _ref3;
const LWR = /*#__PURE__*/React.createElement(LabelsWithRanges, {
labels: labels,
dense: dense,
showGray: showGray,
checkboxes: checkboxes
});
return checkboxes ? /*#__PURE__*/React.createElement(CheckboxField, {
onChange: onChange,
label: LWR,
qElemNumber: qElemNumber,
isSelected: isSelected,
dense: dense,
cell: cell,
isGridCol: isGridCol,
showGray: showGray,
isSingleSelect: isSingleSelect,
checkboxes: checkboxes,
valueTextAlign: valueTextAlign,
styles: styles
}) : LWR;
}
function Field(_ref) {
let {
onChange,
label,
qElemNumber,
isSelected,
dense,
cell,
isGridCol,
showGray,
isSingleSelect,
checkboxes,
valueTextAlign,
styles
} = _ref;
return checkboxes ? /*#__PURE__*/React.createElement(CheckboxField, {
onChange: onChange,
label: label,
qElemNumber: qElemNumber,
isSelected: isSelected,
dense: dense,
cell: cell,
isGridCol: isGridCol,
showGray: showGray,
isSingleSelect: isSingleSelect,
checkboxes: checkboxes,
valueTextAlign: valueTextAlign,
styles: styles
}) : /*#__PURE__*/React.createElement(ValueField, {
label: label,
dense: dense,
showGray: true,
checkboxes: checkboxes,
cell: cell,
valueTextAlign: valueTextAlign
});
}
var Field$1 = React.memo(Field);
function Histogram(_ref) {
let {
qFrequency,
histogram,
checkboxes,
isSelected,
frequencyMax
} = _ref;
const hasHistogramBar = qFrequency && histogram && getFrequencyText(qFrequency) !== frequencyTextNone;
if (!hasHistogramBar) {
return undefined;
}
const width = getBarWidth({
qFrequency,
frequencyMax
});
return /*#__PURE__*/React.createElement(Box, {
className: joinClassNames([rowColClasses.bar, checkboxes && rowColClasses.barWithCheckbox, isSelected && (checkboxes ? rowColClasses.barSelectedWithCheckbox : rowColClasses.barSelected)])
}, /*#__PURE__*/React.createElement(Box, {
className: "bar-filled",
width: width
}));
}
function Frequency(_ref) {
let {
cell,
checkboxes,
dense,
showGray
} = _ref;
const frequencyText = getFrequencyText(cell === null || cell === void 0 ? void 0 : cell.qFrequency);
return /*#__PURE__*/React.createElement(Grid, {
item: true,
style: {
display: 'flex',
alignItems: 'center'
},
className: rowColClasses.frequencyCount,
"aria-label": frequencyText,
title: frequencyText
}, /*#__PURE__*/React.createElement(Typography, {
noWrap: true,
color: "inherit",
variant: "body2",
className: joinClassNames([dense && rowColClasses.labelDense, rowColClasses.labelText, showGray && excludedOrAlternative({
cell,
checkboxes
}) && rowColClasses.excludedTextWithCheckbox])
}, frequencyText));
}
function getGridItemSizes(_ref) {
let {
dataLayout,
layoutOrder,
itemPadding,
fillHeight
} = _ref;
// Simulate margin/padding by making the item smaller than its container.
if (dataLayout === 'singleColumn') {
return {
height: '100%',
width: '100%'
};
}
switch (layoutOrder) {
case 'row':
return {
height: fillHeight ? '100%' : "calc(100% - ".concat(itemPadding, "px)"),
width: "calc(100% - ".concat(2 * itemPadding, "px)"),
position: 'absolute',
left: 4
};
case 'column':
return {
height: fillHeight ? '100%' : "calc(100% - ".concat(itemPadding, "px)"),
width: "calc(100% - ".concat(2 * itemPadding, "px)"),
position: 'absolute',
left: 4
};
default:
return {};
}
}
const ItemGrid = styled(Grid, {
shouldForwardProp: prop => !['dataLayout', 'layoutOrder', 'itemPadding', 'cellPaddingRight', 'direction', 'fillHeight'].includes(prop)
})(_ref => {
let {
dataLayout,
layoutOrder,
itemPadding,
cellPaddingRight,
direction,
fillHeight
} = _ref;
const att = "padding".concat(direction === 'rtl' ? 'Left' : 'Right');
return {
["&.".concat(rowColClasses.fieldRoot)]: _objectSpread2(_objectSpread2({}, getGridItemSizes({
dataLayout,
layoutOrder,
itemPadding,
fillHeight
})), {}, {
[att]: cellPaddingRight ? '8px' : undefined
})
};
});
function getCellFromPages(_ref) {
let {
pages,
cellIndex
} = _ref;
let c;
const page = pages.filter(p => p.qArea.qTop <= cellIndex && cellIndex < p.qArea.qTop + p.qArea.qHeight)[0];
if (page) {
const area = page.qArea;
if (cellIndex >= area.qTop && cellIndex < area.qTop + area.qHeight) {
[c] = page.qMatrix[cellIndex - area.qTop];
}
}
return c;
}
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 removeInnnerTabStops(container) {
container === null || container === void 0 || container.querySelectorAll('[tabIndex="0"]').forEach(elm => {
elm.setAttribute('tabIndex', -1);
});
}
function removeLastFocused(container) {
container === null || container === void 0 || container.querySelectorAll('.last-focused').forEach(elm => {
elm.classList.remove('last-focused');
});
}
function getVizCell(container) {
return (container === null || container === void 0 ? void 0 : container.closest('.njs-cell')) || (container === null || container === void 0 ? void 0 : container.closest('.qv-gridcell')) || (container === null || container === void 0 ? void 0 : container.closest('.qv-gs-listbox'));
}
// Emulate the keyboard hook, until we support it in the Listbox.
function useTempKeyboard(_ref) {
let {
containerRef,
enabled
} = _ref;
const [keyboardActive, setKeyboardActive] = reactExports.useState(false);
const keyboard = {
enabled,
active: keyboardActive,
// innerTabStops: whether keyboard permits inner tab stops
// (inner = everything inside .listbox-container)
innerTabStops: !enabled || keyboardActive,
blur(resetFocus) {
var _containerRef$current;
if (!enabled) {
return;
}
setKeyboardActive(false);
const vizCell = getVizCell(containerRef.current) || ((_containerRef$current = containerRef.current) === null || _containerRef$current === void 0 ? void 0 : _containerRef$current.parentElement);
removeInnnerTabStops(containerRef.current);
removeLastFocused(containerRef.current);
if (resetFocus && vizCell) {
// Move focus to the viz's cell.
vizCell.setAttribute('tabIndex', 0);
containerRef.current.setAttribute('tabIndex', -1);
vizCell.focus();
}
},
focus() {
if (!enabled) {
return;
}
setKeyboardActive(true);
const c = containerRef.current;
const searchField = c === null || c === void 0 ? void 0 : c.querySelector('.search input');
const lastSelectedRow = c === null || c === void 0 ? void 0 : c.querySelector('.value.last-focused');
const firstRowElement = c === null || c === void 0 ? void 0 : c.querySelector('.value.selector, .value');
const confirmButton = c === null || c === void 0 ? void 0 : c.querySelector('.actions-toolbar-default-actions .actions-toolbar-confirm');
const unlockCoverButton = c === null || c === void 0 ? void 0 : c.querySelector('#listbox-unlock-button');
const cyclicButton = c === null || c === void 0 ? void 0 : c.querySelector('.listbox-cyclic-button');
const elementToFocus = cyclicButton || searchField || lastSelectedRow || firstRowElement || unlockCoverButton || confirmButton;
elementToFocus === null || elementToFocus === void 0 || elementToFocus.setAttribute('tabIndex', 0);
elementToFocus === null || elementToFocus === void 0 || elementToFocus.focus();
},
focusSelection() {
const unlockCoverButton = document.querySelector('#listbox-unlock-button');
const confirmButton = document.querySelector('.actions-toolbar-default-actions .actions-toolbar-confirm:not(:disabled)');
const btnToFocus = unlockCoverButton || confirmButton;
btnToFocus === null || btnToFocus === void 0 || btnToFocus.setAttribute('tabIndex', 0);
btnToFocus === null || btnToFocus === void 0 || btnToFocus.focus();
return btnToFocus;
}
};
return keyboard;
}
const getElementIndex = currentTarget => +currentTarget.getAttribute('data-n');
const focusSearch = container => {
const searchField = container === null || container === void 0 ? void 0 : container.querySelector('.search input');
searchField === null || searchField === void 0 || searchField.focus();
return searchField;
};
const focusRow = container => {
const lastFocusedRow = container === null || container === void 0 ? void 0 : container.querySelector('.value.last-focused');
const selectorRow = container === null || container === void 0 ? void 0 : container.querySelector('.value.selector');
const row = container === null || container === void 0 ? void 0 : container.querySelector('.value');
const rowToFocus = lastFocusedRow || selectorRow || row;
rowToFocus === null || rowToFocus === void 0 || rowToFocus.setAttribute('tabIndex', 0);
rowToFocus === null || rowToFocus === void 0 || rowToFocus.focus();
removeLastFocused(container);
return rowToFocus;
};
const focusCyclicButton = container => {
const button = container === null || container === void 0 ? void 0 : container.querySelector('.listbox-cyclic-button:not(:disabled)');
button === null || button === void 0 || button.setAttribute('tabIndex', 0);
button === null || button === void 0 || button.focus();
return button;
};
const blur$1 = (event, keyboard) => {
if (!keyboard.enabled) return;
const {
currentTarget,
target
} = event;
const isFocusedOnListbox = target.classList.contains('listbox-container');
const container = currentTarget.closest('.listbox-container');
const vizCell = getVizCell(container);
const isSingleListbox = (vizCell === null || vizCell === void 0 ? void 0 : vizCell.querySelectorAll('.listbox-container').length) === 1;
if (isFocusedOnListbox || isSingleListbox) {
// Move the focus from listbox container to the viz container.
keyboard.blur(true);
} else {
// More than one listbox: Move focus from row to listbox container.
// 1. Remove last-focused class from row siblings.
removeLastFocused(container);
// 2. Add last-focused class so we can re-focus it later.
currentTarget.classList.add('last-focused');
// 3. Blur row and focus the listbox container.
keyboard.blur();
const c = currentTarget.closest('.listbox-container');
c.setAttribute('tabIndex', -1);
c === null || c === void 0 || c.focus();
}
};
// Find next item index to focus in the dom element list on key up and key down
const findNextItemIndex = _ref => {
let {
rowIndex,
columnIndex,
rowCount,
columnCount,
layoutOrder,
keyCode,
numCells
} = _ref;
const getNumCellsInColumn = colIdx => {
let remain;
if (layoutOrder === 'row') {
remain = numCells % columnCount;
return colIdx < remain ? rowCount : rowCount - 1;
}
remain = numCells % rowCount;
return colIdx < columnCount - 1 ? rowCount : remain;
};
let nextRowIndex = rowIndex;
let nextColumnIndex = columnIndex;
if (keyCode === KEYS.ARROW_DOWN) {
if (rowIndex >= getNumCellsInColumn(columnIndex) - 1) {
if (columnIndex === columnCount - 1) return -1;
nextRowIndex = 0;
nextColumnIndex = columnIndex + 1;
} else {
nextRowIndex = rowIndex + 1;
}
} else if (rowIndex === 0) {
if (columnIndex === 0) return -1;
nextRowIndex = getNumCellsInColumn(columnIndex - 1) - 1;
nextColumnIndex = columnIndex - 1;
} else {
nextRowIndex = rowIndex - 1;
}
// Convert from row, column indices to the element index in the dom element list
if (layoutOrder === 'row') {
return nextRowIndex * columnCount + nextColumnIndex;
}
// The dom element list is always row order. If the layout is column order then the conversion is not straight forward
const remain = numCells % rowCount;
if (remain === 0 || nextRowIndex < remain) return nextRowIndex * columnCount + nextColumnIndex;
return (nextRowIndex - remain) * (columnCount - 1) + nextColumnIndex + remain * columnCount;
};
function getRowsKeyboardNavigation(_ref) {
let {
select,
selectAll,
onCtrlF,
confirm,
cancel,
setScrollPosition,
focusListItems,
keyboard,
isModal,
rowCount,
columnCount,
rowIndex,
columnIndex,
layoutOrder
} = _ref;
const getElement = function (keyCode, elm) {
let next = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (keyCode === KEYS.ARROW_LEFT || keyCode === KEYS.ARROW_RIGHT || !(typeof rowIndex === 'number' && typeof columnIndex === 'number')) {
const parentElm = elm === null || elm === void 0 ? void 0 : elm.parentElement[next ? 'nextElementSibling' : 'previousElementSibling'];
return parentElm === null || parentElm === void 0 ? void 0 : parentElm.querySelector('[role]');
}
const gridElm = elm === null || elm === void 0 ? void 0 : elm.parentElement.parentElement;
const numCells = gridElm === null || gridElm === void 0 ? void 0 : gridElm.childElementCount;
if (numCells) {
const nextIndex = findNextItemIndex({
rowIndex,
columnIndex,
rowCount,
columnCount,
layoutOrder,
keyCode,
numCells
});
const nextElm = elm === null || elm === void 0 ? void 0 : elm.parentElement.parentElement.children[nextIndex];
return nextElm === null || nextElm === void 0 ? void 0 : nextElm.querySelector('[role]');
}
return undefined;
};
let startedRange = false;
const setStartedRange = val => {
startedRange = val;
};
const handleKeyDown = event => {
let elementToFocus;
const {
currentTarget,
nativeEvent
} = event;
const {
keyCode,
shiftKey = false,
ctrlKey = false,
metaKey = false
} = nativeEvent;
switch (keyCode) {
case KEYS.TAB:
{
// Try to focus search field, otherwise confirm button.
const container = currentTarget.closest('.listbox-container');
const inSelection = typeof isModal !== 'undefined' ? isModal() : undefined;
// TODO: use a store to keep track of this row.
currentTarget.classList.add('last-focused'); // so that we can go back here when we tab back
const useDefaultBrowserSupport = !(keyboard !== null && keyboard !== void 0 && keyboard.enabled);
if (useDefaultBrowserSupport) {
if (!inSelection) return;
keyboard.focusSelection();
event.preventDefault();
event.stopPropagation();
return;
}
if (shiftKey) {
if (!focusSearch(container) && !focusCyclicButton(container)) {
if (inSelection) {
keyboard.focusSelection();
} else {
blur$1(event, keyboard);
}
}
break;
}
// Without shift key
if (!keyboard.focusSelection() && !focusCyclicButton(container) && !focusSearch(container)) {
currentTarget.blur();
blur$1(event, keyboard);
}
break;
}
case KEYS.SHIFT:
// This is to ensure we include the first value when starting a range selection.
setStartedRange(true);
break;
case KEYS.SPACE:
select([getElementIndex(currentTarget)], false, event);
break;
case KEYS.ARROW_DOWN:
case KEYS.ARROW_RIGHT:
elementToFocus = getElement(keyCode, currentTarget, true);
if (shiftKey && elementToFocus) {
if (startedRange) {
select([getElementIndex(currentTarget)], true);
setStartedRange(false);
}
select([getElementIndex(elementToFocus)], true);
}
break;
case KEYS.ARROW_UP:
case KEYS.ARROW_LEFT:
elementToFocus = getElement(keyCode, currentTarget, false);
if (shiftKey && elementToFocus) {
if (startedRange) {
select([getElementIndex(currentTarget)], true);
setStartedRange(false);
}
select([getElementIndex(elementToFocus)], true);
}
break;
case KEYS.ENTER:
confirm();
if (typeof isModal === 'undefined') {
return;
}
break;
case KEYS.ESCAPE:
if (typeof isModal === 'undefined') {
cancel();
return;
}
if (isModal()) {
cancel();
} else {
return; // propagate to other Esc handler
}
break;
case KEYS.HOME:
focusListItems.setFirst(true);
if (ctrlKey) {
setScrollPosition === null || setScrollPosition === void 0 || setScrollPosition('overflowStart');
break;
}
setScrollPosition === null || setScrollPosition === void 0 || setScrollPosition('start');
break;
case KEYS.END:
focusListItems.setLast(true);
if (ctrlKey) {
setScrollPosition === null || setScrollPosition === void 0 || setScrollPosition('overflowEnd');
break;
}
setScrollPosition === null || setScrollPosition === void 0 || setScrollPosition('end');
break;
case KEYS.A:
if (ctrlKey || metaKey) {
selectAll();
break;
}
return;
case KEYS.F:
if (ctrlKey || metaKey) {
onCtrlF();
break;
}
return;
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 getValueTextAlign(_ref) {
let {
direction,
cell,
textAlign
} = _ref;
const isNumeric = !['NaN', undefined].includes(cell === null || cell === void 0 ? void 0 : cell.qNum);
let valueTextAlign;
const isAutoTextAlign = !textAlign || textAlign.auto;
const dirToTextAlignMap = {
rtl: 'right',
ltr: 'left'
};
if (isAutoTextAlign) {
if (!isNumeric) {
valueTextAlign = dirToTextAlignMap[direction];
} else {
valueTextAlign = direction === 'rtl' ? 'left' : 'right';
}
} else {
valueTextAlign = (textAlign === null || textAlign === void 0 ? void 0 : textAlign.align) || 'left';
}
const ALLOWED_OPTIONS = ['left', 'center', 'right'];
return ALLOWED_OPTIONS.includes(valueTextAlign) ? valueTextAlign : 'left';
}
const LOC_STATES = {
S: 'Object.Listbox.Selected',
A: 'Object.Listbox.Alternative',
O: 'Object.Listbox.Optional',
XS: 'Object.Listbox.SelectedExcluded',
L: 'Object.Listbox.Locked',
X: 'Object.Listbox.Excluded',
XL: 'Object.Listbox.ExcludedLock'
};
function getValueLabel(_ref) {
let {
translator: translatorDynamic,
label,
qState,
isSelected,
currentIndex,
maxIndex,
showSearch
} = _ref;
const stateTranslation = LOC_STATES[qState];
const state = translatorDynamic.get(stateTranslation);
const srStringArr = [];
if (isSelected) {
const navTranslation = showSearch ? 'Listbox.ScreenReader.SearchThenSelectionsMenu.WithAccSelMenu' : 'Listbox.ScreenReader.SelectionMenu.WithAccSelMenu';
const nav = translatorDynamic.get(navTranslation);
srStringArr.push(nav);
}
const valueString = "".concat(label, " ").concat(state);
const indexString = translatorDynamic.get('CurrentSelections.Of', [currentIndex + 1, maxIndex + 1]); // E.g. 3 of 20
srStringArr.unshift(valueString, indexString);
const srString = srStringArr.join('. ').trim();
return srString;
}
function RowColumn(_ref) {
var _cell$qText, _cell$qHighlightRange;
let {
index,
rowIndex,
columnIndex,
style,
data
} = _ref;
const {
onChange,
onClick,
onMouseDown,
onMouseUp,
onMouseEnter,
onTouchStart,
onTouchEnd,
pages,
isLocked,
column = false,
checkboxes = false,
textAlign,
direction,
layoutOptions = {},
freqIsAllowed,
isSingleSelect,
actions,
frequencyMax = '',
histogram = false,
keyboard,
showGray = true,
showTick: sizePermitsTickOrLock = true,
columnCount = 1,
rowCount = 1,
dataOffset,
deducedFrequencyMode,
focusListItems,
listCount,
sizes,
translator,
showSearch,
isModal,
contentFontStyle,
styles,
fillHeight
} = data;
const {
dense = false,
dataLayout = 'singleColumn',
layoutOrder
} = layoutOptions;
const {
itemPadding
} = sizes;
let cellIndex;
let styleOverrides;
const count = {
max: null,
currentIndex: null
};
if (typeof rowIndex === 'number' && typeof columnIndex === 'number') {
if (layoutOrder === 'row') {
cellIndex = rowIndex * columnCount + columnIndex;
count.max = rowCount;
count.currentIndex = rowIndex;
} else {
cellIndex = columnIndex * rowCount + rowIndex;
count.max = columnCount;
count.currentIndex = columnIndex;
}
const padding = 0;
styleOverrides = _objectSpread2(_objectSpread2({}, style), {}, {
height: fillHeight ? '100%' : style.height,
left: padding + (columnIndex === 0 ? style.left : Number(style.left) + columnIndex * padding),
// right: columnIndex === columnCount ? style.right : Number(style.right) + columnIndex * padding,
top: rowIndex === 0 ? style.top : Number(style.top) + rowIndex * padding
});
} else {
cellIndex = index;
count.max = listCount;
count.currentIndex = index;
styleOverrides = _objectSpread2({}, style);
}
cellIndex += dataOffset;
const [rowRef, setRowRef] = reactExports.useState(null);
reactExports.useEffect(() => {
if (rowRef !== null) {
if (count.currentIndex === 0 && focusListItems.first) {
rowRef.focus();
focusListItems.setFirst(false);
}
if (count.currentIndex === count.max - 1 && focusListItems.last) {
rowRef.focus();
focusListItems.setLast(false);
}
}
}, [rowRef, focusListItems.first, focusListItems.last]);
const handleKeyDownCallback = reactExports.useCallback(getRowsKeyboardNavigation(_objectSpread2(_objectSpread2({}, actions), {}, {
focusListItems,
keyboard,
isModal,
rowCount,
columnCount,
rowIndex,
columnIndex,
layoutOrder
})), [actions, keyboard === null || keyboard === void 0 ? void 0 : keyboard.innerTabStops, rowCount, columnCount, rowIndex, columnIndex, layoutOrder]);
const cell = reactExports.useMemo(() => getCellFromPages({
pages,
cellIndex
}), [pages, cellIndex]);
const isSelected = (cell === null || cell === void 0 ? void 0 : cell.qState) === 'S' || (cell === null || cell === void 0 ? void 0 : cell.qState) === 'XS' || (cell === null || cell === void 0 ? void 0 : cell.qState) === 'L' || (cell === null || cell === void 0 ? void 0 : cell.qState) === 'XL';
const classArr = reactExports.useMemo(() => getValueStateClasses({
column,
histogram,
cell,
showGray
}), [cell === null || cell === void 0 ? void 0 : cell.qState, histogram, dense]);
const preventContextMenu = reactExports.useCallback(event => {
event.preventDefault();
}, [checkboxes]);
const valueTextAlign = reactExports.useMemo(() => cell && getValueTextAlign({
direction,
cell,
textAlign
}), [direction, cell, textAlign]);
if (!cell) {
return null; // prevent rendering empty rows
}
const isGridCol = dataLayout === 'grid' && layoutOrder === 'column';
const label = (_cell$qText = cell === null || cell === void 0 ? void 0 : cell.qText) !== null && _cell$qText !== void 0 ? _cell$qText : '';
// Search highlights. Split up labelText span into several and add the highlighted class to matching sub-strings.
let labels;
if ((_cell$qHighlightRange = cell.qHighlightRanges) !== null && _cell$qHighlightRange !== void 0 && (_cell$qHighlightRange = _cell$qHighlightRange.qRanges) !== null && _cell$qHighlightRange !== void 0 && _cell$qHighlightRange.length) {
const ranges = cell.qHighlightRanges.qRanges.sort((a, b) => a.qCharPos - b.qCharPos) || [];
labels = getSegmentsFromRanges(label, ranges);
}
const iconStyles = {
alignItems: 'center',
display: 'flex',
fontSize: '8px'
};
const isRtl = direction === 'rtl';
const cellStyle = {
display: 'flex',
alignItems: 'center',
flexGrow: 1,
paddingLeft: isRtl ? 8 : checkboxes ? 0 : undefined,
paddingRight: checkboxes ? 0 : isRtl ? 8 : 0,
justifyContent: valueTextAlign,
textAlign: valueTextAlign
};
const isFirstElement = index === 0;
const showLockIcon = isSelected && isLocked;
const showTickIcon = !checkboxes && isSelected && !isLocked;
const showAnyIcon = !checkboxes && sizePermitsTickOrLock;
const cellPaddingRight = checkboxes || !sizePermitsTickOrLock;
const ariaLabel = getValueLabel({
translator,
label,
qState: cell.qState,
currentIndex: count.currentIndex,
maxIndex: count.max,
showSearch
});
const freqHitsValue = !isRtl && valueTextAlign === 'right' || isRtl && valueTextAlign === 'left';
return /*#__PURE__*/React.createElement(RowColRoot$1, {
className: rowColClasses.barContainer,
checkboxes: checkboxes,
style: styleOverrides,
styles: styles,
isGridCol: isGridCol,
isGridMode: dataLayout === 'grid',
dense: dense,
direction: direction,
sizes: sizes,
frequencyMode: deducedFrequencyMode,
freqHitsValue: freqHitsValue,
contentFontStyle: contentFontStyle,
"data-testid": "listbox.item"
}, /*#__PURE__*/React.createElement(ItemGrid, {
role: "row",
"aria-label": ariaLabel,
"aria-selected": isSelected,
"aria-setsize": count.max,
"aria-rowindex": count.currentIndex,
ref: setRowRef,
container: true,
dataLayout: dataLayout,
cellPaddingRight: cellPaddingRight,
layoutOrder: layoutOrder,
itemPadding: itemPadding,
gap: 0,
className: joinClassNames(['value', ...classArr]),
classes: {
root: rowColClasses.fieldRoot
},
onClick: onClick,
onMouseDown: onMouseDown,
onMouseUp: onMouseUp,
onMouseEnter: onMouseEnter,
onKeyDown: handleKeyDownCallback,
onTouchStart: onTouchStart,
onTouchEnd: onTouchEnd,
onContextMenu: preventContextMenu,
tabIndex: isFirstElement && keyboard.innerTabStops ? 0 : -1,
"data-n": cell === null || cell === void 0 ? void 0 : cell.qElemNumber,
direction: direction,
fillHeight: fillHeight
}, (cell === null || cell === void 0 ? void 0 : cell.qFrequency) && /*#__PURE__*/React.createElement(Histogram, {
qFrequency: cell === null || cell === void 0 ? void 0 : cell.qFrequency,
histogram: histogram,
checkboxes: checkboxes,
isSelected: isSelected,
frequencyMax: frequencyMax
}), /*#__PURE__*/React.createElement(Grid, {
item: true,
style: cellStyle,
className: joinClassNames([rowColClasses.cell, rowColClasses.selectedCell]),
title: "".concat(label)
}, labels ? /*#__PURE__*/React.createElement(FieldWithRanges, {
onChange: onChange,
labels: labels,
checkboxes: checkboxes,
dense: dense,
showGray: showGray,
qElemNumber: cell.qElemNumber,
isSelected: isSelected,
cell: cell,
isGridCol: isGridCol,
isSingleSelect: isSingleSelect,
valueTextAlign: valueTextAlign,
styles: styles
}) : /*#__PURE__*/React.createElement(Field$1, {
onChange: onChange,
label: label,
qElemNumber: cell.qElemNumber,
isSelected: isSelected,
dense: dense,
cell: cell,
isGridCol: isGridCol,
showGray: showGray,
isSingleSelect: isSingleSelect,
checkboxes: checkboxes,
valueTextAlign: valueTextAlign,
styles: styles
})), freqIsAllowed && /*#__PURE__*/React.createElement(Frequency, {
cell: cell,
checkboxes: checkboxes,
dense: dense,
showGray: showGray
}), showAnyIcon && /*#__PURE__*/React.createElement(Grid, {
item: true,
className: rowColClasses.icon
}, showLockIcon && /*#__PURE__*/React.createElement(Lock, {
style: iconStyles,
size: "small"
}), showTickIcon && /*#__PURE__*/React.createElement(Tick, {
style: iconStyles,
size: "small"
}))));
}
function deriveRenderOptions(options) {
const {
renderProps,
scrollState,
layoutOrder,
rowCount,
columnCount
} = options;
const {
overscanRowStartIndex,
overscanRowStopIndex,
overscanColumnStartIndex,
overscanColumnStopIndex,
visibleStopIndex: initialVisibleStopIndex
} = renderProps;
if (scrollState) {
scrollState.setScrollPos(initialVisibleStopIndex);
}
let toTheLeftOfStart;
let aboveStart;
let toTheLeftOfEnd;
let aboveEnd;
if (layoutOrder === 'column') {
toTheLeftOfStart = overscanColumnStartIndex * rowCount;
aboveStart = overscanRowStartIndex;
toTheLeftOfEnd = overscanColumnStopIndex * rowCount;
aboveEnd = overscanRowStopIndex;
} else {
toTheLeftOfStart = overscanColumnStartIndex;
aboveStart = overscanRowStartIndex * columnCount;
toTheLeftOfEnd = overscanColumnStopIndex;
aboveEnd = overscanRowStopIndex * columnCount;
}
const visibleStartIndex = toTheLeftOfStart + aboveStart;
const visibleStopIndex = toTheLeftOfEnd + aboveEnd;
return {
visibleStartIndex,
visibleStopIndex
};
}
var safeIsNaN = Number.isNaN ||
function ponyfill(value) {
return typeof value === 'number' && value !== value;
};
function isEqual$1(first, second) {
if (first === second) {
return true;
}
if (safeIsNaN(first) && safeIsNaN(second)) {
return true;
}
return false;
}
function areInputsEqual(newInputs, lastInputs) {
if (newInputs.length !== lastInputs.length) {
return false;
}
for (var i = 0; i < newInputs.length; i++) {
if (!isEqual$1(newInputs[i], lastInputs[i])) {
return false;
}
}
return true;
}
function memoizeOne(resultFn, isEqual) {
if (isEqual === void 0) { isEqual = areInputsEqual; }
var lastThis;
var lastArgs = [];
var lastResult;
var calledOnce = false;
function memoized() {
var newArgs = [];
for (var _i = 0; _i < arguments.length; _i++) {
newArgs[_i] = arguments[_i];
}
if (calledOnce && lastThis === this && isEqual(newArgs, lastArgs)) {
return lastResult;
}
lastResult = resultFn.apply(this, newArgs);
calledOnce = true;
lastThis = this;
lastArgs = newArgs;
return lastResult;
}
return memoized;
}
// 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 size = -1; // This utility copied from "dom-helpers" package.
function getScrollbarSize(recalculate) {
if (recalculate === void 0) {
recalculate = false;
}
if (size === -1 || recalculate) {
var div = document.createElement('div');
var style = div.style;
style.width = '50px';
style.height = '50px';
style.overflow = 'scroll';
document.body.appendChild(div);
size = div.offsetWidth - div.clientWidth;
document.body.removeChild(div);
}
return size;
}
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 = 150;
var defaultItemKey = function defaultItemKey(_ref) {
var columnIndex = _ref.columnIndex;
_ref.data;
var rowIndex = _ref.rowIndex;
return rowIndex + ":" + columnIndex;
}; // In DEV mode, this Set helps us only log a warning once per component instance.
function createGridComponent(_ref2) {
var _class;
var getColumnOffset = _ref2.getColumnOffset,
getColumnStartIndexForOffset = _ref2.getColumnStartIndexForOffset,
getColumnStopIndexForStartIndex = _ref2.getColumnStopIndexForStartIndex,
getColumnWidth = _ref2.getColumnWidth,
getEstimatedTotalHeight = _ref2.getEstimatedTotalHeight,
getEstimatedTotalWidth = _ref2.getEstimatedTotalWidth,
getOffsetForColumnAndAlignment = _ref2.getOffsetForColumnAndAlignment,
getOffsetForRowAndAlignment = _ref2.getOffsetForRowAndAlignment,
getRowHeight = _ref2.getRowHeight,
getRowOffset = _ref2.getRowOffset,
getRowStartIndexForOffset = _ref2.getRowStartIndexForOffset,
getRowStopIndexForStartIndex = _ref2.getRowStopIndexForStartIndex,
initInstanceProps = _ref2.initInstanceProps,
shouldResetStyleCacheOnItemSizeChange = _ref2.shouldResetStyleCacheOnItemSizeChange,
validateProps = _ref2.validateProps;
return _class = /*#__PURE__*/function (_PureComponent) {
_inheritsLoose(Grid, _PureComponent);
// Always use explicit constructor for React components.
// It produces less code after transpilation. (#26)
// eslint-disable-next-line no-useless-constructor
function Grid(props) {
var _this;
_this = _PureComponent.call(this, props) || this;
_this._instanceProps = initInstanceProps(_this.props, _assertThisInitialized(_this));
_this._resetIsScrollingTimeoutId = null;
_this._outerRef = void 0;
_this.state = {
instance: _assertThisInitialized(_this),
isScrolling: false,
horizontalScrollDirection: 'forward',
scrollLeft: typeof _this.props.initialScrollLeft === 'number' ? _this.props.initialScrollLeft : 0,
scrollTop: typeof _this.props.initialScrollTop === 'number' ? _this.props.initialScrollTop : 0,
scrollUpdateWasRequested: false,
verticalScrollDirection: 'forward'
};
_this._callOnItemsRendered = void 0;
_this._callOnItemsRendered = memoizeOne(function (overscanColumnStartIndex, overscanColumnStopIndex, overscanRowStartIndex, overscanRowStopIndex, visibleColumnStartIndex, visibleColumnStopIndex, visibleRowStartIndex, visibleRowStopIndex) {
return _this.props.onItemsRendered({
overscanColumnStartIndex: overscanColumnStartIndex,
overscanColumnStopIndex: overscanColumnStopIndex,
overscanRowStartIndex: overscanRowStartIndex,
overscanRowStopIndex: overscanRowStopIndex,
visibleColumnStartIndex: visibleColumnStartIndex,
visibleColumnStopIndex: visibleColumnStopIndex,
visibleRowStartIndex: visibleRowStartIndex,
visibleRowStopIndex: visibleRowStopIndex
});
});
_this._callOnScroll = void 0;
_this._callOnScroll = memoizeOne(function (scrollLeft, scrollTop, horizontalScrollDirection, verticalScrollDirection, scrollUpdateWasRequested) {
return _this.props.onScroll({
horizontalScrollDirection: horizontalScrollDirection,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
verticalScrollDirection: verticalScrollDirection,
scrollUpdateWasRequested: scrollUpdateWasRequested
});
});
_this._getItemStyle = void 0;
_this._getItemStyle = function (rowIndex, columnIndex) {
var _this$props = _this.props,
columnWidth = _this$props.columnWidth,
direction = _this$props.direction,
rowHeight = _this$props.rowHeight;
var itemStyleCache = _this._getItemStyleCache(shouldResetStyleCacheOnItemSizeChange && columnWidth, shouldResetStyleCacheOnItemSizeChange && direction, shouldResetStyleCacheOnItemSizeChange && rowHeight);
var key = rowIndex + ":" + columnIndex;
var style;
if (itemStyleCache.hasOwnProperty(key)) {
style = itemStyleCache[key];
} else {
var _offset = getColumnOffset(_this.props, columnIndex, _this._instanceProps);
var isRtl = direction === 'rtl';
itemStyleCache[key] = style = {
position: 'absolute',
left: isRtl ? undefined : _offset,
right: isRtl ? _offset : undefined,
top: getRowOffset(_this.props, rowIndex, _this._instanceProps),
height: getRowHeight(_this.props, rowIndex, _this._instanceProps),
width: getColumnWidth(_this.props, columnIndex, _this._instanceProps)
};
}
return style;
};
_this._getItemStyleCache = void 0;
_this._getItemStyleCache = memoizeOne(function (_, __, ___) {
return {};
});
_this._onScroll = function (event) {
var _event$currentTarget = event.currentTarget,
clientHeight = _event$currentTarget.clientHeight,
clientWidth = _event$currentTarget.clientWidth,
scrollLeft = _event$currentTarget.scrollLeft,
scrollTop = _event$currentTarget.scrollTop,
scrollHeight = _event$currentTarget.scrollHeight,
scrollWidth = _event$currentTarget.scrollWidth;
_this.setState(function (prevState) {
if (prevState.scrollLeft === scrollLeft && prevState.scrollTop === 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;
}
var direction = _this.props.direction; // 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.
var calculatedScrollLeft = scrollLeft;
if (direction === 'rtl') {
switch (getRTLOffsetType()) {
case 'negative':
calculatedScrollLeft = -scrollLeft;
break;
case 'positive-descending':
calculatedScrollLeft = scrollWidth - clientWidth - scrollLeft;
break;
}
} // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds.
calculatedScrollLeft = Math.max(0, Math.min(calculatedScrollLeft, scrollWidth - clientWidth));
var calculatedScrollTop = Math.max(0, Math.min(scrollTop, scrollHeight - clientHeight));
return {
isScrolling: true,
horizontalScrollDirection: prevState.scrollLeft < scrollLeft ? 'forward' : 'backward',
scrollLeft: calculatedScrollLeft,
scrollTop: calculatedScrollTop,
verticalScrollDirection: prevState.scrollTop < scrollTop ? 'forward' : 'backward',
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);
};
_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);
});
};
return _this;
}
Grid.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
validateSharedProps(nextProps, prevState);
validateProps(nextProps);
return null;
};
var _proto = Grid.prototype;
_proto.scrollTo = function scrollTo(_ref3) {
var scrollLeft = _ref3.scrollLeft,
scrollTop = _ref3.scrollTop;
if (scrollLeft !== undefined) {
scrollLeft = Math.max(0, scrollLeft);
}
if (scrollTop !== undefined) {
scrollTop = Math.max(0, scrollTop);
}
this.setState(function (prevState) {
if (scrollLeft === undefined) {
scrollLeft = prevState.scrollLeft;
}
if (scrollTop === undefined) {
scrollTop = prevState.scrollTop;
}
if (prevState.scrollLeft === scrollLeft && prevState.scrollTop === scrollTop) {
return null;
}
return {
horizontalScrollDirection: prevState.scrollLeft < scrollLeft ? 'forward' : 'backward',
scrollLeft: scrollLeft,
scrollTop: scrollTop,
scrollUpdateWasRequested: true,
verticalScrollDirection: prevState.scrollTop < scrollTop ? 'forward' : 'backward'
};
}, this._resetIsScrollingDebounced);
};
_proto.scrollToItem = function scrollToItem(_ref4) {
var _ref4$align = _ref4.align,
align = _ref4$align === void 0 ? 'auto' : _ref4$align,
columnIndex = _ref4.columnIndex,
rowIndex = _ref4.rowIndex;
var _this$props2 = this.props,
columnCount = _this$props2.columnCount,
height = _this$props2.height,
rowCount = _this$props2.rowCount,
width = _this$props2.width;
var _this$state = this.state,
scrollLeft = _this$state.scrollLeft,
scrollTop = _this$state.scrollTop;
var scrollbarSize = getScrollbarSize();
if (columnIndex !== undefined) {
columnIndex = Math.max(0, Math.min(columnIndex, columnCount - 1));
}
if (rowIndex !== undefined) {
rowIndex = Math.max(0, Math.min(rowIndex, rowCount - 1));
}
var estimatedTotalHeight = getEstimatedTotalHeight(this.props, this._instanceProps);
var estimatedTotalWidth = getEstimatedTotalWidth(this.props, this._instanceProps); // The scrollbar size should be considered when scrolling an item into view,
// to ensure it's fully visible.
// But we only need to account for its size when it's actually visible.
var horizontalScrollbarSize = estimatedTotalWidth > width ? scrollbarSize : 0;
var verticalScrollbarSize = estimatedTotalHeight > height ? scrollbarSize : 0;
this.scrollTo({
scrollLeft: columnIndex !== undefined ? getOffsetForColumnAndAlignment(this.props, columnIndex, align, scrollLeft, this._instanceProps, verticalScrollbarSize) : scrollLeft,
scrollTop: rowIndex !== undefined ? getOffsetForRowAndAlignment(this.props, rowIndex, align, scrollTop, this._instanceProps, horizontalScrollbarSize) : scrollTop
});
};
_proto.componentDidMount = function componentDidMount() {
var _this$props3 = this.props,
initialScrollLeft = _this$props3.initialScrollLeft,
initialScrollTop = _this$props3.initialScrollTop;
if (this._outerRef != null) {
var outerRef = this._outerRef;
if (typeof initialScrollLeft === 'number') {
outerRef.scrollLeft = initialScrollLeft;
}
if (typeof initialScrollTop === 'number') {
outerRef.scrollTop = initialScrollTop;
}
}
this._callPropsCallbacks();
};
_proto.componentDidUpdate = function componentDidUpdate() {
var direction = this.props.direction;
var _this$state2 = this.state,
scrollLeft = _this$state2.scrollLeft,
scrollTop = _this$state2.scrollTop,
scrollUpdateWasRequested = _this$state2.scrollUpdateWasRequested;
if (scrollUpdateWasRequested && this._outerRef != null) {
// 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.
var outerRef = this._outerRef;
if (direction === 'rtl') {
switch (getRTLOffsetType()) {
case 'negative':
outerRef.scrollLeft = -scrollLeft;
break;
case 'positive-ascending':
outerRef.scrollLeft = scrollLeft;
break;
default:
var clientWidth = outerRef.clientWidth,
scrollWidth = outerRef.scrollWidth;
outerRef.scrollLeft = scrollWidth - clientWidth - scrollLeft;
break;
}
} else {
outerRef.scrollLeft = Math.max(0, scrollLeft);
}
outerRef.scrollTop = Math.max(0, scrollTop);
}
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,
columnCount = _this$props4.columnCount,
direction = _this$props4.direction,
height = _this$props4.height,
innerRef = _this$props4.innerRef,
innerElementType = _this$props4.innerElementType,
innerTagName = _this$props4.innerTagName,
itemData = _this$props4.itemData,
_this$props4$itemKey = _this$props4.itemKey,
itemKey = _this$props4$itemKey === void 0 ? defaultItemKey : _this$props4$itemKey,
outerElementType = _this$props4.outerElementType,
outerTagName = _this$props4.outerTagName,
rowCount = _this$props4.rowCount,
style = _this$props4.style,
useIsScrolling = _this$props4.useIsScrolling,
width = _this$props4.width;
var isScrolling = this.state.isScrolling;
var _this$_getHorizontalR = this._getHorizontalRangeToRender(),
columnStartIndex = _this$_getHorizontalR[0],
columnStopIndex = _this$_getHorizontalR[1];
var _this$_getVerticalRan = this._getVerticalRangeToRender(),
rowStartIndex = _this$_getVerticalRan[0],
rowStopIndex = _this$_getVerticalRan[1];
var items = [];
if (columnCount > 0 && rowCount) {
for (var _rowIndex = rowStartIndex; _rowIndex <= rowStopIndex; _rowIndex++) {
for (var _columnIndex = columnStartIndex; _columnIndex <= columnStopIndex; _columnIndex++) {
items.push(reactExports.createElement(children, {
columnIndex: _columnIndex,
data: itemData,
isScrolling: useIsScrolling ? isScrolling : undefined,
key: itemKey({
columnIndex: _columnIndex,
data: itemData,
rowIndex: _rowIndex
}),
rowIndex: _rowIndex,
style: this._getItemStyle(_rowIndex, _columnIndex)
}));
}
}
} // Read this value AFTER items have been created,
// So their actual sizes (if variable) are taken into consideration.
var estimatedTotalHeight = getEstimatedTotalHeight(this.props, this._instanceProps);
var estimatedTotalWidth = getEstimatedTotalWidth(this.props, this._instanceProps);
return reactExports.createElement(outerElementType || outerTagName || 'div', {
className: className,
onScroll: this._onScroll,
ref: this._outerRefSetter,
style: _extends({
position: 'relative',
height: height,
width: width,
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
willChange: 'transform',
direction: direction
}, style)
}, reactExports.createElement(innerElementType || innerTagName || 'div', {
children: items,
ref: innerRef,
style: {
height: estimatedTotalHeight,
pointerEvents: isScrolling ? 'none' : undefined,
width: estimatedTotalWidth
}
}));
};
_proto._callPropsCallbacks = function _callPropsCallbacks() {
var _this$props5 = this.props,
columnCount = _this$props5.columnCount,
onItemsRendered = _this$props5.onItemsRendered,
onScroll = _this$props5.onScroll,
rowCount = _this$props5.rowCount;
if (typeof onItemsRendered === 'function') {
if (columnCount > 0 && rowCount > 0) {
var _this$_getHorizontalR2 = this._getHorizontalRangeToRender(),
_overscanColumnStartIndex = _this$_getHorizontalR2[0],
_overscanColumnStopIndex = _this$_getHorizontalR2[1],
_visibleColumnStartIndex = _this$_getHorizontalR2[2],
_visibleColumnStopIndex = _this$_getHorizontalR2[3];
var _this$_getVerticalRan2 = this._getVerticalRangeToRender(),
_overscanRowStartIndex = _this$_getVerticalRan2[0],
_overscanRowStopIndex = _this$_getVerticalRan2[1],
_visibleRowStartIndex = _this$_getVerticalRan2[2],
_visibleRowStopIndex = _this$_getVerticalRan2[3];
this._callOnItemsRendered(_overscanColumnStartIndex, _overscanColumnStopIndex, _overscanRowStartIndex, _overscanRowStopIndex, _visibleColumnStartIndex, _visibleColumnStopIndex, _visibleRowStartIndex, _visibleRowStopIndex);
}
}
if (typeof onScroll === 'function') {
var _this$state3 = this.state,
_horizontalScrollDirection = _this$state3.horizontalScrollDirection,
_scrollLeft = _this$state3.scrollLeft,
_scrollTop = _this$state3.scrollTop,
_scrollUpdateWasRequested = _this$state3.scrollUpdateWasRequested,
_verticalScrollDirection = _this$state3.verticalScrollDirection;
this._callOnScroll(_scrollLeft, _scrollTop, _horizontalScrollDirection, _verticalScrollDirection, _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._getHorizontalRangeToRender = function _getHorizontalRangeToRender() {
var _this$props6 = this.props,
columnCount = _this$props6.columnCount,
overscanColumnCount = _this$props6.overscanColumnCount,
overscanColumnsCount = _this$props6.overscanColumnsCount,
overscanCount = _this$props6.overscanCount,
rowCount = _this$props6.rowCount;
var _this$state4 = this.state,
horizontalScrollDirection = _this$state4.horizontalScrollDirection,
isScrolling = _this$state4.isScrolling,
scrollLeft = _this$state4.scrollLeft;
var overscanCountResolved = overscanColumnCount || overscanColumnsCount || overscanCount || 1;
if (columnCount === 0 || rowCount === 0) {
return [0, 0, 0, 0];
}
var startIndex = getColumnStartIndexForOffset(this.props, scrollLeft, this._instanceProps);
var stopIndex = getColumnStopIndexForStartIndex(this.props, startIndex, scrollLeft, 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 || horizontalScrollDirection === 'backward' ? Math.max(1, overscanCountResolved) : 1;
var overscanForward = !isScrolling || horizontalScrollDirection === 'forward' ? Math.max(1, overscanCountResolved) : 1;
return [Math.max(0, startIndex - overscanBackward), Math.max(0, Math.min(columnCount - 1, stopIndex + overscanForward)), startIndex, stopIndex];
};
_proto._getVerticalRangeToRender = function _getVerticalRangeToRender() {
var _this$props7 = this.props,
columnCount = _this$props7.columnCount,
overscanCount = _this$props7.overscanCount,
overscanRowCount = _this$props7.overscanRowCount,
overscanRowsCount = _this$props7.overscanRowsCount,
rowCount = _this$props7.rowCount;
var _this$state5 = this.state,
isScrolling = _this$state5.isScrolling,
verticalScrollDirection = _this$state5.verticalScrollDirection,
scrollTop = _this$state5.scrollTop;
var overscanCountResolved = overscanRowCount || overscanRowsCount || overscanCount || 1;
if (columnCount === 0 || rowCount === 0) {
return [0, 0, 0, 0];
}
var startIndex = getRowStartIndexForOffset(this.props, scrollTop, this._instanceProps);
var stopIndex = getRowStopIndexForStartIndex(this.props, startIndex, scrollTop, 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 || verticalScrollDirection === 'backward' ? Math.max(1, overscanCountResolved) : 1;
var overscanForward = !isScrolling || verticalScrollDirection === 'forward' ? Math.max(1, overscanCountResolved) : 1;
return [Math.max(0, startIndex - overscanBackward), Math.max(0, Math.min(rowCount - 1, stopIndex + overscanForward)), startIndex, stopIndex];
};
return Grid;
}(reactExports.PureComponent), _class.defaultProps = {
direction: 'ltr',
itemData: undefined,
useIsScrolling: false
}, _class;
}
var validateSharedProps = function validateSharedProps(_ref5, _ref6) {
_ref5.children;
_ref5.direction;
_ref5.height;
_ref5.innerTagName;
_ref5.outerTagName;
_ref5.overscanColumnsCount;
_ref5.overscanCount;
_ref5.overscanRowsCount;
_ref5.width;
_ref6.instance;
};
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 = memoizeOne(function (overscanStartIndex, overscanStopIndex, visibleStartIndex, visibleStopIndex) {
return _this.props.onItemsRendered({
overscanStartIndex: overscanStartIndex,
overscanStopIndex: overscanStopIndex,
visibleStartIndex: visibleStartIndex,
visibleStopIndex: visibleStopIndex
});
});
_this._callOnScroll = void 0;
_this._callOnScroll = memoizeOne(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 = memoizeOne(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 < scrollOffset ? '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 _this$props2 = this.props,
itemCount = _this$props2.itemCount,
layout = _this$props2.layout;
var scrollOffset = this.state.scrollOffset;
index = Math.max(0, Math.min(index, itemCount - 1)); // The scrollbar size should be considered when scrolling an item into view, to ensure it's fully visible.
// But we only need to account for its size when it's actually visible.
// This is an edge case for lists; normally they only scroll in the dominant direction.
var scrollbarSize = 0;
if (this._outerRef) {
var outerRef = this._outerRef;
if (layout === 'vertical') {
scrollbarSize = outerRef.scrollWidth > outerRef.clientWidth ? getScrollbarSize() : 0;
} else {
scrollbarSize = outerRef.scrollHeight > outerRef.clientHeight ? getScrollbarSize() : 0;
}
}
this.scrollTo(getOffsetForIndexAndAlignment(this.props, index, align, scrollOffset, this._instanceProps, scrollbarSize));
};
_proto.componentDidMount = function componentDidMount() {
var _this$props3 = this.props,
direction = _this$props3.direction,
initialScrollOffset = _this$props3.initialScrollOffset,
layout = _this$props3.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$props4 = this.props,
direction = _this$props4.direction,
layout = _this$props4.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$props5 = this.props,
children = _this$props5.children,
className = _this$props5.className,
direction = _this$props5.direction,
height = _this$props5.height,
innerRef = _this$props5.innerRef,
innerElementType = _this$props5.innerElementType,
innerTagName = _this$props5.innerTagName,
itemCount = _this$props5.itemCount,
itemData = _this$props5.itemData,
_this$props5$itemKey = _this$props5.itemKey,
itemKey = _this$props5$itemKey === void 0 ? defaultItemKey$1 : _this$props5$itemKey,
layout = _this$props5.layout,
outerElementType = _this$props5.outerElementType,
outerTagName = _this$props5.outerTagName,
style = _this$props5.style,
useIsScrolling = _this$props5.useIsScrolling,
width = _this$props5.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(reactExports.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 reactExports.createElement(outerElementType || outerTagName || 'div', {
className: className,
onScroll: onScroll,
ref: this._outerRefSetter,
style: _extends({
position: 'relative',
height: height,
width: width,
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
willChange: 'transform',
direction: direction
}, style)
}, reactExports.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$props6 = this.props,
itemCount = _this$props6.itemCount,
overscanCount = _this$props6.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;
}(reactExports.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 FixedSizeGrid = /*#__PURE__*/createGridComponent({
getColumnOffset: function getColumnOffset(_ref, index) {
var columnWidth = _ref.columnWidth;
return index * columnWidth;
},
getColumnWidth: function getColumnWidth(_ref2, index) {
var columnWidth = _ref2.columnWidth;
return columnWidth;
},
getRowOffset: function getRowOffset(_ref3, index) {
var rowHeight = _ref3.rowHeight;
return index * rowHeight;
},
getRowHeight: function getRowHeight(_ref4, index) {
var rowHeight = _ref4.rowHeight;
return rowHeight;
},
getEstimatedTotalHeight: function getEstimatedTotalHeight(_ref5) {
var rowCount = _ref5.rowCount,
rowHeight = _ref5.rowHeight;
return rowHeight * rowCount;
},
getEstimatedTotalWidth: function getEstimatedTotalWidth(_ref6) {
var columnCount = _ref6.columnCount,
columnWidth = _ref6.columnWidth;
return columnWidth * columnCount;
},
getOffsetForColumnAndAlignment: function getOffsetForColumnAndAlignment(_ref7, columnIndex, align, scrollLeft, instanceProps, scrollbarSize) {
var columnCount = _ref7.columnCount,
columnWidth = _ref7.columnWidth,
width = _ref7.width;
var lastColumnOffset = Math.max(0, columnCount * columnWidth - width);
var maxOffset = Math.min(lastColumnOffset, columnIndex * columnWidth);
var minOffset = Math.max(0, columnIndex * columnWidth - width + scrollbarSize + columnWidth);
if (align === 'smart') {
if (scrollLeft >= minOffset - width && scrollLeft <= maxOffset + width) {
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(width / 2)) {
return 0; // near the beginning
} else if (middleOffset > lastColumnOffset + Math.floor(width / 2)) {
return lastColumnOffset; // near the end
} else {
return middleOffset;
}
case 'auto':
default:
if (scrollLeft >= minOffset && scrollLeft <= maxOffset) {
return scrollLeft;
} else if (minOffset > maxOffset) {
// Because we only take into account the scrollbar size when calculating minOffset
// this value can be larger than maxOffset when at the end of the list
return minOffset;
} else if (scrollLeft < minOffset) {
return minOffset;
} else {
return maxOffset;
}
}
},
getOffsetForRowAndAlignment: function getOffsetForRowAndAlignment(_ref8, rowIndex, align, scrollTop, instanceProps, scrollbarSize) {
var rowHeight = _ref8.rowHeight,
height = _ref8.height,
rowCount = _ref8.rowCount;
var lastRowOffset = Math.max(0, rowCount * rowHeight - height);
var maxOffset = Math.min(lastRowOffset, rowIndex * rowHeight);
var minOffset = Math.max(0, rowIndex * rowHeight - height + scrollbarSize + rowHeight);
if (align === 'smart') {
if (scrollTop >= minOffset - height && scrollTop <= maxOffset + height) {
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(height / 2)) {
return 0; // near the beginning
} else if (middleOffset > lastRowOffset + Math.floor(height / 2)) {
return lastRowOffset; // near the end
} else {
return middleOffset;
}
case 'auto':
default:
if (scrollTop >= minOffset && scrollTop <= maxOffset) {
return scrollTop;
} else if (minOffset > maxOffset) {
// Because we only take into account the scrollbar size when calculating minOffset
// this value can be larger than maxOffset when at the end of the list
return minOffset;
} else if (scrollTop < minOffset) {
return minOffset;
} else {
return maxOffset;
}
}
},
getColumnStartIndexForOffset: function getColumnStartIndexForOffset(_ref9, scrollLeft) {
var columnWidth = _ref9.columnWidth,
columnCount = _ref9.columnCount;
return Math.max(0, Math.min(columnCount - 1, Math.floor(scrollLeft / columnWidth)));
},
getColumnStopIndexForStartIndex: function getColumnStopIndexForStartIndex(_ref10, startIndex, scrollLeft) {
var columnWidth = _ref10.columnWidth,
columnCount = _ref10.columnCount,
width = _ref10.width;
var left = startIndex * columnWidth;
var numVisibleColumns = Math.ceil((width + scrollLeft - left) / columnWidth);
return Math.max(0, Math.min(columnCount - 1, startIndex + numVisibleColumns - 1 // -1 is because stop index is inclusive
));
},
getRowStartIndexForOffset: function getRowStartIndexForOffset(_ref11, scrollTop) {
var rowHeight = _ref11.rowHeight,
rowCount = _ref11.rowCount;
return Math.max(0, Math.min(rowCount - 1, Math.floor(scrollTop / rowHeight)));
},
getRowStopIndexForStartIndex: function getRowStopIndexForStartIndex(_ref12, startIndex, scrollTop) {
var rowHeight = _ref12.rowHeight,
rowCount = _ref12.rowCount,
height = _ref12.height;
var top = startIndex * rowHeight;
var numVisibleRows = Math.ceil((height + scrollTop - top) / rowHeight);
return Math.max(0, Math.min(rowCount - 1, startIndex + numVisibleRows - 1 // -1 is because stop index is inclusive
));
},
initInstanceProps: function initInstanceProps(props) {// Noop
},
shouldResetStyleCacheOnItemSizeChange: true,
validateProps: function validateProps(_ref13) {
_ref13.columnWidth;
_ref13.rowHeight;
}
});
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, instanceProps, scrollbarSize) {
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 + scrollbarSize);
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;
}
});
const PREFIX$9 = 'ListBox';
const scrollBarThumb = '#BBB';
const scrollBarThumbHover = '#555';
const scrollBarBackground = '#f1f1f1';
const classes$9 = {
styledScrollbars: "".concat(PREFIX$9, "-styledScrollbars")
};
function getStyledComponents() {
const getScrollbarStyling = scrollDisabled => ({
scrollbarColor: "".concat(scrollBarThumb, " ").concat(scrollBarBackground),
overflow: scrollDisabled ? 'hidden !important' : undefined,
'&::-webkit-scrollbar': {
width: 10,
height: 10
},
'&::-webkit-scrollbar-track': {
backgroundColor: scrollBarBackground
},
'&::-webkit-scrollbar-thumb': {
backgroundColor: scrollBarThumb,
borderRadius: '1rem'
},
'&::-webkit-scrollbar-thumb:hover': {
backgroundColor: scrollBarThumbHover
}
});
const StyledFixedSizeList = styled$2(FixedSizeList, {
shouldForwardProp: prop => prop !== 'scrollDisabled'
})(_ref => {
let {
scrollDisabled
} = _ref;
return {
["&.".concat(classes$9.styledScrollbars)]: getScrollbarStyling(scrollDisabled)
};
});
const StyledFixedSizeGrid = styled$2(FixedSizeGrid, {
shouldForwardProp: prop => prop !== 'scrollDisabled'
})(_ref2 => {
let {
scrollDisabled
} = _ref2;
return {
["&.".concat(classes$9.styledScrollbars)]: getScrollbarStyling(scrollDisabled)
};
});
return {
StyledFixedSizeList,
StyledFixedSizeGrid
};
}
const getIndex = (renderProps, isColumnLayout) => {
if ((renderProps === null || renderProps === void 0 ? void 0 : renderProps.visibleRowStopIndex) !== undefined || renderProps.visibleColumnStopIndex !== undefined) {
return isColumnLayout ? renderProps.visibleColumnStopIndex : renderProps.visibleRowStopIndex;
}
return renderProps.visibleStopIndex;
};
const getIsScrollTop = (renderProps, isColumnLayout) => {
if ((renderProps === null || renderProps === void 0 ? void 0 : renderProps.visibleRowStartIndex) !== undefined || renderProps.visibleColumnStartIndex !== undefined) {
return isColumnLayout ? renderProps.visibleColumnStartIndex === 0 : renderProps.visibleRowStartIndex === 0;
}
return renderProps.visibleStartIndex === 0;
};
const getIsEndOfData = (qCardinal, index, count, dataOffset) => qCardinal === index * count + dataOffset + count;
function handleSetOverflowDisclaimer(_ref) {
let {
renderProps,
layoutOptions,
maxCount,
columnCount,
rowCount,
overflowDisclaimer,
qCardinal,
dataOffset
} = _ref;
const isColumnLayout = (layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.layoutOrder) === 'column' && layoutOptions.dataLayout !== 'singleColumn';
const index = getIndex(renderProps, isColumnLayout);
const stopIndex = isColumnLayout ? maxCount.column : maxCount.row;
const count = isColumnLayout ? columnCount : rowCount;
const overflowPossible = count >= stopIndex;
const isEndOfData = getIsEndOfData(qCardinal, index, isColumnLayout ? rowCount : columnCount, dataOffset);
const isTopOfOverflowData = !!dataOffset && getIsScrollTop(renderProps, isColumnLayout);
const show = overflowPossible && !isEndOfData && index >= stopIndex - 1 || isTopOfOverflowData || overflowDisclaimer.state.show; // If its shown once, the user have to dismiss to hide it.
overflowDisclaimer.set(show);
}
const {
StyledFixedSizeList,
StyledFixedSizeGrid
} = getStyledComponents();
function getListBoxComponents(_ref) {
let {
layout,
width,
checkboxes,
local,
isVertical,
pages,
selectionState,
interactionEvents,
deducedFrequencyMode,
histogram,
isSingleSelect,
select,
selectAll,
onCtrlF,
textAlign,
selections,
keyboard,
showGray,
scrollState,
direction,
sizes,
listCount,
overflowDisclaimer,
setScrollPosition,
focusListItems,
setCurrentScrollIndex,
constraints,
frequencyMax,
freqIsAllowed,
translator,
showSearch,
isModal,
styles
} = _ref;
const {
layoutOptions = {}
} = layout || {};
const {
columnWidth,
listHeight,
itemHeight,
rowCount,
columnCount
} = sizes || {};
const itemWidth = layoutOptions.dataLayout === 'grid' ? columnWidth : width;
const showTick = itemWidth > REMOVE_TICK_LIMIT;
// Options common for List and Grid.
const commonComponentOptions = {
direction: direction === 'rtl' ? 'rtl' : 'ltr',
useIsScrolling: true,
className: classes$9.styledScrollbars
};
const isLocked = layout === null || layout === void 0 ? void 0 : layout.qListObject.qDimensionInfo.qLocked;
const fillHeight = listHeight <= itemHeight;
// Item data common for List and Grid.
const commonItemData = _objectSpread2(_objectSpread2({
isLocked,
column: !isVertical,
pages
}, isLocked || selectionState.selectDisabled() ? {} : interactionEvents), {}, {
checkboxes,
layoutOptions,
deducedFrequencyMode,
freqIsAllowed,
isSingleSelect,
textAlign,
sizes,
actions: {
select,
confirm: () => selections === null || selections === void 0 ? void 0 : selections.confirm.call(selections),
cancel: () => selections === null || selections === void 0 ? void 0 : selections.cancel.call(selections),
setScrollPosition,
selectAll,
onCtrlF
},
frequencyMax,
histogram,
keyboard,
showGray,
showTick,
dataOffset: local.current.dataOffset,
focusListItems,
direction,
translator,
showSearch,
isModal,
styles,
fillHeight
});
const List = _ref2 => {
let {
onItemsRendered,
ref
} = _ref2;
// eslint-disable-next-line no-param-reassign
local.current.listRef = ref;
return /*#__PURE__*/React.createElement(StyledFixedSizeList
// eslint-disable-next-line react/jsx-props-no-spreading
, _extends$1({}, commonComponentOptions, {
dataTestid: "fixed-size-list",
scrollDisabled: constraints === null || constraints === void 0 ? void 0 : constraints.active,
height: listHeight,
width: width,
itemCount: listCount,
itemData: _objectSpread2(_objectSpread2({}, commonItemData), {}, {
listCount
}),
itemSize: itemHeight,
onItemsRendered: renderProps => {
var _layout$qListObject;
setCurrentScrollIndex({
start: renderProps.visibleStartIndex,
stop: renderProps.visibleStopIndex
});
if (scrollState) {
scrollState.setScrollPos(renderProps.visibleStopIndex);
}
handleSetOverflowDisclaimer({
renderProps,
layoutOptions,
maxCount: sizes.maxCount,
columnCount,
rowCount,
overflowDisclaimer,
qCardinal: layout === null || layout === void 0 || (_layout$qListObject = layout.qListObject) === null || _layout$qListObject === void 0 || (_layout$qListObject = _layout$qListObject.qDimensionInfo) === null || _layout$qListObject === void 0 ? void 0 : _layout$qListObject.qCardinal,
dataOffset: local.current.dataOffset
});
onItemsRendered(_objectSpread2({}, renderProps));
},
ref: ref
}), RowColumn);
};
const Grid = _ref3 => {
let {
onItemsRendered,
ref
} = _ref3;
const {
overflowStyling,
scrollBarWidth
} = sizes;
const {
layoutOrder
} = layoutOptions || {};
const gridHeight = Math.min(listHeight, rowCount * itemHeight + scrollBarWidth);
// eslint-disable-next-line no-param-reassign
local.current.listRef = ref;
const handleGridItemsRendered = renderProps => {
var _layout$qListObject2;
const isRow = layoutOrder === 'row';
setCurrentScrollIndex({
start: isRow ? renderProps.visibleRowStartIndex : renderProps.visibleColumnStartIndex,
stop: isRow ? renderProps.visibleRowStopIndex : renderProps.visibleColumnStopIndex
});
const renderOptions = deriveRenderOptions({
renderProps,
scrollState,
layoutOrder,
rowCount,
columnCount
});
handleSetOverflowDisclaimer({
renderProps,
layoutOptions,
maxCount: sizes.maxCount,
columnCount,
rowCount,
overflowDisclaimer,
qCardinal: layout === null || layout === void 0 || (_layout$qListObject2 = layout.qListObject) === null || _layout$qListObject2 === void 0 || (_layout$qListObject2 = _layout$qListObject2.qDimensionInfo) === null || _layout$qListObject2 === void 0 ? void 0 : _layout$qListObject2.qCardinal,
dataOffset: local.current.dataOffset
});
onItemsRendered(renderOptions);
};
return /*#__PURE__*/React.createElement(StyledFixedSizeGrid
// eslint-disable-next-line react/jsx-props-no-spreading
, _extends$1({}, commonComponentOptions, {
dataTestid: "fixed-size-grid",
scrollDisabled: constraints === null || constraints === void 0 ? void 0 : constraints.active,
height: gridHeight,
width: width,
columnCount: columnCount,
columnWidth: columnWidth,
rowCount: rowCount,
rowHeight: itemHeight,
style: _objectSpread2({}, overflowStyling),
itemData: _objectSpread2(_objectSpread2({}, commonItemData), {}, {
column: undefined,
columnCount,
rowCount
}),
onItemsRendered: handleGridItemsRendered,
ref: ref
}), RowColumn);
};
return {
List,
Grid
};
}
function calculateColumnMode(_ref) {
let {
maxVisibleRows,
itemHeight,
listCount,
listHeight,
columnAutoWidth,
containerWidth,
itemMinWidth
} = _ref;
let rowCount;
const maxRows = (maxVisibleRows === null || maxVisibleRows === void 0 ? void 0 : maxVisibleRows.maxRows) || 3;
const autoRowCount = Math.floor(listHeight / itemHeight);
if (maxVisibleRows.auto !== false) {
rowCount = autoRowCount;
} else {
rowCount = Math.min(listCount, maxRows, autoRowCount);
}
rowCount = Math.max(rowCount, 1);
const columnCount = Math.ceil(listCount / rowCount);
const columnWidth = Math.max(columnAutoWidth, containerWidth / columnCount, itemMinWidth);
return {
columnWidth,
columnCount,
rowCount
};
}
function calculateRowMode(_ref) {
let {
maxVisibleColumns,
listCount,
containerWidth,
columnAutoWidth,
itemMinWidth
} = _ref;
const maxColumns = (maxVisibleColumns === null || maxVisibleColumns === void 0 ? void 0 : maxVisibleColumns.maxColumns) || 3;
const innerWidth = containerWidth - SCROLL_BAR_WIDTH;
let columnCount;
const autoColumnCount = Math.min(listCount, Math.max(1, Math.round(innerWidth / Math.max(itemMinWidth, columnAutoWidth)))); // TODO: smarter sizing... based on glyph count + font size etc...??
if ((maxVisibleColumns === null || maxVisibleColumns === void 0 ? void 0 : maxVisibleColumns.auto) !== false) {
columnCount = autoColumnCount;
} else {
columnCount = Math.min(listCount, maxColumns, autoColumnCount);
}
columnCount = Math.max(columnCount, 1);
const columnWidth = innerWidth / columnCount;
const rowCount = Math.ceil(listCount / columnCount);
return {
rowCount,
columnWidth,
columnCount
};
}
const getContext = () => {
const fragment = document.createDocumentFragment();
const canvas = document.createElement('canvas');
fragment.appendChild(canvas);
return canvas.getContext('2d');
};
const getTextWidth = (currentText, font) => {
const context = getContext();
context.font = font;
if (Array.isArray(currentText)) {
return Math.max(...currentText.map(t => context.measureText(t).width));
}
const metrics = context.measureText(currentText);
return Math.ceil(metrics.width || 0);
};
const useTextWidth = options => {
const textOptions = reactExports.useMemo(() => 'text' in options ? options : {}, [options]);
return reactExports.useMemo(() => getTextWidth(textOptions.text, textOptions.font || '12px Source Sans Pro'), [textOptions.text, textOptions.font]);
};
function getMeasureText(layoutOrNumber) {
if (!layoutOrNumber) {
return '';
}
const maxGlyphCount = typeof layoutOrNumber === 'number' ? layoutOrNumber : layoutOrNumber.qListObject.qDimensionInfo.qApprMaxGlyphCount;
const measureString = Array(maxGlyphCount).fill('M').join('');
return measureString;
}
function getItemHeight(_ref) {
let {
isGridMode,
dense
} = _ref;
const normalItemHeight = isGridMode ? GRID_ROW_HEIGHT : LIST_ROW_HEIGHT;
let itemHeight = dense ? DENSE_ROW_HEIGHT : normalItemHeight;
if (isGridMode) {
// Emulate a margin between items using padding, since the list library
// needs an explicit row height and cannot handle margins.
itemHeight += GRID_ITEM_PADDING;
}
return itemHeight;
}
function useListSizes(_ref) {
let {
layout,
width,
height,
listCount,
count,
freqIsAllowed,
checkboxes,
styles
} = _ref;
const {
layoutOptions = {}
} = layout || {};
const {
layoutOrder,
maxVisibleRows = {},
maxVisibleColumns,
dense,
dataLayout
} = layoutOptions;
const {
fontSize = '12px',
fontFamily = 'Source sans pro'
} = (styles === null || styles === void 0 ? void 0 : styles.content) || {};
const font = "".concat(fontSize, " ").concat(fontFamily); // font format as supported by HTML canvas
const textWidth = useTextWidth({
text: getMeasureText(layout),
font
});
const freqMinWidth = useTextWidth({
text: getMeasureText(5),
font
});
const freqMaxWidth = useTextWidth({
text: getMeasureText(8),
font
});
const frequencyAddWidth = freqIsAllowed ? freqMinWidth : 0;
const checkboxAddWidth = checkboxes ? CHECKBOX_WIDTH : 0;
const tickIconWidth = CHECKBOX_WIDTH;
let dynamicItemMinWidth = ITEM_MIN_WIDTH + frequencyAddWidth + checkboxAddWidth;
if (!checkboxes && dynamicItemMinWidth >= REMOVE_TICK_LIMIT) {
dynamicItemMinWidth += tickIconWidth;
}
let columnAutoWidth = textWidth + 18 + frequencyAddWidth + checkboxAddWidth;
if (!checkboxes && columnAutoWidth >= REMOVE_TICK_LIMIT) {
columnAutoWidth += tickIconWidth;
}
columnAutoWidth = Math.min(ITEM_MAX_WIDTH, Math.max(columnAutoWidth, dynamicItemMinWidth));
let overflowStyling;
let columnCount;
let columnWidth;
let rowCount;
const isGridMode = dataLayout === 'grid';
const itemHeight = getItemHeight({
isGridMode,
dense
});
const listHeight = height !== null && height !== void 0 ? height : 8 * itemHeight;
if (layoutOrder) {
// Modify container width to achieve the exact design with 8px margins on each side (left and right).
let containerWidth = width;
if (layoutOrder === 'row') {
overflowStyling = {
overflowX: 'hidden'
};
containerWidth += GRID_ITEM_PADDING * 2;
({
rowCount,
columnWidth,
columnCount
} = calculateRowMode({
maxVisibleColumns,
listCount,
containerWidth,
columnAutoWidth,
itemMinWidth: dynamicItemMinWidth
}));
} else {
overflowStyling = {
overflowY: 'hidden'
};
({
rowCount,
columnWidth,
columnCount
} = calculateColumnMode({
maxVisibleRows,
itemHeight,
listCount,
listHeight,
columnAutoWidth,
containerWidth,
itemMinWidth: dynamicItemMinWidth
}));
}
}
columnCount = (dataLayout === 'singleColumn' ? 1 : columnCount) || 1;
rowCount = (dataLayout === 'singleColumn' ? count : rowCount) || listCount;
const maxRowCount = layoutOptions.dense ? 838000 : 577000; // Styling breaks on items above this number: https://github.com/bvaughn/react-window/issues/659
rowCount = Math.min(rowCount, maxRowCount);
const maxScrollWidth = 33550000; // Styling breaks on items above this width: https://github.com/bvaughn/react-window/issues/659
const maxColumnCount = Math.floor(maxScrollWidth / columnWidth);
columnCount = Math.min(columnCount, maxColumnCount) || 1;
const maxListCount = rowCount * columnCount;
const limitedListCount = Math.min(listCount, maxListCount);
return {
columnCount,
columnWidth,
rowCount,
overflowStyling,
itemHeight,
listHeight,
listWidth: width,
scrollBarWidth: SCROLL_BAR_WIDTH,
count,
listCount: limitedListCount,
maxCount: {
row: maxRowCount,
column: maxColumnCount
},
itemPadding: GRID_ITEM_PADDING,
textWidth,
freqMinWidth,
freqMaxWidth
};
}
function getHorizontalMinBatchSize(_ref) {
let {
width,
columnWidth,
listHeight,
itemHeight
} = _ref;
const visibleCellsCount = Math.ceil(width / columnWidth) * Math.ceil(listHeight / itemHeight);
const minSize = visibleCellsCount * 2;
return minSize;
}
/* eslint-disable no-param-reassign */
function useItemsLoader(_ref) {
let {
local,
loaderRef,
model,
fetchStart,
scrollTimeout,
postProcessPages,
listData
} = _ref;
const [isLoading, setIsLoading] = reactExports.useState(false);
const [pages, setPages] = reactExports.useState([]);
let [minimumBatchSize] = reactExports.useState(0);
const loadMoreItems = (startIndex, stopIndex) => {
const offset = local.current.dataOffset;
local.current.queue.push({
start: startIndex + offset,
stop: stopIndex + offset
});
const isScrolling = loaderRef.current ?
// eslint-disable-next-line no-underscore-dangle
loaderRef.current._listRef && loaderRef.current._listRef.state.isScrolling : false;
if (local.current.queue.length > 10) {
local.current.queue.shift();
}
clearTimeout(local.current.timeout);
setIsLoading(true);
return new Promise(resolve => {
local.current.timeout = setTimeout(() => {
const lastItemInQueue = local.current.queue.slice(-1)[0];
if (!lastItemInQueue) {
setIsLoading(false);
resolve();
return;
}
const reqPromise = model.getListObjectData('/qListObjectDef',
// we need to ask for two payloads
// 2nd one is our starting index + minimumBatchSize items
// 1st one is 2nd ones starting index - minimumBatchSize items
// we do this because we don't want to miss any items between fast scrolls
[{
qTop: lastItemInQueue.start > minimumBatchSize ? lastItemInQueue.start - minimumBatchSize : 0,
qHeight: minimumBatchSize,
qLeft: 0,
qWidth: 1
}, {
qTop: lastItemInQueue.start,
qHeight: minimumBatchSize,
qLeft: 0,
qWidth: 1
}]).then(p => {
const processedPages = postProcessPages ? postProcessPages(p) : p;
local.current.validPages = true;
listData.current.pages = processedPages;
setPages(processedPages);
setIsLoading(false);
resolve();
});
fetchStart && fetchStart(reqPromise);
}, isScrolling ? scrollTimeout : 0);
});
};
return {
loadMoreItems: {
with(_ref2) {
let {
minimumBatchSize: m
} = _ref2;
if (m) {
minimumBatchSize = m;
}
return loadMoreItems;
}
},
pages,
isLoading
};
}
const getCalculatedHeight = _ref => {
let {
pages = [],
minimumBatchSize,
count
} = _ref;
// If values have been filtered in the currently loaded page, we want to
// prevent rendering empty rows by assigning the actual number of items to render
// since count (qcy) does not reflect this in DQ mode currently.
const hasFilteredValues = pages.some(page => page.qArea.qHeight < minimumBatchSize);
const h = Math.max(...pages.map(page => page.qArea.qTop + page.qArea.qHeight));
const out = hasFilteredValues ? h : count;
return out;
};
function getListCount(_ref2) {
let {
pages,
minimumBatchSize,
count,
calculatePagesHeight = false
} = _ref2;
const listCount = pages !== null && pages !== void 0 && pages.length && calculatePagesHeight ? getCalculatedHeight({
pages,
minimumBatchSize,
count
}) : count;
return listCount || 0;
}
const [useVizDataStore] = createKeyStore({});
function useDataStore(model) {
const keyPrefix = "".concat(model.id);
const [vizDataStore] = useVizDataStore();
const setStoreValue = (key, val) => vizDataStore.set("".concat(keyPrefix, "/").concat(key), val);
const getStoreValue = key => vizDataStore.get("".concat(keyPrefix, "/").concat(key));
return {
setStoreValue,
getStoreValue
};
}
const StyledText = styled(Typography, {
shouldForwardProp: p => !['width', 'dense'].includes(p)
})(_ref => {
let {
width,
dense
} = _ref;
return _objectSpread2({
minWidth: "".concat(width, "px"),
textAlign: 'center',
fontSize: "".concat(dense ? '12px' : '14px'),
whiteSpace: 'normal'
}, dense && {
textOverflow: 'ellipsis',
overflow: 'hidden',
whiteSpace: 'nowrap',
width
});
});
function ListBoxDisclaimer(_ref2) {
let {
width,
text,
dense,
tooltip
} = _ref2;
const {
translator: translatorDynamic
} = reactExports.useContext(InstanceContext);
return /*#__PURE__*/React.createElement(Tooltip, {
title: tooltip ? translatorDynamic.get(text) : ''
}, /*#__PURE__*/React.createElement(StyledText, {
width: width,
dense: dense,
component: "div",
variant: "body1",
py: "12px"
}, translatorDynamic.get(text)));
}
var CloseIcon = createSvgIcon(/*#__PURE__*/jsxRuntimeExports.jsx("path", {
d: "M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
}), 'Close');
const RootContainer = styled(Paper)(_ref => {
let {
theme,
left
} = _ref;
return {
position: 'absolute',
bottom: '12px',
display: 'flex',
border: "1px solid ".concat(theme.palette.divider),
width: 'calc(100% - 11px)',
left
};
});
const LeftItem = styled('div')(() => ({
paddingLeft: '6px',
flexGrow: 1
}));
const RightItem = styled('div')(_ref2 => {
let {
dense
} = _ref2;
return {
display: 'flex',
alignItems: "".concat(dense ? 'center' : 'flex-start')
};
});
const SmallCloseIcon = styled(CloseIcon)(() => ({
fontSize: '14px'
}));
function ListBoxFooter(_ref3) {
let {
text,
dismiss,
dense,
parentWidth = 0
} = _ref3;
const hasDismissButton = typeof dismiss === 'function';
const maxWidth = dense ? 370 : 282;
const left = Math.max(parentWidth / 2 - maxWidth / 2, 0);
const textWidth = Math.min(maxWidth, parentWidth) - 42;
const enableTooltip = dense && parentWidth < maxWidth;
return /*#__PURE__*/React.createElement(RootContainer, {
left: left,
style: {
maxWidth
}
}, /*#__PURE__*/React.createElement(LeftItem, null, /*#__PURE__*/React.createElement(ListBoxDisclaimer, {
text: text,
dense: dense,
width: textWidth,
tooltip: enableTooltip
})), /*#__PURE__*/React.createElement(RightItem, {
dense: dense
}, hasDismissButton && /*#__PURE__*/React.createElement(IconButton, {
"aria-label": "close",
onClick: () => dismiss()
}, /*#__PURE__*/React.createElement(SmallCloseIcon, null))));
}
const getOffset = (layout, listCount) => {
const totalLength = layout.qListObject.qDimensionInfo.qCardinal;
const offset = totalLength - listCount;
return offset;
};
function getScrollIndex(_ref) {
let {
position,
isRow,
sizes,
layout,
offset
} = _ref;
let scrollIndex;
let triggerRerender = false;
let newOffset = offset !== null && offset !== void 0 ? offset : 0;
switch (position) {
case 'start':
scrollIndex = 0;
break;
case 'end':
scrollIndex = isRow ? sizes.rowCount : sizes.columnCount;
break;
case 'overflowStart':
newOffset = 0;
scrollIndex = 0;
triggerRerender = true;
break;
case 'overflowEnd':
newOffset = getOffset(layout, sizes.listCount);
scrollIndex = layout.qListObject.qDimensionInfo.qCardinal;
triggerRerender = true;
break;
}
return {
scrollIndex,
offset: newOffset,
triggerRerender
};
}
const FREQUENCY_MIN_SHOW_WIDTH = 80;
function getFrequencyAllowed(_ref) {
let {
itemWidth,
layout,
frequencyMode
} = _ref;
const widthPermitsFreq = itemWidth > FREQUENCY_MIN_SHOW_WIDTH;
const {
frequencyEnabled = false
} = (layout === null || layout === void 0 ? void 0 : layout.qListObject) || {};
const hasValidFreqOption = !['N', undefined].includes(frequencyMode);
return !!(widthPermitsFreq && (hasValidFreqOption || frequencyEnabled));
}
const escapeField = field => {
if (!field || field === ']') {
return field;
}
if (/^[A-Za-z][A-Za-z0-9_]*$/.test(field)) {
return field;
}
return "[".concat(field.replace(/\]/g, ']]'), "]");
};
const needToFetchFrequencyMax = layout => (layout === null || layout === void 0 ? void 0 : layout.frequencyMax) === 'fetch';
const getFrequencyMaxExpression = field => {
const escapedField = escapeField(field);
return "Max(AGGR(Count(".concat(escapedField, "), ").concat(escapedField, "))");
};
const getFrequencyMax = async (layout, app) => {
const dimInfo = layout.qListObject.qDimensionInfo;
const field = dimInfo.qGroupFieldDefs[dimInfo.qGroupPos];
const expression = getFrequencyMaxExpression(field);
const evaluadedExpression = await app.evaluateEx(expression);
return evaluadedExpression.qNumber;
};
const useFrequencyMax = (app, layout) => {
const needFetch = needToFetchFrequencyMax(layout);
const [frequencyMax, setFrequencyMax] = reactExports.useState();
const [awaitingFrequencyMax, setAwaitingFrequencyMax] = reactExports.useState(needFetch);
reactExports.useEffect(() => {
if (!needFetch) {
return;
}
const fetch = async () => {
const newValue = await getFrequencyMax(layout, app);
setFrequencyMax(newValue);
setAwaitingFrequencyMax(false);
};
fetch();
}, [needFetch && layout]);
return {
frequencyMax: needFetch ? frequencyMax : layout === null || layout === void 0 ? void 0 : layout.frequencyMax,
awaitingFrequencyMax
};
};
/**
* Announces the selection state.
*
* @ignore
* @param {Layout} object
* @returns {string}
*/
function getSRForSelectedState(_ref) {
var _layout$qListObject;
let {
layout,
translatorDynamic
} = _ref;
const {
qStateCounts: s = {}
} = (layout === null || layout === void 0 || (_layout$qListObject = layout.qListObject) === null || _layout$qListObject === void 0 ? void 0 : _layout$qListObject.qDimensionInfo) || {};
const count = s.qSelected + s.qSelectedExcluded + s.qLocked + s.qLockedExcluded;
let t;
switch (count) {
case 0:
t = 'ScreenReader.ZeroSelected';
break;
case 1:
t = 'ScreenReader.OneSelected';
break;
default:
t = 'ScreenReader.ManySelected';
break;
}
const text = translatorDynamic.get(t, [count]);
return text;
}
function getSearchTranslationString(listCount) {
let t;
switch (listCount) {
case 0:
t = 'Listbox.NoMatchesForYourTerms';
break;
case 1:
t = 'ScreenReader.OneSearchResult';
break;
default:
t = 'ScreenReader.ManySearchResults';
break;
}
return t;
}
function getScreenReaderAssertiveText(_ref2) {
let {
layout,
searchInputText,
listCount
} = _ref2;
const {
translator: translatorDynamic
} = reactExports.useContext(InstanceContext);
const finalStringArr = [];
if (searchInputText !== null && searchInputText !== void 0 && searchInputText.length) {
// Add search result text.
const srSearchTranslationString = getSearchTranslationString(listCount);
const srSearchString = translatorDynamic.get(srSearchTranslationString, [listCount]);
finalStringArr.push(srSearchString);
}
// Add selection value text.
const srSelectionValueText = getSRForSelectedState({
layout,
translatorDynamic
});
finalStringArr.push(srSelectionValueText);
// Merge texts into one text string, targeting the assertive screen reader.
const finalString = finalStringArr.filter(v => !!(v !== null && v !== void 0 && v.length)).join('. ');
return finalString;
}
function deduceFrequencyMode(pages) {
const hasPercentSign = pages.some(_ref => {
let {
qMatrix
} = _ref;
return qMatrix.some(_ref2 => {
var _item$qFrequency;
let [item] = _ref2;
return !!((_item$qFrequency = item.qFrequency) !== null && _item$qFrequency !== void 0 && _item$qFrequency.match('%'));
});
});
const OTHER = '-'; // treat all other as '-' (change later if we need to identify other modes)
return hasPercentSign ? 'P' : OTHER;
}
const _excluded$4 = ["isLoadingData"];
const DEFAULT_MIN_BATCH_SIZE = 100;
const StyledWrapper = styled('div')(() => ({
["& .screenReaderOnly"]: {
position: 'absolute',
height: 0,
width: 0,
overflow: 'hidden'
}
}));
function ListBox(_ref) {
var _layout$qListObject$q, _loaderRef$current;
let {
model,
app,
constraints,
layout,
selections,
selectionState,
direction,
checkboxes: checkboxOption,
height,
width,
frequencyMode,
update = undefined,
fetchStart = undefined,
postProcessPages = undefined,
calculatePagesHeight = false,
keyboard = {},
showGray = true,
scrollState,
keyScroll = {
state: {},
reset: () => {}
},
currentScrollIndex = {
set: () => {}
},
renderedCallback,
onCtrlF,
showSearch,
isModal,
styles
} = _ref;
const {
translator: translatorDynamic
} = reactExports.useContext(InstanceContext);
const [initScrollPosIsSet, setInitScrollPosIsSet] = reactExports.useState(false);
const isSingleSelect = !!(layout && layout.qListObject.qDimensionInfo.qIsOneAndOnlyOne);
const {
checkboxes = checkboxOption,
histogram
} = layout !== null && layout !== void 0 ? layout : {};
const loaderRef = reactExports.useRef(null);
const local = reactExports.useRef({
queue: [],
validPages: false,
dataOffset: 0
});
const listData = reactExports.useRef({
pages: []
});
// The time from scroll end until new data is being fetched, may be exposed in API later on.
const scrollTimeout = 0;
const {
frequencyMax,
awaitingFrequencyMax
} = useFrequencyMax(app, layout);
// eslint-disable-next-line no-unused-vars
const _useItemsLoader = useItemsLoader({
local,
loaderRef,
model,
fetchStart,
scrollTimeout,
postProcessPages,
listData
}),
{
isLoadingData
} = _useItemsLoader,
itemsLoader = _objectWithoutProperties(_useItemsLoader, _excluded$4);
const {
getStoreValue,
setStoreValue
} = useDataStore(model);
const loadMoreItems = reactExports.useCallback(itemsLoader.loadMoreItems, [layout]);
const [overflowDisclaimer, setOverflowDisclaimer] = reactExports.useState({
show: false,
dismissed: false
});
const showOverflowDisclaimer = show => setOverflowDisclaimer(state => _objectSpread2(_objectSpread2({}, state), {}, {
show
}));
const [pages, setPages] = reactExports.useState([]);
if (itemsLoader !== null && itemsLoader !== void 0 && itemsLoader.pages) {
selectionState.update({
setPages,
pages: itemsLoader.pages,
isSingleSelect,
layout
});
}
const cardinal = layout === null || layout === void 0 ? void 0 : layout.qListObject.qDimensionInfo.qCardinal;
if (itemsLoader !== null && itemsLoader !== void 0 && itemsLoader.pages.length && !awaitingFrequencyMax || cardinal === 0) {
// All necessary data fetching done - signal rendering done!
renderedCallback === null || renderedCallback === void 0 || renderedCallback();
}
const isItemLoaded = reactExports.useCallback(index => {
if (!(pages !== null && pages !== void 0 && pages.length) || !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]);
const {
interactionEvents,
select
} = useSelectionsInteractions({
selectionState,
selections,
checkboxes,
doc: document,
loaderRef
});
const {
layoutOptions = {}
} = layout || {};
let isRow = true;
if (layoutOptions.dataLayout) {
isRow = layoutOptions.dataLayout === 'singleColumn' ? true : (layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.layoutOrder) === 'row';
}
const isGrid = (layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.dataLayout) === 'grid';
const scrollToIndex = index => {
const gridIndex = _objectSpread2({}, isRow ? {
rowIndex: index
} : {
columnIndex: index
});
const scrollIndex = isGrid ? gridIndex : index;
loaderRef.current._listRef.scrollToItem(scrollIndex);
};
const fetchData = () => {
local.current.queue = [];
local.current.validPages = false;
if (loaderRef.current) {
loaderRef.current.resetloadMoreItemsCache(true);
const isScrollingToEnd = keyScroll.state.scrollPosition === 'overflowEnd';
// Skip scrollToItem if we are in selections or if scrolling to the end.
if (layout && layout.qSelectionInfo.qInSelections || isScrollingToEnd) {
if (isScrollingToEnd) {
keyScroll.reset();
}
return;
}
local.current.dataOffset = 0;
scrollToIndex(0);
}
};
if (update) {
// Hand over the update function for manual refresh from hosting application.
update.call(null, fetchData);
}
reactExports.useEffect(() => {
if (scrollState && !initScrollPosIsSet && loaderRef.current) {
loaderRef.current._listRef.scrollToItem(scrollState.initScrollPos);
setInitScrollPosIsSet(true);
}
}, [loaderRef.current]);
reactExports.useEffect(() => {
fetchData();
}, [layout, local.current.dataOffset]);
let minimumBatchSize = DEFAULT_MIN_BATCH_SIZE;
const isVertical = layoutOptions.dataLayout !== 'grid';
const count = layout === null || layout === void 0 || (_layout$qListObject$q = layout.qListObject.qSize) === null || _layout$qListObject$q === void 0 ? void 0 : _layout$qListObject$q.qcy;
const unlimitedListCount = getListCount({
pages,
minimumBatchSize,
count,
calculatePagesHeight});
let freqIsAllowed = getFrequencyAllowed({
itemWidth: width,
layout,
frequencyMode
});
const deducedFrequencyMode = deduceFrequencyMode(pages);
const sizes = useListSizes({
layout,
width,
height,
listCount: unlimitedListCount,
count,
freqIsAllowed,
checkboxes,
styles
});
if (sizes.columnWidth) {
// In grid mode, where we have a dynamic item width, get a second opinion on showing/hiding frequency.
freqIsAllowed = getFrequencyAllowed({
itemWidth: sizes.columnWidth,
layout,
frequencyMode
});
}
const {
listCount
} = sizes;
setStoreValue('listCount', listCount);
const searchInputText = getStoreValue('inputText');
const screenReaderText = getScreenReaderAssertiveText({
layout,
searchInputText,
listCount
});
const setScrollPosition = position => {
const {
scrollIndex,
offset,
triggerRerender
} = getScrollIndex({
position,
isRow,
sizes,
layout,
offset: local.current.dataOffset
});
local.current.dataOffset = offset;
if (triggerRerender) {
selectionState.triggerStateChanged();
}
scrollToIndex(scrollIndex);
};
reactExports.useEffect(() => {
const s = keyScroll.state;
if (s.up) {
scrollToIndex(currentScrollIndex.state.start - s.up);
} else if (s.down) {
scrollToIndex(currentScrollIndex.state.stop + s.down);
} else if (s.scrollPosition) {
setScrollPosition(s.scrollPosition);
}
if (s.scrollPosition === 'overflowEnd') {
return; // Do keyScroll.reset() in fetchData() to avoid scrolling to top.
}
keyScroll.reset();
}, [keyScroll.state.up, keyScroll.state.down, keyScroll.state.scrollPosition]);
const {
textAlign
} = (layout === null || layout === void 0 ? void 0 : layout.qListObject.qDimensionInfo) || {};
const [focusListItem, setFocusListItem] = reactExports.useState({
first: false,
last: false
});
const getFocusState = () => ({
first: focusListItem.first,
setFirst: first => setFocusListItem(prevState => _objectSpread2(_objectSpread2({}, prevState), {}, {
first
})),
last: focusListItem.last,
setLast: last => setFocusListItem(prevState => _objectSpread2(_objectSpread2({}, prevState), {}, {
last
}))
});
const selectAll = () => {
selectionState.clearItemStates(false);
model.selectListObjectAll('/qListObjectDef');
};
const {
List,
Grid
} = getListBoxComponents({
direction,
layout,
width,
checkboxes,
deducedFrequencyMode,
histogram,
keyboard,
showGray,
interactionEvents,
select,
selectAll,
onCtrlF,
textAlign,
isVertical,
pages,
selectionState,
isSingleSelect,
selections,
scrollState,
local,
sizes,
listCount,
overflowDisclaimer: {
state: overflowDisclaimer,
set: showOverflowDisclaimer
},
setScrollPosition,
focusListItems: getFocusState(),
setCurrentScrollIndex: currentScrollIndex.set,
constraints,
frequencyMax,
freqIsAllowed,
translator: translatorDynamic,
showSearch,
isModal,
styles
});
const {
columnWidth,
listHeight,
itemHeight
} = sizes || {};
if (!isVertical) {
minimumBatchSize = getHorizontalMinBatchSize({
width,
columnWidth,
listHeight,
itemHeight
});
}
return /*#__PURE__*/React.createElement(StyledWrapper, null, /*#__PURE__*/React.createElement("div", {
className: "screenReaderOnly",
"aria-live": "assertive"
}, screenReaderText), !listCount && cardinal > 0 && /*#__PURE__*/React.createElement(ListBoxDisclaimer, {
width: width,
text: "Listbox.NoMatchesForYourTerms"
}), /*#__PURE__*/React.createElement(InfiniteLoader, {
isItemLoaded: isItemLoaded,
itemCount: listCount || 1 // must be more than 0 or loadMoreItems will never be called again
,
loadMoreItems: loadMoreItems.with({
minimumBatchSize
}),
threshold: 0,
minimumBatchSize: minimumBatchSize,
ref: loaderRef,
role: "grid"
}, isVertical ? List : Grid), overflowDisclaimer.show && !overflowDisclaimer.dismissed && /*#__PURE__*/React.createElement(ListBoxFooter, {
text: "Listbox.ItemsOverflow",
dismiss: () => setOverflowDisclaimer(state => _objectSpread2(_objectSpread2({}, state), {}, {
dismissed: true
})),
parentWidth: loaderRef === null || loaderRef === void 0 || (_loaderRef$current = loaderRef.current) === null || _loaderRef$current === void 0 || (_loaderRef$current = _loaderRef$current._listRef) === null || _loaderRef$current === void 0 || (_loaderRef$current = _loaderRef$current.props) === null || _loaderRef$current === void 0 ? void 0 : _loaderRef$current.width,
dense: layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.dense
}));
}
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,
selectionState,
isDirectQuery = false,
selections
} = _ref;
if (layout.qListObject.qDimensionInfo.qIsOneAndOnlyOne) {
return [];
}
const path = '/qListObjectDef';
const activateSelection = () => {
if (!selections.isActive()) {
selections.begin(path);
}
};
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: () => {
activateSelection();
selectionState.clearItemStates(false);
model.selectListObjectAll(path);
}
}, {
key: 'selectPossible',
type: 'menu-icon-button',
label: translator.get('Selection.SelectPossible'),
getSvgIconShape: selectPossible,
enabled: canSelectPossible,
action: () => {
activateSelection();
selectionState.clearItemStates(false);
model.selectListObjectPossible(path);
}
}, isDirectQuery ? false : {
key: 'selectAlternative',
type: 'menu-icon-button',
label: translator.get('Selection.SelectAlternative'),
getSvgIconShape: selectAlternative,
enabled: canSelectAlternative,
action: () => {
activateSelection();
selectionState.clearItemStates(false);
model.selectListObjectAlternative(path);
}
}, isDirectQuery ? false : {
key: 'selectExcluded',
type: 'menu-icon-button',
label: translator.get('Selection.SelectExcluded'),
getSvgIconShape: selectExcluded,
enabled: canSelectExcluded,
action: () => {
activateSelection();
selectionState.clearItemStates(false);
model.selectListObjectExcluded(path);
}
}].filter(Boolean);
};
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 spacing = Number.parseInt(theme.spacing(0.5), 10);
const keyboardAction = item.keyboardAction || item.action;
const handleKeyDown = keyboardAction ? e => ['Enter'].includes(e.key) && keyboardAction() : null;
const handleKeyUp = keyboardAction ? e => [' ', 'Spacebar'].includes(e.key) && keyboardAction() : null;
const btnId = "actions-toolbar-".concat(item.key);
return /*#__PURE__*/React.createElement(IconButton, {
ref: !addAnchor ? ref : null,
title: item.label,
onClick: item.action,
onKeyDown: handleKeyDown,
onKeyUp: handleKeyUp,
disabled: disabled,
style: style,
className: [ActionElement.className, btnId].join(' '),
size: "large",
disableRipple: true,
"aria-label": item.label,
"data-testid": btnId
}, hasSvgIconShape && SvgIcon(item.getSvgIconShape()), addAnchor && /*#__PURE__*/React.createElement("div", {
ref: ref,
style: {
bottom: -spacing,
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'
}
}]
});
var Close = props => SvgIcon(close(props));
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,
layout,
onConfirm = () => {},
onCancel = () => {},
onKeyDeactivate = () => {}
} = _ref;
const {
translator
} = reactExports.useContext(InstanceContext);
return [{
key: 'clear',
type: 'icon-button',
label: translator.get('Selection.Clear'),
enabled: () => api.canClear(layout),
action: () => api.clear(),
getSvgIconShape: clearSelections
}, {
key: 'cancel',
type: 'icon-button',
label: translator.get('Selection.Cancel'),
enabled: () => api.canCancel(layout),
action: () => {
onCancel();
api.cancel();
},
keyboardAction: () => {
onKeyDeactivate();
onCancel();
api.cancel();
},
getSvgIconShape: close
}, {
key: 'confirm',
type: 'icon-button',
label: translator.get('Selection.Confirm'),
enabled: () => api.canConfirm(layout),
action: () => {
onConfirm();
api.confirm();
},
keyboardAction: () => {
onKeyDeactivate();
onConfirm();
api.confirm();
},
getSvgIconShape: tick
}];
}
const PREFIX$8 = 'More';
const ActionsToolbarMoreElement = {
className: 'njs-action-toolbar-more'
};
const classes$8 = {
icon: "".concat(PREFIX$8, "-icon")
};
const StyledPopover$1 = styled(Popover)(_ref => {
let {
theme
} = _ref;
return {
// Set here to allow clicking through the modals container
pointerEvents: 'none',
["& .".concat(classes$8.icon, " *")]: {
color: theme.palette.text.primary
}
};
});
function MoreItem(_ref2) {
let {
item,
autoFocus,
onActionClick = () => {}
} = _ref2;
const {
hidden,
disabled,
hasSvgIconShape
} = useActionState(item);
const handleClick = () => {
item.action();
onActionClick();
};
return !hidden ? /*#__PURE__*/React.createElement(MenuItem, {
autoFocus: autoFocus,
title: item.label,
onClick: handleClick,
disabled: disabled,
tabindex: "0"
}, hasSvgIconShape && /*#__PURE__*/React.createElement(ListItemIcon, {
className: classes$8.icon
}, SvgIcon(item.getSvgIconShape())), /*#__PURE__*/React.createElement(Typography, {
noWrap: true
}, item.label)) : null;
}
const More$1 = React.forwardRef((_ref3, ref) => {
let {
actions = [],
show = true,
alignTo,
popoverProps = {},
popoverPaperStyle = {},
onCloseOrActionClick = () => {},
disablePortal = true
} = _ref3;
const showActions = actions.length > 0;
const autoFocusIndex = actions.findIndex(action => !action.disabled);
return showActions && /*#__PURE__*/React.createElement(StyledPopover$1
// eslint-disable-next-line react/jsx-props-no-spreading
, _extends$1({}, popoverProps, {
onClose: onCloseOrActionClick,
ref: ref,
open: show,
anchorEl: alignTo.current,
getContentAnchorEl: disablePortal ? null : undefined,
container: disablePortal ? alignTo.current : undefined,
disablePortal: disablePortal,
hideBackdrop: true,
transitionDuration: 0,
slotProps: {
root: {
className: ActionsToolbarMoreElement.className
},
paper: {
style: _objectSpread2({
pointerEvents: 'auto',
maxWidth: '250px'
}, popoverPaperStyle)
}
},
anchorOrigin: {
vertical: 'bottom',
horizontal: 'right'
},
transformOrigin: {
vertical: 'top',
horizontal: 'right'
}
}), /*#__PURE__*/React.createElement(MenuList, {
id: "moreMenuList"
}, actions.map((item, ix) =>
/*#__PURE__*/
// eslint-disable-next-line react/no-array-index-key
React.createElement(MoreItem, {
key: ix,
item: item,
autoFocus: ix === autoFocusIndex,
onActionClick: onCloseOrActionClick
}))));
});
const getActionButtonIndex = btn => {
const toolbar = btn.closest('#actions-toolbar');
const nodeList = toolbar === null || toolbar === void 0 ? void 0 : toolbar.querySelectorAll('.njs-cell-action');
return Array.from(nodeList).indexOf(btn);
};
const focusButton = index => {
const toolbar = document.querySelector('#actions-toolbar');
const nodeList = toolbar === null || toolbar === void 0 ? void 0 : toolbar.querySelectorAll('.njs-cell-action');
if (!nodeList.length) {
return;
}
const ix = Math.min(Math.max(0, index), nodeList.length - 1);
const btn = nodeList[ix];
btn.focus();
};
function getActionsKeyDownHandler(_ref) {
let {
keyboardNavigation,
focusHandler,
getEnabledButton,
selections,
isRtl
} = _ref;
const handleActionsKeyDown = evt => {
const {
target,
nativeEvent
} = evt;
const {
keyCode
} = nativeEvent;
switch (keyCode) {
case KEYS.ARROW_LEFT:
case KEYS.ARROW_DOWN:
case KEYS.ARROW_RIGHT:
case KEYS.ARROW_UP:
{
const isActionButton = target.classList.contains('njs-cell-action');
if (isActionButton) {
const index = getActionButtonIndex(target);
let pressedLeft = [KEYS.ARROW_LEFT, KEYS.ARROW_DOWN].includes(keyCode);
pressedLeft = isRtl ? !pressedLeft : pressedLeft; // invert direction when using RTL
focusButton(pressedLeft ? index - 1 : index + 1);
}
evt.stopPropagation();
evt.preventDefault();
break;
}
case KEYS.SPACE:
evt.preventDefault(); // prevent scrolling in listbox
break;
case KEYS.TAB:
if (keyboardNavigation && focusHandler !== null && focusHandler !== void 0 && focusHandler.refocusContent) {
const isTabbingOut = evt.shiftKey && getEnabledButton(false) === evt.target || !evt.shiftKey && getEnabledButton(true) === evt.target;
if (isTabbingOut) {
evt.preventDefault();
evt.stopPropagation();
// if keyboardNavigation is true, create a callback to handle tabbing from the first/last button in the toolbar that resets focus on the content
focusHandler.refocusContent();
}
}
break;
case KEYS.ESCAPE:
if (selections) {
selections.onCancel();
selections.api.cancel();
evt.preventDefault();
evt.stopPropagation();
}
break;
}
};
return handleActionsKeyDown;
}
const PREFIX$7 = 'ActionsToolbar';
const classes$7 = {
item: "".concat(PREFIX$7, "-item"),
itemSpacing: "".concat(PREFIX$7, "-itemSpacing")
};
const StyledPopover = styled(Popover)(_ref => {
let {
theme
} = _ref;
return {
["& .".concat(classes$7.itemSpacing)]: {
padding: theme.spacing(0, 0.25)
}
};
});
/**
* @interface
* @extends HTMLElement
* @since 2.1.0
*/
const ActionToolbarElement = {
/** @type {'njs-action-toolbar-popover'} */
className: 'njs-action-toolbar-popover'
};
const ActionsGroup = React.forwardRef((_ref2, ref) => {
let {
className,
actions = [],
addAnchor = false,
isRtl = false
} = _ref2;
return actions.length > 0 ? /*#__PURE__*/React.createElement(Grid, {
item: true,
container: true,
gap: 0,
flexDirection: isRtl ? 'row-reverse' : 'row',
wrap: "nowrap",
className: className
}, actions.map((e, ix) => /*#__PURE__*/React.createElement(Grid, {
item: true,
key: e.key,
className: "".concat(classes$7.itemSpacing, " ").concat(classes$7.item)
}, /*#__PURE__*/React.createElement(Item, {
key: e.key,
item: e,
ref: ix === 0 ? ref : null,
addAnchor: addAnchor
})))) : null;
});
const popoverStyle = {
pointerEvents: 'none'
};
function ActionsToolbar(_ref3) {
var _popover$anchorEl$cli, _popover$anchorEl;
let {
show = true,
actions = [],
maxItems = 3,
selections = {
show: false,
api: null,
onConfirm: () => {},
onCancel: () => {}
},
extraItems,
more: more$1 = {
enabled: false,
actions: [],
alignTo: null,
popoverProps: {},
popoverPaperStyle: {},
disablePortal: true
},
popover = {
show: false,
anchorEl: null
},
focusHandler = null,
actionsRefMock = null,
// for testing
isRtl,
autoConfirm = false,
layout
} = _ref3;
const defaultSelectionActions = useDefaultSelectionActions(_objectSpread2(_objectSpread2({}, selections), {}, {
layout
}));
const {
translator,
keyboardNavigation
} = reactExports.useContext(InstanceContext);
const [showMoreItems, setShowMoreItems] = reactExports.useState(false);
const popoverAnchorOrigin = {
vertical: 12,
horizontal: isRtl ? 0 : ((_popover$anchorEl$cli = (_popover$anchorEl = popover.anchorEl) === null || _popover$anchorEl === void 0 ? void 0 : _popover$anchorEl.clientWidth) !== null && _popover$anchorEl$cli !== void 0 ? _popover$anchorEl$cli : 0) - 7
};
const popoverTransformOrigin = {
vertical: 'bottom',
horizontal: isRtl ? -7 : 'right'
};
const actionsRef = reactExports.useRef();
const moreRef = reactExports.useRef();
const theme = useTheme$1();
const dividerStyle = reactExports.useMemo(() => ({
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];
};
const handleActionsKeyDown = reactExports.useMemo(() => getActionsKeyDownHandler({
keyboardNavigation,
focusHandler,
getEnabledButton,
selections,
isRtl
}), [keyboardNavigation, focusHandler, getEnabledButton, selections, isRtl]);
reactExports.useEffect(() => () => {
setShowMoreItems(false);
}, [popover.show, show, selections.show]);
reactExports.useEffect(() => {
if (!focusHandler) return;
const focusFirst = () => {
const enabledButton = getEnabledButton(false);
enabledButton === null || enabledButton === void 0 || enabledButton.focus();
};
const focusLast = () => {
const enabledButton = getEnabledButton(true);
enabledButton === null || enabledButton === void 0 || enabledButton.focus();
};
focusHandler.on('focus_toolbar_first', focusFirst);
focusHandler.on('focus_toolbar_last', focusLast);
}, []);
if (autoConfirm) {
return undefined;
}
let moreEnabled = more$1.enabled;
let moreActions = more$1.actions;
const moreAlignTo = more$1.alignTo || moreRef;
const newActions = actions.filter(a => !a.hidden);
if (newActions.length > maxItems) {
const newMoreActions = newActions.splice(-(newActions.length - maxItems) - 1);
moreEnabled = true;
moreActions = [...newMoreActions, ...more$1.actions];
}
if (!selections.show && newActions.length === 0 && !moreEnabled) return null;
const handleCloseShowMoreItems = () => {
setShowMoreItems(false);
};
const moreItem = {
key: 'more',
label: translator.get('Menu.More'),
// TODO: Add translation
getSvgIconShape: more,
hidden: false,
active: showMoreItems,
enabled: () => moreEnabled,
action: () => setShowMoreItems(!showMoreItems)
};
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: handleActionsKeyDown,
container: true,
gap: 0,
wrap: "nowrap",
id: "actions-toolbar",
"data-testid": "actions-toolbar",
sx: {
flexDirection: isRtl ? 'row-reverse' : 'row'
}
}, (extraItems === null || extraItems === void 0 ? void 0 : extraItems.length) && /*#__PURE__*/React.createElement(ActionsGroup, {
className: "actions-toolbar-extra-actions",
actions: extraItems,
isRtl: isRtl
}), showActions && /*#__PURE__*/React.createElement(ActionsGroup, {
actions: newActions
}), showMore && /*#__PURE__*/React.createElement(ActionsGroup, {
id: "actions-toolbar-show-more",
"data-testid": "actions-toolbar-show-more",
ref: moreRef,
actions: [moreItem],
addAnchor: true
}), showDivider && /*#__PURE__*/React.createElement(Grid, {
item: true,
className: classes$7.itemSpacing,
style: dividerStyle
}, /*#__PURE__*/React.createElement(Divider, {
orientation: "vertical"
})), selections.show && /*#__PURE__*/React.createElement(ActionsGroup, {
className: "actions-toolbar-default-actions",
actions: defaultSelectionActions,
isRtl: isRtl
}), showMoreItems && /*#__PURE__*/React.createElement(More$1, {
show: showMoreItems,
actions: moreActions,
alignTo: moreAlignTo,
popoverProps: more$1.popoverProps,
popoverPaperStyle: more$1.popoverPaperStyle,
onCloseOrActionClick: handleCloseShowMoreItems,
disablePortal: more$1.disablePortal
}));
return popover.show ? /*#__PURE__*/React.createElement(StyledPopover, {
disableEnforceFocus: true,
disableAutoFocus: true,
disableRestoreFocus: true,
open: popover.show,
anchorEl: popover.anchorEl,
anchorOrigin: popoverAnchorOrigin,
transformOrigin: popoverTransformOrigin,
hideBackdrop: true,
style: popoverStyle,
onMouseDown: e => {
e.stopPropagation(); // prevent click through, closing when it should not
},
slotProps: {
paper: {
id: 'njs-action-toolbar-popover',
'data-testid': 'njs-action-toolbar-popover',
className: ActionToolbarElement.className,
style: {
pointerEvents: 'auto',
padding: theme.spacing(0.5, 0.25)
}
}
}
}, Actions) : show && Actions;
}
const search = props => _objectSpread2(_objectSpread2({}, props), {}, {
shapes: [{
type: 'path',
attrs: {
d: 'M8.588 11.415a6 6 0 1 1 2.828-2.829l4.101 4a1.5 1.5 0 0 1 .014 2.134l-.707.707a1.5 1.5 0 0 1-2.108.014l-4.128-4.026ZM11 6A5 5 0 1 0 1 6a5 5 0 0 0 10 0Zm-1.52 4.888 3.934 3.837a.5.5 0 0 0 .703-.005l.707-.707a.5.5 0 0 0-.005-.711l-3.926-3.829a6.034 6.034 0 0 1-1.413 1.415Z'
}
}]
});
var SearchIcon = props => SvgIcon(search(props));
const MAX_SEARCH_LENGTH = 64000;
const TREE_PATH = '/qListObjectDef';
const WILDCARD = '**';
const limitSearchLength = val => val === null || val === void 0 ? void 0 : val.substring(0, MAX_SEARCH_LENGTH);
const StyledOutlinedInput = styled(OutlinedInput, {
shouldForwardProp: p => !['styles', 'dense', 'isRtl'].includes(p)
})(_ref => {
let {
styles,
dense,
isRtl
} = _ref;
let denseProps = {};
if (dense) {
denseProps = {
fontSize: 12,
'& input': {
paddingTop: '5px',
paddingBottom: '5px',
color: styles.search.color,
textAlign: isRtl ? 'right' : 'left'
}
};
}
return _objectSpread2({
display: 'flex',
border: 'none',
fontSize: 14,
borderRadius: 0,
backgroundColor: styles.search.backgroundColor,
backdropFilter: styles.background.backgroundImage ? styles.search.backdropFilter : undefined,
paddingLeft: 0,
paddingRight: 0,
flexDirection: isRtl ? 'row-reverse' : 'row',
'& fieldset': {
borderColor: "".concat(styles.search.borderColor),
borderWidth: '1px 0 1px 0',
borderRadius: 0
},
'&.Mui-focused fieldset': {
borderColor: "".concat(styles.search.highlightBorderColor, " !important")
},
'& .MuiInputBase-root': _objectSpread2({}, styles.search),
'& *': {
color: styles.search.color
},
'& input': {
color: styles.search.color,
textAlign: isRtl ? 'right' : 'left'
}
}, denseProps);
});
const StyledIconButton = styled(IconButton)(() => ({
border: 0,
padding: '8px',
cursor: 'pointer',
lineHeight: '12px',
'&:hover': {
backgroundColor: 'transparent'
},
':focus-visible': {
borderRadius: '4px',
boxShadow: 'inset 0 0 0 2px rgb(2, 117, 217)'
}
}));
function ListBoxSearch(_ref2, ref) {
let {
popoverOpen,
selections,
selectionState,
model,
keyboard,
dense = false,
visible = true,
autoFocus = true,
beginSelectionOnFocus = true,
wildCardSearch = false,
searchEnabled,
direction,
hide,
styles
} = _ref2;
const {
translator
} = reactExports.useContext(InstanceContext);
const [value, setValue] = reactExports.useState('');
const [wildcardOn, setWildcardOn] = reactExports.useState(false);
const inputRef = reactExports.useRef();
const clearSearchRef = reactExports.useRef();
const clearSearchText = translator.get('Listbox.Clear.Search');
const {
getStoreValue,
setStoreValue
} = useDataStore(model);
const isRtl = direction === 'rtl';
const cancel = () => selections.cancel();
const abortSearch = async () => {
try {
await model.abortListObjectSearch(TREE_PATH);
} finally {
setValue('');
}
};
reactExports.useEffect(() => {
if (visible) {
return () => abortSearch(); // abort when toggling off search
}
return () => {};
}, [visible]);
reactExports.useEffect(() => {
selections.on('deactivated', abortSearch);
return () => {
selections.removeListener && selections.removeListener('deactivated', abortSearch);
};
}, []);
reactExports.useEffect(() => {
if (wildcardOn && inputRef.current) {
const cursorPos = value.length - 1;
inputRef.current.setSelectionRange(cursorPos, cursorPos); // place the cursor in the wildcard
setWildcardOn(false);
}
}, [wildcardOn, inputRef.current]);
reactExports.useEffect(() => {
setStoreValue('inputText', value);
}, [value]);
const onChange = async e => {
const searchValue = limitSearchLength(e.target.value);
setValue(searchValue);
if (!searchValue.length) {
return abortSearch();
}
return model.searchListObjectFor(TREE_PATH, searchValue);
};
const beginSelection = () => {
const shouldBeginSelection = !selectionState.selectDisabled() && !selections.isModal();
if (shouldBeginSelection) {
selections.begin('/qListObjectDef');
}
};
const handleFocus = () => {
if (wildCardSearch) {
setValue(WILDCARD);
setWildcardOn(true);
}
if (beginSelectionOnFocus) {
beginSelection();
}
};
const hasHits = () => {
const listCount = getStoreValue("listCount");
return listCount > 0;
};
const performSearch = async () => {
let response;
const searchValue = limitSearchLength(value);
const success = await model.searchListObjectFor(TREE_PATH, searchValue);
if (selectionState.selectDisabled()) {
return success;
}
if (success && searchValue.length && hasHits()) {
response = model.acceptListObjectSearch(TREE_PATH, true);
// eslint-disable-next-line no-param-reassign
selections.selectionsMade = true;
selectionState.clearItemStates(false);
setValue('');
}
return response;
};
const onKeyDown = async e => {
const {
currentTarget
} = e;
const container = currentTarget.closest('.listbox-container');
switch (e.key) {
case 'Enter':
performSearch();
break;
case 'Escape':
{
focusRow(container);
cancel();
if (popoverOpen) {
return undefined;
}
break;
}
case 'Tab':
{
if (e.shiftKey) {
if (!focusCyclicButton(container)) {
keyboard.focusSelection();
}
} else if (clearSearchRef.current) {
clearSearchRef.current.focus();
} else {
// Focus the row we last visited or the first one.
focusRow(container);
}
break;
}
case 'f':
case 'F':
if (e.ctrlKey || e.metaKey) {
if (hide) {
hide();
// Focus the row we last visited or the first one.
focusRow(container);
}
} else {
return undefined;
}
break;
default:
return undefined;
}
e.preventDefault();
e.stopPropagation();
return undefined;
};
const focusOnInput = () => {
var _inputRef$current;
(_inputRef$current = inputRef.current) === null || _inputRef$current === void 0 || _inputRef$current.focus();
};
const onClearSearch = () => {
abortSearch();
focusOnInput();
};
const onKeyDownClearSearch = e => {
const container = e.currentTarget.closest('.listbox-container');
switch (e.key) {
case 'Enter':
onClearSearch();
break;
case 'Tab':
{
if (e.shiftKey) {
focusOnInput();
} else {
// Focus the row we last visited or the first one.
focusRow(container);
}
break;
}
default:
return undefined;
}
e.preventDefault();
e.stopPropagation();
return undefined;
};
reactExports.useImperativeHandle(ref, () => ({
focus() {
focusOnInput();
}
}));
if (!visible || searchEnabled === false) {
return null;
}
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(StyledOutlinedInput, {
styles: styles,
dense: dense,
isRtl: isRtl,
startAdornment: /*#__PURE__*/React.createElement(InputAdornment, {
position: "start",
sx: {
marginLeft: dense ? '8px' : "".concat(CELL_PADDING_LEFT, "px")
}
}, /*#__PURE__*/React.createElement(SearchIcon, {
size: dense ? 'small' : 'normal'
})),
endAdornment: /*#__PURE__*/React.createElement(InputAdornment, {
position: "end",
sx: {
marginLeft: 0
}
}, value !== '' && /*#__PURE__*/React.createElement(StyledIconButton, {
tabIndex: 0,
ref: clearSearchRef,
title: clearSearchText,
"aria-label": clearSearchText,
onClick: onClearSearch,
onKeyDown: onKeyDownClearSearch
}, /*#__PURE__*/React.createElement(Close, {
size: dense ? 'small' : 'normal'
}))),
className: "search",
inputRef: inputRef,
size: "small",
fullWidth: true,
placeholder: translator.get('Listbox.Search'),
value: value,
onFocus: handleFocus,
onChange: onChange,
onKeyDown: onKeyDown,
autoFocus: autoFocus,
inputProps: {
tabIndex: keyboard.innerTabStops ? 0 : -1,
'data-testid': 'search-input-field',
'aria-label': translator.get('Listbox.Search'),
'aria-describedby': 'listbox-search-instructions'
}
}), /*#__PURE__*/React.createElement("span", {
id: "listbox-search-instructions",
style: {
position: 'absolute',
height: 0,
width: 0,
overflow: 'hidden'
}
}, translator.get('Listbox.Search.ScreenReaderInstructions')));
}
var ListBoxSearch$1 = reactExports.forwardRef(ListBoxSearch);
/* eslint no-underscore-dangle: 0 */
function createAppSelections(_ref) {
let {
app,
selectionStore
} = _ref;
const key = "".concat(app.id);
const {
modalObjectStore,
appModalStore
} = selectionStore;
const end = async function () {
let accept = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
const {
model,
objectSelections
} = modalObjectStore.get(key) || {};
if (model) {
await model.endSelections(accept);
modalObjectStore.clear(key);
objectSelections.emit('deactivated');
}
};
const begin = async _ref2 => {
var _modalObjectStore$get;
let {
model,
paths,
accept = true,
objectSelections
} = _ref2;
// Quick return if it's already in modal
if (objectSelections === ((_modalObjectStore$get = modalObjectStore.get(key)) === null || _modalObjectStore$get === void 0 ? void 0 : _modalObjectStore$get.objectSelections)) {
return;
}
// If other model is in modal state end it
end(accept);
// Pending modal
modalObjectStore.set(key, {
model,
objectSelections
});
const p = Array.isArray(paths) ? paths : [paths];
const beginSelections = async skipRetry => {
try {
await model.beginSelections(p);
modalObjectStore.set(key, {
model,
objectSelections
}); // 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(objectSelections) {
var _modalObjectStore$get2;
// TODO check model state
return objectSelections ? ((_modalObjectStore$get2 = modalObjectStore.get(key)) === null || _modalObjectStore$get2 === void 0 ? void 0 : _modalObjectStore$get2.objectSelections) === objectSelections : !!modalObjectStore.get(key);
},
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 {
selectionStore
} = reactExports.useContext(InstanceContext);
const [appSelectionsStore] = selectionStore.useAppSelectionsStore();
const key = app ? app.id : null;
let appSelections = appSelectionsStore.get(key);
reactExports.useEffect(() => {
if (!app || appSelections) return;
appSelections = createAppSelections({
app,
selectionStore
});
appSelectionsStore.set(key, appSelections);
appSelectionsStore.dispatch(true);
}, [app]);
return [appSelections];
}
function eventmixin (obj) {
/* eslint no-param-reassign: 0 */
Object.keys(EventEmitter.prototype).forEach(key => {
obj[key] = EventEmitter.prototype[key];
});
EventEmitter.init(obj);
return obj;
}
/* eslint no-underscore-dangle: 0 */
const event = () => {
let prevented = false;
return {
isPrevented: () => prevented,
preventDefault: () => {
prevented = true;
}
};
};
function createHandler(_ref) {
let {
elements,
handleClickOutside
} = _ref;
const handler = evt => {
const targetStillExists = document.contains(evt.target);
if (!targetStillExists) {
return;
}
// Resolve elements and filter out containers which do not exist.
const containers = elements.map(item => {
const elm = typeof item === 'string' ? document.querySelector(item) : item === null || item === void 0 ? void 0 : item.current;
return elm;
}).filter(elm => !!elm && !!document.contains(elm));
if (!containers.length) {
return;
}
const isWithinSomeContainer = containers.some(elm => elm.contains(evt.target));
const isClickOutside = !isWithinSomeContainer;
if (isClickOutside) {
handleClickOutside(evt);
}
};
return handler;
}
const createObjectSelections = _ref2 => {
let {
appSelections,
appModal,
model
} = _ref2;
let layout;
let isActive = false;
let hasSelected = false;
/**
* Event listener function on instance
*
* @method
* @name ObjectSelections#addListener
* @param {string} eventType event type that function needs to listen
* @param {Function} callback a callback function to run when event emits
* @example
* api.addListener('someEvent', () => {...});
*/
/**
* Remove listener function on instance
*
* @method
* @name ObjectSelections#removeListener
* @param {string} eventType event type that function needs to listen
* @param {Function} callback a callback function to run when event emits
* @example
* api.removeListener('someEvent', () => {...});
*/
/**
* @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,
accept: true,
objectSelections: api
});
},
/**
* @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(api),
/**
* @param {string[]} paths
* @returns {Promise<undefined>}
*/
goModal: paths => appModal.begin({
model,
paths,
accept: false,
objectSelections: api
}),
/**
* @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;
};
const getClickOutFuncs = _ref3 => {
let {
elements,
objectSelections,
options = {}
} = _ref3;
const handler = createHandler({
elements,
handleClickOutside: () => objectSelections.confirm.call(objectSelections)
});
return {
activateClickOut() {
var _options$onSelectionA;
document.addEventListener('mousedown', handler);
options === null || options === void 0 || (_options$onSelectionA = options.onSelectionActivated) === null || _options$onSelectionA === void 0 || _options$onSelectionA.call(options);
},
deactivateClickOut() {
var _options$onSelectionD;
document.removeEventListener('mousedown', handler);
options === null || options === void 0 || (_options$onSelectionD = options.onSelectionDeactivated) === null || _options$onSelectionD === void 0 || _options$onSelectionD.call(options);
}
};
};
function useObjectSelections(app, model, elements, options) {
const elementsArr = Array.isArray(elements) ? elements : [elements];
const [appSelections] = useAppSelections(app);
const [layout] = useLayout$1(model);
const {
appModalStore
} = reactExports.useContext(InstanceContext).selectionStore;
const appModal = appModalStore.get(app.id);
const [objectSelections, setObjectSelections] = reactExports.useState();
reactExports.useEffect(() => {
if (!appSelections || !model || objectSelections) return;
setObjectSelections(createObjectSelections({
appSelections,
appModal,
model
}));
}, [appSelections, model]);
reactExports.useEffect(() => {
if (!objectSelections) return () => {};
const {
activateClickOut,
deactivateClickOut
} = getClickOutFuncs({
elements: elementsArr,
objectSelections,
options
});
objectSelections.addListener('activated', activateClickOut);
objectSelections.addListener('deactivated', deactivateClickOut);
return () => {
// confirm selection before removing event handler
// to end the selection when the object is removed
// and remove the (ClickOut) mousedown handler from the document
if (objectSelections.isActive()) {
objectSelections.confirm();
}
objectSelections.removeListener('activated', activateClickOut);
objectSelections.removeListener('deactivated', deactivateClickOut);
};
}, [objectSelections]);
reactExports.useEffect(() => {
if (!objectSelections) return;
objectSelections.setLayout(layout);
}, [objectSelections, layout]);
return [objectSelections];
}
function selectionState() {
let initialState = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const state = _objectSpread2(_objectSpread2({
itemStates: {},
ignoreSelectionState: false,
selectedInEngine: [],
enginePages: [],
setPages: undefined,
lastRowCount: undefined,
lastApprMaxGlyphCount: undefined,
selectDisabled: undefined
}, initialState), {}, {
update(_ref) {
var _layout$qListObject$q, _layout$qListObject;
let {
setPages,
pages,
isSingleSelect,
selectDisabled,
layout
} = _ref;
this.setPages = setPages;
const isSameRowCount = this.lastRowCount === layout.qListObject.qSize.qcy;
const isSameMaxGlyphCnt = this.lastApprMaxGlyphCount === layout.qListObject.qDimensionInfo.qApprMaxGlyphCount;
if (!isSameRowCount || !isSameMaxGlyphCnt) {
this.lastRowCount = layout.qListObject.qSize.qcy;
this.lastApprMaxGlyphCount = layout.qListObject.qDimensionInfo.qApprMaxGlyphCount;
// The field have probably changed (drill up/down)
// need to clear the client side item states since the field values have changed
this.clearItemStates(false);
}
if (state.enginePages !== pages && pages !== undefined) {
state.enginePages = pages !== null && pages !== void 0 ? pages : [];
state.selectedInEngine = getSelectedValues(pages);
state.selectableValuesUpdating = false;
state.triggerStateChanged();
}
state.isSingleSelect = isSingleSelect;
state.selectDisabled = selectDisabled || state.selectDisabled;
state.isDimCalculated = (_layout$qListObject$q = layout === null || layout === void 0 || (_layout$qListObject = layout.qListObject) === null || _layout$qListObject === void 0 || (_layout$qListObject = _layout$qListObject.qDimensionInfo) === null || _layout$qListObject === void 0 ? void 0 : _layout$qListObject.qIsCalculated) !== null && _layout$qListObject$q !== void 0 ? _layout$qListObject$q : false;
},
allowedToSelect() {
if (state.selectDisabled()) {
return false;
}
// When a dim is calculated, the rows must be done updating after previeous selection
return !(state.isDimCalculated && state.selectableValuesUpdating);
},
setSelectableValuesUpdating() {
state.selectableValuesUpdating = true;
},
useClientItemState(elementNumber) {
return state.ignoreSelectionState || elementNumber in state.itemStates;
},
isSelected(elementNumber) {
if (state.useClientItemState(elementNumber)) {
return !!state.itemStates[elementNumber];
}
return state.selectedInEngine.includes(elementNumber);
},
getState(item) {
const {
qElemNumber,
qState
} = item;
if (!state.useClientItemState(qElemNumber)) {
return qState;
}
if (state.itemStates[qElemNumber]) {
return qState === 'XS' ? 'XS' : 'S';
}
return qState === 'S' || qState === 'XS' ? 'A' : qState;
},
updateItemNoEvents(elementNumber, additive, selectedValues) {
const selected = state.isSelected(elementNumber);
if (selected && !additive) {
state.itemStates[elementNumber] = false;
} else if (!selected) {
selectedValues === null || selectedValues === void 0 || selectedValues.push(elementNumber);
state.itemStates[elementNumber] = true;
}
},
triggerStateChanged() {
if (this.setPages) {
const pages = state.applySelectionsOnPages(state.enginePages);
this.setPages(pages);
}
},
applySelectionsOnPages(pages) {
const matrices = pages.map(page => {
const qMatrix = page.qMatrix.map(p => {
const [p0] = p;
const qState = state.getState(p0);
return [_objectSpread2(_objectSpread2({}, p0), {}, {
qState
}), ...p.slice(1)];
});
return _objectSpread2(_objectSpread2({}, page), {}, {
qMatrix
});
});
return matrices;
},
updateItem(elementNumber, additive, selectedValues) {
state.updateItemNoEvents(elementNumber, additive, selectedValues);
state.triggerStateChanged();
},
updateItems(elementNumbers, additive, selectedValues) {
elementNumbers.forEach(elementNumber => {
state.updateItemNoEvents(elementNumber, additive, selectedValues);
});
state.triggerStateChanged();
},
clearItemStates(ignoreSelectionState) {
state.itemStates = {};
state.ignoreSelectionState = ignoreSelectionState;
}
});
return state;
}
const getValue$1 = function (obj, prop) {
var _obj$prop;
let defaultValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
return (_obj$prop = obj === null || obj === void 0 ? void 0 : obj[prop]) !== null && _obj$prop !== void 0 ? _obj$prop : defaultValue;
};
function hasSelections(layout) {
const counts = (layout === null || layout === void 0 ? void 0 : layout.qListObject.qDimensionInfo.qStateCounts) || {};
const totalCounts = getValue$1(counts, 'qSelected', 0) + getValue$1(counts, 'qSelectedExcluded', 0) + getValue$1(counts, 'qLocked', 0) + getValue$1(counts, 'qLockedExcluded', 0);
return totalCounts > 0;
}
/*
* qlik-chart-modules v0.99.3
* Copyright (c) 2025 QlikTech International AB
* Released under the MIT license.
*/
function e(e){return null!==e&&"object"==typeof e&&"r"in e&&"number"==typeof e.r&&"g"in e&&"number"==typeof e.g&&"b"in e&&"number"==typeof e.b&&("number"==typeof e.a||void 0===e.a)}function t(t){if("object"==typeof t&&e(t))return (t.r<<16)+(t.g<<8)+t.b;let n=0,r=0,i=0;if("string"==typeof t){let e;(e=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i.exec(t))?(n=parseInt(e[1],10),r=parseInt(e[2],10),i=parseInt(e[3],10)):(e=/^#([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})$/i.exec(t))?(n=parseInt(e[1],16),r=parseInt(e[2],16),i=parseInt(e[3],16)):(e=/^#([A-Fa-f0-9])([A-Fa-f0-9])([A-Fa-f0-9])$/i.exec(t))&&(n=parseInt(e[1]+e[1],16),r=parseInt(e[2]+e[2],16),i=parseInt(e[3]+e[3],16));}return (n<<16)+(r<<8)+i}const n={aliceblue:{r:240,g:248,b:255},antiquewhite:{r:250,g:235,b:215},aqua:{r:0,g:255,b:255},aquamarine:{r:127,g:255,b:212},azure:{r:240,g:255,b:255},beige:{r:245,g:245,b:220},bisque:{r:255,g:228,b:196},black:{r:0,g:0,b:0},blanchedalmond:{r:255,g:235,b:205},blue:{r:0,g:0,b:255},blueviolet:{r:138,g:43,b:226},brown:{r:165,g:42,b:42},burlywood:{r:222,g:184,b:135},cadetblue:{r:95,g:158,b:160},chartreuse:{r:127,g:255,b:0},chocolate:{r:210,g:105,b:30},coral:{r:255,g:127,b:80},cornflowerblue:{r:100,g:149,b:237},cornsilk:{r:255,g:248,b:220},crimson:{r:220,g:20,b:60},cyan:{r:0,g:255,b:255},darkblue:{r:0,g:0,b:139},darkcyan:{r:0,g:139,b:139},darkgoldenrod:{r:184,g:134,b:11},darkgray:{r:169,g:169,b:169},darkgreen:{r:0,g:100,b:0},darkgrey:{r:169,g:169,b:169},darkkhaki:{r:189,g:183,b:107},darkmagenta:{r:139,g:0,b:139},darkolivegreen:{r:85,g:107,b:47},darkorange:{r:255,g:140,b:0},darkorchid:{r:153,g:50,b:204},darkred:{r:139,g:0,b:0},darksalmon:{r:233,g:150,b:122},darkseagreen:{r:143,g:188,b:143},darkslateblue:{r:72,g:61,b:139},darkslategray:{r:47,g:79,b:79},darkslategrey:{r:47,g:79,b:79},darkturquoise:{r:0,g:206,b:209},darkviolet:{r:148,g:0,b:211},deeppink:{r:255,g:20,b:147},deepskyblue:{r:0,g:191,b:255},dimgray:{r:105,g:105,b:105},dimgrey:{r:105,g:105,b:105},dodgerblue:{r:30,g:144,b:255},firebrick:{r:178,g:34,b:34},floralwhite:{r:255,g:250,b:240},forestgreen:{r:34,g:139,b:34},fuchsia:{r:255,g:0,b:255},gainsboro:{r:220,g:220,b:220},ghostwhite:{r:248,g:248,b:255},gold:{r:255,g:215,b:0},goldenrod:{r:218,g:165,b:32},gray:{r:128,g:128,b:128},green:{r:0,g:128,b:0},greenyellow:{r:173,g:255,b:47},grey:{r:128,g:128,b:128},honeydew:{r:240,g:255,b:240},hotpink:{r:255,g:105,b:180},indianred:{r:205,g:92,b:92},indigo:{r:75,g:0,b:130},ivory:{r:255,g:255,b:240},khaki:{r:240,g:230,b:140},lavender:{r:230,g:230,b:250},lavenderblush:{r:255,g:240,b:245},lawngreen:{r:124,g:252,b:0},lemonchiffon:{r:255,g:250,b:205},lightblue:{r:173,g:216,b:230},lightcoral:{r:240,g:128,b:128},lightcyan:{r:224,g:255,b:255},lightgoldenrodyellow:{r:250,g:250,b:210},lightgray:{r:211,g:211,b:211},lightgreen:{r:144,g:238,b:144},lightgrey:{r:211,g:211,b:211},lightpink:{r:255,g:182,b:193},lightsalmon:{r:255,g:160,b:122},lightseagreen:{r:32,g:178,b:170},lightskyblue:{r:135,g:206,b:250},lightslategray:{r:119,g:136,b:153},lightslategrey:{r:119,g:136,b:153},lightsteelblue:{r:176,g:196,b:222},lightyellow:{r:255,g:255,b:224},lime:{r:0,g:255,b:0},limegreen:{r:50,g:205,b:50},linen:{r:250,g:240,b:230},magenta:{r:255,g:0,b:255},maroon:{r:128,g:0,b:0},mediumaquamarine:{r:102,g:205,b:170},mediumblue:{r:0,g:0,b:205},mediumorchid:{r:186,g:85,b:211},mediumpurple:{r:147,g:112,b:219},mediumseagreen:{r:60,g:179,b:113},mediumslateblue:{r:123,g:104,b:238},mediumspringgreen:{r:0,g:250,b:154},mediumturquoise:{r:72,g:209,b:204},mediumvioletred:{r:199,g:21,b:133},midnightblue:{r:25,g:25,b:112},mintcream:{r:245,g:255,b:250},mistyrose:{r:255,g:228,b:225},moccasin:{r:255,g:228,b:181},navajowhite:{r:255,g:222,b:173},navy:{r:0,g:0,b:128},oldlace:{r:253,g:245,b:230},olive:{r:128,g:128,b:0},olivedrab:{r:107,g:142,b:35},orange:{r:255,g:165,b:0},orangered:{r:255,g:69,b:0},orchid:{r:218,g:112,b:214},palegoldenrod:{r:238,g:232,b:170},palegreen:{r:152,g:251,b:152},paleturquoise:{r:175,g:238,b:238},palevioletred:{r:219,g:112,b:147},papayawhip:{r:255,g:239,b:213},peachpuff:{r:255,g:218,b:185},peru:{r:205,g:133,b:63},pink:{r:255,g:192,b:203},plum:{r:221,g:160,b:221},powderblue:{r:176,g:224,b:230},purple:{r:128,g:0,b:128},red:{r:255,g:0,b:0},rosybrown:{r:188,g:143,b:143},royalblue:{r:65,g:105,b:225},saddlebrown:{r:139,g:69,b:19},salmon:{r:250,g:128,b:114},sandybrown:{r:244,g:164,b:96},seagreen:{r:46,g:139,b:87},seashell:{r:255,g:245,b:238},sienna:{r:160,g:82,b:45},silver:{r:192,g:192,b:192},skyblue:{r:135,g:206,b:235},slateblue:{r:106,g:90,b:205},slategray:{r:112,g:128,b:144},slategrey:{r:112,g:128,b:144},snow:{r:255,g:250,b:250},springgreen:{r:0,g:255,b:127},steelblue:{r:70,g:130,b:180},tan:{r:210,g:180,b:140},teal:{r:0,g:128,b:128},thistle:{r:216,g:191,b:216},tomato:{r:255,g:99,b:71},transparent:{r:0,g:0,b:0,a:0},turquoise:{r:64,g:224,b:208},violet:{r:238,g:130,b:238},wheat:{r:245,g:222,b:179},white:{r:255,g:255,b:255},whitesmoke:{r:245,g:245,b:245},yellow:{r:255,g:255,b:0},yellowgreen:{r:154,g:205,b:50}};function r(...t){const r={type:"qcm-color",r:0,g:0,b:0,a:1,invalid:false,spaces:{}};let i=0,o=0,a=0,l=1;if(null!==(s=t[0])&&"object"==typeof s&&"type"in s&&"qcm-color"===s.type)(({r:i,g:o,b:a,a:l}=t[0])),r.invalid=t[0].invalid,r.spaces={...t[0].spaces};else if(e(t[0]))(({r:i,g:o,b:a}=t[0])),"a"in t[0]&&({a:l}=t[0]);else if(t.length<3)if("string"==typeof t[0]){const e=t[0];let s;if(s=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i.exec(e))i=parseInt(s[1],10),o=parseInt(s[2],10),a=parseInt(s[3],10);else if(s=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d(\.\d+)?)\s*\)$/i.exec(e))i=parseInt(s[1],10),o=parseInt(s[2],10),a=parseInt(s[3],10),l=parseFloat(s[4]);else if(s=/^ARGB\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i.exec(e))l=parseInt(s[1],10)/255,i=parseInt(s[2],10),o=parseInt(s[3],10),a=parseInt(s[4],10);else if(s=/^#([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})$/i.exec(e))i=parseInt(s[1],16),o=parseInt(s[2],16),a=parseInt(s[3],16),l=1;else if(s=/^#([A-Fa-f0-9])([A-Fa-f0-9])([A-Fa-f0-9])$/i.exec(e))i=parseInt(s[1]+s[1],16),o=parseInt(s[2]+s[2],16),a=parseInt(s[3]+s[3],16),l=1;else if(s=/^hsl\(\s*(\d+(\.\d+)?)\s*,\s*(\d+(\.\d+)?%?)\s*,\s*(\d+(\.\d+)?%?)\s*\)$/i.exec(e)){let e=parseFloat(s[1]),t=parseFloat(s[3]),n=parseFloat(s[5]);e%=360,t/=100,n/=100,e=e<0?0:e>360?360:e,t=t<0?0:t>1?1:t,n=n<0?0:n>1?1:n;const r=n<=.5?2*n*t:(2-2*n)*t;let c=e/60;const u=r*(1-Math.abs(c%2-1));let f=[];switch(c=Math.floor(c),c){case 0:f=[r,u,0];break;case 1:f=[u,r,0];break;case 2:f=[0,r,u];break;case 3:f=[0,u,r];break;case 4:f=[u,0,r];break;case 5:f=[r,0,u];break;default:f=[0,0,0];}const d=n-.5*r;i=f[0]+d,o=f[1]+d,a=f[2]+d,i=Math.round(255*i),o=Math.round(255*o),a=Math.round(255*a),l=1;}else if(s=/^hsla\(\s*(\d+(\.\d+)?)\s*,\s*(\d+(\.\d+)?%?)\s*,\s*(\d+(\.\d+)?%?)\s*,\s*(\d(\.\d+)?)\s*\)$/i.exec(e)){let e=parseFloat(s[1]),t=parseFloat(s[3]),n=parseFloat(s[5]);l=parseFloat(s[7]),e%=360,t/=100,n/=100,e=e<0?0:e>360?360:e,t=t<0?0:t>1?1:t,n=n<0?0:n>1?1:n;const r=n<=.5?2*n*t:(2-2*n)*t;let c=e/60;const u=r*(1-Math.abs(c%2-1));let f=[];switch(c=Math.floor(c),c){case 0:f=[r,u,0];break;case 1:f=[u,r,0];break;case 2:f=[0,r,u];break;case 3:f=[0,u,r];break;case 4:f=[u,0,r];break;case 5:f=[r,0,u];break;default:f=[0,0,0];}const d=n-.5*r;i=f[0]+d,o=f[1]+d,a=f[2]+d,i=Math.round(255*i),o=Math.round(255*o),a=Math.round(255*a);}else if(s=/^hsv\(\s*(\d+(\.\d+)?)\s*,\s*(\d+(\.\d+)?%?)\s*,\s*(\d+(\.\d+)?%?)\s*\)$/i.exec(e)){let e=parseFloat(s[1]),t=parseFloat(s[3]),n=parseFloat(s[5]);e%=360,t/=100,n/=100,e=e<0?0:e>360?360:e,t=t<0?0:t>1?1:t,n=n<0?0:n>1?1:n;const r=n*t;let c=e/60;const u=r*(1-Math.abs(c%2-1));let f=[];switch(c=Math.floor(c),c){case 0:f=[r,u,0];break;case 1:f=[u,r,0];break;case 2:f=[0,r,u];break;case 3:f=[0,u,r];break;case 4:f=[u,0,r];break;case 5:f=[r,0,u];break;default:f=[0,0,0];}const d=n-r;i=f[0]+d,o=f[1]+d,a=f[2]+d,i=Math.round(255*i),o=Math.round(255*o),a=Math.round(255*a),l=1;}else {const t=e.toLowerCase();if(function(e){return e in n}(t)){const e=n[t];(({r:i,g:o,b:a}=e)),l="a"in e?e.a:1;}else r.invalid=true;}}else "number"==typeof t[0]&&t[0]>=0&&"argb"===t[1]?(l=(4278190080&t[0])>>>24,l/=255,i=(16711680&t[0])>>16,o=(65280&t[0])>>8,a=255&t[0]):"number"==typeof t[0]&&t[0]>=0?(i=(16711680&t[0])>>16,o=(65280&t[0])>>8,a=255&t[0]):r.invalid=true;else 3===t.length||4===t.length?(i=t[0],o=t[1],a=t[2],l=4===t.length?t[3]:1):r.invalid=true;var s;return Number.isNaN(+i+o+a+l)&&(r.invalid=true),r.r=Math.floor(i),r.g=Math.floor(o),r.b=Math.floor(a),r.a=l,r}function i(n){let r,i,o;if(e(n))return r=n.r.toString(16),i=n.g.toString(16),o=n.b.toString(16),1===r.length&&(r=`0${r}`),1===i.length&&(i=`0${i}`),1===o.length&&(o=`0${o}`),`#${[r,i,o].join("")}`;const a="string"==typeof n?t(n):n;return r=((16711680&a)>>16).toString(16),i=((65280&a)>>8).toString(16),o=(255&a).toString(16),1===r.length&&(r=`0${r}`),1===i.length&&(i=`0${i}`),1===o.length&&(o=`0${o}`),`#${r}${i}${o}`}function o(e){let t,n,i=0;const o="string"==typeof e?r(e):e,a=o.r/255,l=o.g/255,s=o.b/255,c=Math.max(a,l,s),u=Math.min(a,l,s),f=(c+u)/2;if(c===u)t=0,i=0;else {switch(n=c-u,t=f>.5?n/(2-c-u):n/(c+u),c){case a:i=(l-s)/n+(l<s?6:0);break;case l:i=(s-a)/n+2;break;case s:i=(a-l)/n+4;}i/=6;}return `hsl(${360*i}, ${100*t}, ${100*f})`}function a(e){let t,n,i=0;const o="string"==typeof e?r(e):e,a=o.r/255,l=o.g/255,s=o.b/255,{a:c}=o,u=Math.max(a,l,s),f=Math.min(a,l,s),d=(u+f)/2;if(u===f)t=0,i=0;else {switch(n=u-f,t=d>.5?n/(2-u-f):n/(u+f),u){case a:i=(l-s)/n+(l<s?6:0);break;case l:i=(s-a)/n+2;break;case s:i=(a-l)/n+4;}i/=6;}return {h:360*i,s:100*t,l:100*d,a:c}}function l(e){const{h:t,s:n,l:r,a:i}=a(e);return `hsla(${t}, ${n}, ${r}, ${i})`}function s(e){let t,n,i=0;const o="string"==typeof e?r(e):e,a=o.r/255,l=o.g/255,s=o.b/255,c=Math.max(a,l,s),u=Math.min(a,l,s),f=c;if(c===u)t=0,i=0;else {switch(n=c-u,t=0===n?0:n/f,c){case a:i=(l-s)/n+(l<s?6:0);break;case l:i=(s-a)/n+2;break;case s:i=(a-l)/n+4;}i/=6;}return {h:360*i%360,s:100*t,v:100*f}}function c(e){const{h:t,s:n,v:r}=s(e);return `hsv(${t}, ${n}, ${r})`}function u(n){if(e(n))return `rgb(${n.r}, ${n.g}, ${n.b})`;const r="string"==typeof n?t(n):n;return `rgb(${(16711680&r)>>16}, ${(65280&r)>>8}, ${255&r})`}function f(t,n){return e(t)?`rgba(${t.r}, ${t.g}, ${t.b}, ${t.a})`:f(r(t))}function d(t){return e(t)?1===t.a?u(t):f(t):d(r(t))}const p=e=>{const t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4};function h(e){return .2126*p(e.r)+.7152*p(e.g)+.0722*p(e.b)}function m(...e){const t=r(...e);return t.invalid||h(t)<.4}function g(...e){const t=r(...e),n={type:t.type,r:t.r,g:t.g,b:t.b,a:t.a,invalid:t.invalid,spaces:t.spaces},p=()=>(n.spaces.hslaObject||(n.spaces.hslaObject=a(n)),n.spaces.hslaObject),h=e=>{const t=p(),{h:n,s:r,l:i,a:o}=t;return `hsla(${n}, ${r}, ${Math.max(0,Math.min(i+e,100))}, ${o})`};return {get type(){return n.type},isInvalid:()=>n.invalid,get r(){return n.r},get g(){return n.g},get b(){return n.b},get a(){return n.a},getR:()=>n.r,getG:()=>n.g,getB:()=>n.b,getAlpha:()=>n.a,setAlpha:e=>{n.a=e,n.spaces={};},isEqualTo:e=>{let t;if("string"==typeof e)t=r(e);else {if(e.type!==n.type)return false;t=e;}return t.r===n.r&&t.g===n.g&&t.b===n.b&&t.a===n.a},isDark:()=>m(n),getRGB:()=>(n.spaces.rgb||(n.spaces.rgb=u(n)),n.spaces.rgb),getRGBA:()=>(n.spaces.rgba||(n.spaces.rgba=f(n)),n.spaces.rgba),getString:()=>(n.spaces.string||(n.spaces.string=d(n)),n.spaces.string),getHex:()=>(n.spaces.hex||(n.spaces.hex=i(n)),n.spaces.hex),getHSL:()=>(n.spaces.hsl||(n.spaces.hsl=o(n)),n.spaces.hsl),getHSLA:()=>(n.spaces.hsla||(n.spaces.hsla=l(n)),n.spaces.hsla),getHSLAObject:p,getShiftedHSLA:h,getHSV:()=>(n.spaces.hsv||(n.spaces.hsv=c(n)),n.spaces.hsv),getHSVObject:()=>(n.spaces.hsvObject||(n.spaces.hsvObject=s(n)),n.spaces.hsvObject),blend:(e,t)=>`rgba(${Math.floor(n.r+(e.r-n.r)*t)}, ${Math.floor(n.g+(e.g-n.g)*t)}, ${Math.floor(n.b+(e.b-n.b)*t)}, ${Math.floor(n.a+(e.getAlpha()-n.a)*t)})`,getBrightenedColor:(e=1)=>g(h(18*e)),getDarkenedColor:(e=1)=>g(h(18*-e))}}function v(e,t){if(!e||!t)return;const n=h(e),r=h(t);return n>r?(n+.05)/(r+.05):(r+.05)/(n+.05)}function b(e,t){const n=g("#FFFFFF"),r=g(e),i=g(t);if(r.isInvalid()||i.isInvalid()||r.getAlpha()<1||i.getAlpha()<1)return t;const o=v(n,r),a=v(i,r),l=o>a||o>4.5;return !l&&a>3?i.getHex():l?"#FFFFFF":"#000000"}function M(e,t,n){return (t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return ("string"===t?String:Number)(e)}(e,"string");return "symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:true,configurable:true,writable:true}):e[t]=n,e}var N="unclassified",F="equal-equal",j="equal-higher",z="equal-lower",H="equal-void",B="higher-equal",R="higher-higher-acute",V="higher-higher-obtuse",_="higher-lower-negative",$="higher-lower-positive",K="higher-void",Y="lower-equal",G="lower-higher-negative",U="lower-higher-positive",W="lower-lower-acute",X="lower-lower-obtuse",Z="lower-void",J="void-equal",Q="void-higher",ee="void-lower",te="void-void";var ae={TOP:"top",TOP_RIGHT:"top-right",RIGHT:"right",BOTTOM_RIGHT:"bottom-right",BOTTOM:"bottom",BOTTOM_LEFT:"bottom-left",LEFT:"left",TOP_LEFT:"top-left"};var ce;(M(M(M(M(M(M(M(M(M(M(ce={},F,[ae.TOP,ae.BOTTOM]),j,[ae.BOTTOM,ae.BOTTOM_RIGHT]),z,[ae.TOP,ae.TOP_RIGHT]),H,[ae.TOP,ae.BOTTOM]),B,[ae.LEFT,ae.BOTTOM_LEFT,ae.TOP,ae.TOP_RIGHT]),R,[ae.BOTTOM,ae.BOTTOM_LEFT,ae.LEFT,ae.TOP_RIGHT]),V,[ae.BOTTOM,ae.TOP]),_,[ae.TOP,ae.TOP_RIGHT,ae.RIGHT]),$,[ae.BOTTOM,ae.BOTTOM_LEFT,ae.LEFT]),K,[ae.TOP]),M(M(M(M(M(M(M(M(M(M(ce,Y,[ae.TOP]),G,[ae.TOP,ae.TOP_LEFT]),U,[ae.BOTTOM_RIGHT]),W,[ae.TOP,ae.TOP_LEFT,ae.LEFT,ae.TOP_RIGHT,ae.RIGHT]),X,[ae.TOP,ae.BOTTOM]),Z,[ae.TOP]),J,[ae.TOP]),Q,[ae.TOP,ae.BOTTOM]),ee,[ae.TOP,ae.BOTTOM,ae.LEFT]),te,[ae.TOP]),M(ce,N,[ae.TOP,ae.BOTTOM,ae.RIGHT,ae.LEFT,ae.TOP_RIGHT,ae.BOTTOM_RIGHT,ae.BOTTOM_LEFT,ae.TOP_LEFT]));var Ze,Je;function ft(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var dt=function(){if(Je)return Ze;Je=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=function(e){return "function"==typeof Array.isArray?Array.isArray(e):"[object Array]"===t.call(e)},o=function(n){if(!n||"[object Object]"!==t.call(n))return false;var r,i=e.call(n,"constructor"),o=n.constructor&&n.constructor.prototype&&e.call(n.constructor.prototype,"isPrototypeOf");if(n.constructor&&!i&&!o)return false;for(r in n);return void 0===r||e.call(n,r)},a=function(e,t){n&&"__proto__"===t.name?n(e,t.name,{enumerable:true,configurable:true,value:t.newValue,writable:true}):e[t.name]=t.newValue;},l=function(t,n){if("__proto__"===n){if(!e.call(t,n))return;if(r)return r(t,n).value}return t[n]};return Ze=function e(){var t,n,r,s,c,u,f=arguments[0],d=1,p=arguments.length,h=false;for("boolean"==typeof f&&(h=f,f=arguments[1]||{},d=2),(null==f||"object"!=typeof f&&"function"!=typeof f)&&(f={});d<p;++d)if(null!=(t=arguments[d]))for(n in t)r=l(f,n),f!==(s=l(t,n))&&(h&&s&&(o(s)||(c=i(s)))?(c?(c=false,u=r&&i(r)?r:[]):u=r&&o(r)?r:{},a(f,{name:n,newValue:e(h,u,s)})):void 0!==s&&a(f,{name:n,newValue:s}));return f},Ze}();ft(dt);function bt(e,t,n){e.prototype=t.prototype=n,n.constructor=e;}function xt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function wt(){}var qt=1/.7,kt="\\s*([+-]?\\d+)\\s*",Mt="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Ot="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Ct=/^#([0-9a-f]{3,8})$/,Tt=new RegExp(`^rgb\\(${kt},${kt},${kt}\\)$`),St=new RegExp(`^rgb\\(${Ot},${Ot},${Ot}\\)$`),It=new RegExp(`^rgba\\(${kt},${kt},${kt},${Mt}\\)$`),Dt=new RegExp(`^rgba\\(${Ot},${Ot},${Ot},${Mt}\\)$`),Et=new RegExp(`^hsl\\(${Mt},${Ot},${Ot}\\)$`),At=new RegExp(`^hsla\\(${Mt},${Ot},${Ot},${Mt}\\)$`),Pt={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function Lt(){return this.rgb().formatHex()}function Nt(){return this.rgb().formatRgb()}function Ft(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=Ct.exec(e))?(n=t[1].length,t=parseInt(t[1],16),6===n?jt(t):3===n?new Rt(t>>8&15|t>>4&240,t>>4&15|240&t,(15&t)<<4|15&t,1):8===n?zt(t>>24&255,t>>16&255,t>>8&255,(255&t)/255):4===n?zt(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|240&t,((15&t)<<4|15&t)/255):null):(t=Tt.exec(e))?new Rt(t[1],t[2],t[3],1):(t=St.exec(e))?new Rt(255*t[1]/100,255*t[2]/100,255*t[3]/100,1):(t=It.exec(e))?zt(t[1],t[2],t[3],t[4]):(t=Dt.exec(e))?zt(255*t[1]/100,255*t[2]/100,255*t[3]/100,t[4]):(t=Et.exec(e))?Gt(t[1],t[2]/100,t[3]/100,1):(t=At.exec(e))?Gt(t[1],t[2]/100,t[3]/100,t[4]):Pt.hasOwnProperty(e)?jt(Pt[e]):"transparent"===e?new Rt(NaN,NaN,NaN,0):null}function jt(e){return new Rt(e>>16&255,e>>8&255,255&e,1)}function zt(e,t,n,r){return r<=0&&(e=t=n=NaN),new Rt(e,t,n,r)}function Ht(e){return e instanceof wt||(e=Ft(e)),e?new Rt((e=e.rgb()).r,e.g,e.b,e.opacity):new Rt}function Bt(e,t,n,r){return 1===arguments.length?Ht(e):new Rt(e,t,n,null==r?1:r)}function Rt(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r;}function Vt(){return `#${Yt(this.r)}${Yt(this.g)}${Yt(this.b)}`}function _t(){const e=$t(this.opacity);return `${1===e?"rgb(":"rgba("}${Kt(this.r)}, ${Kt(this.g)}, ${Kt(this.b)}${1===e?")":`, ${e})`}`}function $t(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Kt(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Yt(e){return ((e=Kt(e))<16?"0":"")+e.toString(16)}function Gt(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Wt(e,t,n,r)}function Ut(e){if(e instanceof Wt)return new Wt(e.h,e.s,e.l,e.opacity);if(e instanceof wt||(e=Ft(e)),!e)return new Wt;if(e instanceof Wt)return e;var t=(e=e.rgb()).r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),o=Math.max(t,n,r),a=NaN,l=o-i,s=(o+i)/2;return l?(a=t===o?(n-r)/l+6*(n<r):n===o?(r-t)/l+2:(t-n)/l+4,l/=s<.5?o+i:2-o-i,a*=60):l=s>0&&s<1?0:a,new Wt(a,l,s,e.opacity)}function Wt(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r;}function Xt(e){return (e=(e||0)%360)<0?e+360:e}function Zt(e){return Math.max(0,Math.min(1,e||0))}function Jt(e,t,n){return 255*(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)}bt(wt,Ft,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Lt,formatHex:Lt,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return Ut(this).formatHsl()},formatRgb:Nt,toString:Nt}),bt(Rt,Bt,xt(wt,{brighter(e){return e=null==e?qt:Math.pow(qt,e),new Rt(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=null==e?.7:Math.pow(.7,e),new Rt(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Rt(Kt(this.r),Kt(this.g),Kt(this.b),$t(this.opacity))},displayable(){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:Vt,formatHex:Vt,formatHex8:function(){return `#${Yt(this.r)}${Yt(this.g)}${Yt(this.b)}${Yt(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:_t,toString:_t})),bt(Wt,(function(e,t,n,r){return 1===arguments.length?Ut(e):new Wt(e,t,n,null==r?1:r)}),xt(wt,{brighter(e){return e=null==e?qt:Math.pow(qt,e),new Wt(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=null==e?.7:Math.pow(.7,e),new Wt(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+360*(this.h<0),t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,i=2*n-r;return new Rt(Jt(e>=240?e-240:e+120,i,r),Jt(e,i,r),Jt(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new Wt(Xt(this.h),Zt(this.s),Zt(this.l),$t(this.opacity))},displayable(){return (0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=$t(this.opacity);return `${1===e?"hsl(":"hsla("}${Xt(this.h)}, ${100*Zt(this.s)}%, ${100*Zt(this.l)}%${1===e?")":`, ${e})`}`}}));const Qt=Math.PI/180,en=180/Math.PI,tn=4/29,nn=6/29,rn=3*nn*nn;function on(e){if(e instanceof an)return new an(e.l,e.a,e.b,e.opacity);if(e instanceof pn)return hn(e);e instanceof Rt||(e=Ht(e));var t,n,r=un(e.r),i=un(e.g),o=un(e.b),a=ln((.2225045*r+.7168786*i+.0606169*o)/1);return r===i&&i===o?t=n=a:(t=ln((.4360747*r+.3850649*i+.1430804*o)/.96422),n=ln((.0139322*r+.0971045*i+.7141733*o)/.82521)),new an(116*a-16,500*(t-a),200*(a-n),e.opacity)}function an(e,t,n,r){this.l=+e,this.a=+t,this.b=+n,this.opacity=+r;}function ln(e){return e>.008856451679035631?Math.pow(e,1/3):e/rn+tn}function sn(e){return e>nn?e*e*e:rn*(e-tn)}function cn(e){return 255*(e<=.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055)}function un(e){return (e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function fn(e){if(e instanceof pn)return new pn(e.h,e.c,e.l,e.opacity);if(e instanceof an||(e=on(e)),0===e.a&&0===e.b)return new pn(NaN,0<e.l&&e.l<100?0:NaN,e.l,e.opacity);var t=Math.atan2(e.b,e.a)*en;return new pn(t<0?t+360:t,Math.sqrt(e.a*e.a+e.b*e.b),e.l,e.opacity)}function dn(e,t,n,r){return 1===arguments.length?fn(e):new pn(e,t,n,null==r?1:r)}function pn(e,t,n,r){this.h=+e,this.c=+t,this.l=+n,this.opacity=+r;}function hn(e){if(isNaN(e.h))return new an(e.l,0,0,e.opacity);var t=e.h*Qt;return new an(e.l,Math.cos(t)*e.c,Math.sin(t)*e.c,e.opacity)}bt(an,(function(e,t,n,r){return 1===arguments.length?on(e):new an(e,t,n,null==r?1:r)}),xt(wt,{brighter(e){return new an(this.l+18*(null==e?1:e),this.a,this.b,this.opacity)},darker(e){return new an(this.l-18*(null==e?1:e),this.a,this.b,this.opacity)},rgb(){var e=(this.l+16)/116,t=isNaN(this.a)?e:e+this.a/500,n=isNaN(this.b)?e:e-this.b/200;return new Rt(cn(3.1338561*(t=.96422*sn(t))-1.6168667*(e=1*sn(e))-.4906146*(n=.82521*sn(n))),cn(-0.9787684*t+1.9161415*e+.033454*n),cn(.0719453*t-.2289914*e+1.4052427*n),this.opacity)}})),bt(pn,dn,xt(wt,{brighter(e){return new pn(this.h,this.c,this.l+18*(null==e?1:e),this.opacity)},darker(e){return new pn(this.h,this.c,this.l-18*(null==e?1:e),this.opacity)},rgb(){return hn(this).rgb()}}));var mn=e=>()=>e;function gn(e){return 1==(e=+e)?vn:function(t,n){return n-t?function(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}(t,n,e):mn(isNaN(t)?n:t)}}function vn(e,t){var n=t-e;return n?function(e,t){return function(n){return e+n*t}}(e,n):mn(isNaN(e)?t:e)}(function e(t){var n=gn(t);function r(e,t){var r=n((e=Bt(e)).r,(t=Bt(t)).r),i=n(e.g,t.g),o=n(e.b,t.b),a=vn(e.opacity,t.opacity);return function(t){return e.r=r(t),e.g=i(t),e.b=o(t),e.opacity=a(t),e+""}}return r.gamma=e,r})(1);var tr="center",nr="bottom";[{key:"NoDataExist",alignment:tr,condition:function(e){var t=e.layoutService;if(!t)return false;var n=t.meta.size;return n.x*n.y==0}},{key:"OnlyNanDataMeasure",translationKey:"OnlyNanData",alignment:tr,condition:function(e){var t=e.layoutService;return !!t&&t.getHyperCubeValue("qMeasureInfo").every((function(e){return "NaN"===e.qMin&&"NaN"===e.qMax}))}},{key:"OnlyNanDataDimensionContinuous",translationKey:"OnlyNanData",alignment:tr,condition:function(e){var t=e.layoutService;if(!t)return false;if(!t.meta.isContinuous)return false;var n=t.getHyperCubeValue("qDimensionInfo.0");return n&&(n.qMax<n.qMin||"NaN"===n.qMax)}},{key:"OnlyNegativeOrZeroValues",alignment:tr},{key:"DataRangeIncludingZero",alignment:nr},{key:"LimitedData",alignment:nr},{key:"NegativeOrZeroValues",alignment:nr}].reduce((function(e,t){return e[t.key]=t,e}),{});function Ur(e){var t=0,n=e.children,r=n&&n.length;if(r)for(;--r>=0;)t+=n[r].value;else t=1;e.value=t;}function Wr(e,t){e instanceof Map?(e=[void 0,e],void 0===t&&(t=Zr)):void 0===t&&(t=Xr);for(var n,r,i,o,a,l=new ei(e),s=[l];n=s.pop();)if((i=t(n.data))&&(a=(i=Array.from(i)).length))for(n.children=i,o=a-1;o>=0;--o)s.push(r=i[o]=new ei(i[o])),r.parent=n,r.depth=n.depth+1;return l.eachBefore(Qr)}function Xr(e){return e.children}function Zr(e){return Array.isArray(e)?e[1]:null}function Jr(e){ void 0!==e.data.value&&(e.value=e.data.value),e.data=e.data.data;}function Qr(e){var t=0;do{e.height=t;}while((e=e.parent)&&e.height<++t)}function ei(e){this.data=e,this.depth=this.height=0,this.parent=null;}ei.prototype=Wr.prototype={constructor:ei,count:function(){return this.eachAfter(Ur)},each:function(e,t){let n=-1;for(const r of this)e.call(t,r,++n,this);return this},eachAfter:function(e,t){for(var n,r,i,o=this,a=[o],l=[],s=-1;o=a.pop();)if(l.push(o),n=o.children)for(r=0,i=n.length;r<i;++r)a.push(n[r]);for(;o=l.pop();)e.call(t,o,++s,this);return this},eachBefore:function(e,t){for(var n,r,i=this,o=[i],a=-1;i=o.pop();)if(e.call(t,i,++a,this),n=i.children)for(r=n.length-1;r>=0;--r)o.push(n[r]);return this},find:function(e,t){let n=-1;for(const r of this)if(e.call(t,r,++n,this))return r},sum:function(e){return this.eachAfter((function(t){for(var n=+e(t.data)||0,r=t.children,i=r&&r.length;--i>=0;)n+=r[i].value;t.value=n;}))},sort:function(e){return this.eachBefore((function(t){t.children&&t.children.sort(e);}))},path:function(e){for(var t=this,n=function(e,t){if(e===t)return e;var n=e.ancestors(),r=t.ancestors(),i=null;e=n.pop(),t=r.pop();for(;e===t;)i=e,e=n.pop(),t=r.pop();return i}(t,e),r=[t];t!==n;)t=t.parent,r.push(t);for(var i=r.length;e!==n;)r.splice(i,0,e),e=e.parent;return r},ancestors:function(){for(var e=this,t=[e];e=e.parent;)t.push(e);return t},descendants:function(){return Array.from(this)},leaves:function(){var e=[];return this.eachBefore((function(t){t.children||e.push(t);})),e},links:function(){var e=this,t=[];return e.each((function(n){n!==e&&t.push({source:n.parent,target:n});})),t},copy:function(){return Wr(this).eachBefore(Jr)},[Symbol.iterator]:function*(){var e,t,n,r,i=this,o=[i];do{for(e=o.reverse(),o=[];i=e.pop();)if(yield i,t=i.children)for(n=0,r=t.length;n<r;++n)o.push(t[n]);}while(o.length)}};var Si,Ii;(Si=function(e){
/*! javascript-number-formatter - v1.1.11 - http://mottie.github.com/javascript-number-formatter/ * © ecava */
e.exports=function(e,t){if(!e||isNaN(+t))return t;var n,r,i,o,a,l,s,c,u,f,d=e.length,p=e.search(/[0-9\-\+#]/),h=p>0?e.substring(0,p):"",m=e.split("").reverse().join(""),g=m.search(/[0-9\-\+#]/),v=d-g,y=e.substring(v,v+1),b=v+("."===y||","===y?1:0),x=g>0?e.substring(b,d):"";if(n=(t="-"===(e=e.substring(p,b)).charAt(0)?-t:+t)<0?t=-t:0,i=(r=e.match(/[^\d\-\+#]/g))&&r[r.length-1]||".",o=r&&r[1]&&r[0]||",",e=e.split(i),t=+(t=t.toFixed(e[1]&&e[1].length))+"",l=e[1]&&e[1].lastIndexOf("0"),(!(c=t.split("."))[1]||c[1]&&c[1].length<=l)&&(t=(+t).toFixed(l+1)),u=e[0].split(o),e[0]=u.join(""),(a=e[0]&&e[0].indexOf("0"))>-1)for(;c[0].length<e[0].length-a;)c[0]="0"+c[0];else 0==+c[0]&&(c[0]="");if((t=t.split("."))[0]=c[0],s=u[1]&&u[u.length-1].length){for(m="",v=(f=t[0]).length%s,d=f.length,b=0;b<d;b++)m+=f.charAt(b),!((b-v+1)%s)&&b<d-s&&(m+=o);t[0]=m;}return t[1]=e[1]&&t[1]?i+t[1]:"","0"!==(r=t.join(""))&&""!==r||(n=false),h+(n?"-":"")+r+x};},Si(Ii={exports:{}},Ii.exports),Ii.exports);
const MULTI_REG = /,(?![^(]*\))/;
const SINGLE_REG = /\s(?![^(]*\))/;
const LENGTH_REG = /^[0-9]+[a-zA-Z%]+?$/;
const PREDEFINED_STRINGS = ['none', 'inset', 'initial', 'inherit'];
const isLength = v => v === '0' || LENGTH_REG.test(v);
const getColor = singleShadowString => {
if (!singleShadowString) return undefined;
const parts = singleShadowString.split(SINGLE_REG).filter(part => !PREDEFINED_STRINGS.includes(part.toLowerCase()));
const last = parts.at(-1);
const color = last && !isLength(last) && !PREDEFINED_STRINGS.includes(last.toLowerCase()) ? last : undefined;
return color;
};
const getShadows = shadowString => {
if (!shadowString) return [];
return shadowString.split(MULTI_REG).map(s => s.trim());
};
/**
* Combine box shadow with box shadow color.
* @private
* @param {string} boxShadow - Box shadow which may include color
* @param {string} themeBoxShadow - Box shadow from theme which may include color
* @param {string | undefined} boxShadowColor - Box shadow color
* @returns {string} Returns the combined box shadow and box shadow color
*
* If boxShadow is a single shadow and has a color then this color will be replaced by boxShadowColor and then
* returned as the result,otherwise boxShadowColor will be added to boxShadow and then returned as the result.
* If boxShadow is multiple shadows or an empty string then it will be returned as the result.
*
* @example getFullBoxShadow('none', '', 'red') returns 'none'
*
* @example getFullBoxShadow('initial', '', 'red') returns 'initial'
*
* @example getFullBoxShadow('inherit', '', 'red') returns 'inherit'
*
* @example getFullBoxShadow('', '', 'red') returns ''
*
* @example getFullBoxShadow('1px 2px blue, 3px 6px green', '', 'red') returns '1px 2px blue, 3px 6px green'
*
* @example getFullBoxShadow('1px 2px blue', '', 'red') returns '1px 2px red'
*
* @example getFullBoxShadow('1px 2px', '', 'red') returns '1px 2px red'
*
* @example getFullBoxShadow('1px 2px', '2px 5px green', undefined) returns '1px 2px green'
*
* @example getFullBoxShadow('1px 2px', '2px 5px', undefined) returns '1px 2px'
*/
const getFullBoxShadow = (boxShadow, themeBoxShadow, boxShadowColor) => {
if (boxShadow && PREDEFINED_STRINGS.includes(boxShadow.toLowerCase())) return boxShadow.toLowerCase();
const shadowArray = getShadows(boxShadow);
if (shadowArray.length !== 1) return boxShadow;
let shadowColor = boxShadowColor;
if (!shadowColor) {
const themeShadowArray = getShadows(themeBoxShadow);
if (themeShadowArray.length !== 1) return boxShadow;
shadowColor = getColor(themeShadowArray[0]);
}
if (!shadowColor) return boxShadow;
const color = getColor(shadowArray[0]);
if (color) return boxShadow.replace(color, shadowColor);
return "".concat(boxShadow, " ").concat(shadowColor);
};
function resolveProperty(path, attribute, theme, objectType) {
if (theme && objectType) {
return theme.getStyle("object.".concat(objectType), path, attribute);
}
if (theme) {
return theme.getStyle('', path, attribute);
}
return undefined;
}
function resolveColor(colorObj, path, attribute, theme, objectType) {
if (colorObj && theme) {
return colorObj.color !== 'none' ? theme.getColorPickerColor(colorObj) : undefined;
}
return resolveProperty(path, attribute, theme, objectType);
}
const imageSizingToCssProperty = {
originalSize: 'auto auto',
alwaysFit: 'contain',
fitWidth: '100% auto',
fitHeight: 'auto 100%',
stretchFit: '100% 100%',
alwaysFill: 'cover'
};
const positionToCss = {
'top-left': 'top left',
'top-center': 'top center',
'top-right': 'top right',
'center-left': 'center left',
'center-center': 'center center',
'center-right': 'center right',
'bottom-left': 'bottom left',
'bottom-center': 'bottom center',
'bottom-right': 'bottom right'
};
// TODO: this needs some proper verification
function getSenseServerUrl(app) {
var _app$session;
let config;
let wsUrl;
let protocol;
let isSecure;
if (app !== null && app !== void 0 && (_app$session = app.session) !== null && _app$session !== void 0 && _app$session.config) {
config = app.session.config;
wsUrl = new URL(config.url);
isSecure = wsUrl.protocol === 'wss:';
protocol = isSecure ? 'https://' : 'http://';
return protocol + wsUrl.host;
}
return '';
}
function getBackgroundPosition(bgComp) {
var _bgComp$bgImage;
let bkgImagePosition = 'center center';
if (bgComp !== null && bgComp !== void 0 && (_bgComp$bgImage = bgComp.bgImage) !== null && _bgComp$bgImage !== void 0 && _bgComp$bgImage.position) {
bkgImagePosition = positionToCss[bgComp.bgImage.position];
}
return bkgImagePosition;
}
function getBackgroundSize(bgComp) {
var _bgComp$bgImage2;
let bkgImageSize = imageSizingToCssProperty.originalSize;
const size = bgComp === null || bgComp === void 0 || (_bgComp$bgImage2 = bgComp.bgImage) === null || _bgComp$bgImage2 === void 0 ? void 0 : _bgComp$bgImage2.sizing;
if (size) {
bkgImageSize = imageSizingToCssProperty[size];
}
return bkgImageSize;
}
function resolveImageUrl(app, relativeUrl, host) {
if (!relativeUrl) {
return undefined;
}
if (host) {
return host + relativeUrl;
}
return getSenseServerUrl(app) + relativeUrl;
}
function resolveBgImage(bgComp, app, queryParams, host) {
const bgImageDef = bgComp === null || bgComp === void 0 ? void 0 : bgComp.bgImage;
if (bgImageDef) {
let url = '';
if (bgImageDef.mode === 'media' || bgComp.useImage === 'media') {
let authParamsAsString;
const urlObj = bgImageDef === null || bgImageDef === void 0 ? void 0 : bgImageDef.mediaUrl;
const {
qUrl
} = (urlObj === null || urlObj === void 0 ? void 0 : urlObj.qStaticContentUrl) || {};
url = qUrl ? decodeURIComponent(qUrl) : undefined;
url = resolveImageUrl(app, url, host);
if (queryParams) {
authParamsAsString = Object.entries(queryParams).map(_ref => {
let [key, value] = _ref;
return "&".concat(key, "=").concat(encodeURIComponent(value));
}).join('&');
url = "".concat(url, "?").concat(authParamsAsString);
}
}
if (bgImageDef.mode === 'expression') {
url = bgImageDef.expressionUrl ? decodeURIComponent(bgImageDef.expressionUrl) : undefined;
}
const pos = getBackgroundPosition(bgComp);
const size = getBackgroundSize(bgComp);
return url ? {
url,
pos,
size
} : undefined;
}
return undefined;
}
function resolveBgColor(comp, theme, objectType) {
const bgColor = comp === null || comp === void 0 ? void 0 : comp.bgColor;
if (bgColor && theme) {
if (bgColor.useExpression || bgColor.useColorExpression) {
return theme.validateColor(bgColor.colorExpression);
}
}
return resolveColor(bgColor === null || bgColor === void 0 ? void 0 : bgColor.color, '', 'backgroundColor', theme, objectType);
}
function resolveBorder(comp, theme, objectType, disableThemeBorder) {
const borderColor = resolveColor(comp === null || comp === void 0 ? void 0 : comp.borderColor, '', 'borderColor', theme, objectType);
let borderWidth = comp === null || comp === void 0 ? void 0 : comp.borderWidth;
const shouldGetborderFromTheme = !borderWidth && !disableThemeBorder;
if (shouldGetborderFromTheme) {
borderWidth = resolveProperty('', 'borderWidth', theme, objectType);
}
return borderWidth && borderColor ? "".concat(borderWidth, " solid ").concat(borderColor) : undefined;
}
function resolveBorderRadius(comp, theme, objectType) {
return (comp === null || comp === void 0 ? void 0 : comp.borderRadius) || resolveProperty('', 'borderRadius', theme, objectType);
}
function resolveBoxShadow(comp, theme, objectType) {
var _comp$shadow, _comp$shadow2;
const themeBoxShadow = resolveProperty('shadow', 'boxShadow', theme, objectType);
const boxShadow = (comp === null || comp === void 0 || (_comp$shadow = comp.shadow) === null || _comp$shadow === void 0 ? void 0 : _comp$shadow.boxShadow) || themeBoxShadow;
const boxShadowColor = resolveColor(comp === null || comp === void 0 || (_comp$shadow2 = comp.shadow) === null || _comp$shadow2 === void 0 ? void 0 : _comp$shadow2.boxShadowColor, 'shadow', 'boxShadowColor', theme, objectType);
return getFullBoxShadow(boxShadow, themeBoxShadow, boxShadowColor);
}
function unfurlFontStyle(fontStyle, target) {
if (fontStyle && Array.isArray(fontStyle)) {
return fontStyle;
}
return target === 'main' ? ['bold'] : [];
}
function resolveTextStyle(textComp, target, theme, objectType) {
var _textComp$title;
const textProps = (textComp === null || textComp === void 0 || (_textComp$title = textComp.title) === null || _textComp$title === void 0 ? void 0 : _textComp$title[target]) || {};
const fontStyle = unfurlFontStyle(textProps.fontStyle, target);
return {
fontFamily: textProps.fontFamily || theme.getStyle("object.".concat(objectType), "title.".concat(target), 'fontFamily'),
fontSize: textProps.fontSize || theme.getStyle("object.".concat(objectType), "title.".concat(target), 'fontSize'),
color: textProps.color && textProps.color.color !== 'none' ? theme.getColorPickerColor(textProps.color) : theme.getStyle("object.".concat(objectType), "title.".concat(target), 'color'),
backgroundColor: textProps.backgroundColor || theme.getStyle("object.".concat(objectType), "title.".concat(target), 'backgroundColor'),
fontWeight: fontStyle.includes('bold') ? 'bold' : 'normal',
fontStyle: fontStyle.includes('italic') ? 'italic' : 'normal',
textDecoration: fontStyle.includes('underline') ? 'underline' : 'initial'
};
}
const DEFAULT_SELECTION_COLORS = {
selected: '#00873D',
alternative: '#E4E4E4',
excluded: '#A9A9A9',
selectedExcluded: '#A9A9A9',
possible: '#FFFFFF'
};
const SUPPORTED_COMPONENTS = ['theme', 'selections'];
function getOverridesAsObject() {
let components = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
// Currently supporting components "theme" and "selections".
const overrides = {};
components.forEach(c => {
const k = c === null || c === void 0 ? void 0 : c.key;
if (SUPPORTED_COMPONENTS.includes(k)) {
overrides[k] = c;
}
});
return overrides;
}
function getSelectionColors(_ref) {
var _overrides$theme, _theme$palette, _overrides$theme$cont, _overrides$theme2, _overrides$selections;
let {
getColorPickerColor,
theme,
getListboxStyle,
overrides,
checkboxes
} = _ref;
const componentContentTextColor = (_overrides$theme = overrides.theme) === null || _overrides$theme === void 0 || (_overrides$theme = _overrides$theme.content) === null || _overrides$theme === void 0 ? void 0 : _overrides$theme.fontColor;
// color priority: layout.component > theme content color > MUI theme
const desiredTextColor = getColorPickerColor(componentContentTextColor) || getListboxStyle('content', 'color') || ((_theme$palette = theme.palette) === null || _theme$palette === void 0 ? void 0 : _theme$palette.text.primary);
const useContrastTextColor = !checkboxes && ((_overrides$theme$cont = (_overrides$theme2 = overrides.theme) === null || _overrides$theme2 === void 0 || (_overrides$theme2 = _overrides$theme2.content) === null || _overrides$theme2 === void 0 ? void 0 : _overrides$theme2.useContrastColor) !== null && _overrides$theme$cont !== void 0 ? _overrides$theme$cont : true);
const componentSelectionColors = ((_overrides$selections = overrides.selections) === null || _overrides$selections === void 0 ? void 0 : _overrides$selections.colors) || {};
const getSelectionStateColors = state => {
var _theme$palette2, _theme$palette3;
const paletteState = state === 'selected' ? 'main' : state;
const contrastState = "".concat(state, "Contrast");
// color priority: layout.component > theme dataColors > theme background (only for 'possible') > MUI theme > hardcoded default
const color = getColorPickerColor(componentSelectionColors[state]) || getListboxStyle('', "dataColors.".concat(state)) || state === 'possible' && getListboxStyle('', 'backgroundColor') || ((_theme$palette2 = theme.palette) === null || _theme$palette2 === void 0 || (_theme$palette2 = _theme$palette2.selected) === null || _theme$palette2 === void 0 ? void 0 : _theme$palette2[paletteState]) || DEFAULT_SELECTION_COLORS[state];
const contrastColor = useContrastTextColor ? b(color, desiredTextColor) : desiredTextColor || ((_theme$palette3 = theme.palette) === null || _theme$palette3 === void 0 ? void 0 : _theme$palette3.selected["".concat(contrastState, "Text}")]);
return {
[state]: color,
[contrastState]: contrastColor
};
};
return _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({}, getSelectionStateColors('selected')), getSelectionStateColors('alternative')), getSelectionStateColors('excluded')), getSelectionStateColors('selectedExcluded')), getSelectionStateColors('possible'));
}
function getBackgroundColor(_ref2) {
let {
themeApi,
themeOverrides
} = _ref2;
let color;
const bgColor = themeOverrides === null || themeOverrides === void 0 ? void 0 : themeOverrides.background;
if (!bgColor) {
return color;
}
if (bgColor !== null && bgColor !== void 0 && bgColor.useExpression) {
color = resolveBgColor({
bgColor
}, themeApi, 'listBox');
} else {
color = themeApi.getColorPickerColor(bgColor === null || bgColor === void 0 ? void 0 : bgColor.color);
}
return color;
}
function getSearchColor(getListboxStyle) {
const desiredTextColor = getListboxStyle('content', 'color');
const color = b('#fff', desiredTextColor);
return color;
}
function getSearchBGColor(bgCol, getListboxStyle) {
const searchBgColorObj = g(getListboxStyle('', 'backgroundColor'));
searchBgColorObj.setAlpha(0.7);
return searchBgColorObj.isInvalid() ? bgCol : searchBgColorObj.getRGBA();
}
function getStyles(_ref3) {
var _themeOverrides$heade, _themeOverrides$backg, _themeOverrides$heade2, _themeOverrides$conte, _themeOverrides$heade3, _themeOverrides$heade4, _themeOverrides$conte2, _themeOverrides$conte3;
let {
app,
themeApi,
theme,
queryParams,
components = [],
checkboxes = false
} = _ref3;
const overrides = getOverridesAsObject(components);
const getListboxStyle = (path, prop) => themeApi.getStyle('object.listBox', path, prop);
const getColorPickerColor = c => (c === null || c === void 0 ? void 0 : c.index) > 0 || c !== null && c !== void 0 && c.color ? themeApi.getColorPickerColor(c) : undefined;
const selections = getSelectionColors({
getColorPickerColor,
theme,
getListboxStyle,
overrides,
checkboxes
});
const themeOverrides = overrides.theme || {};
const headerColor = getColorPickerColor((_themeOverrides$heade = themeOverrides.header) === null || _themeOverrides$heade === void 0 ? void 0 : _themeOverrides$heade.fontColor) || getListboxStyle('title.main', 'color');
const bgComponentColor = getBackgroundColor({
themeApi,
themeOverrides
});
const bgImage = (_themeOverrides$backg = themeOverrides.background) !== null && _themeOverrides$backg !== void 0 && _themeOverrides$backg.image ? resolveBgImage({
bgImage: themeOverrides.background.image
}, app, queryParams) : undefined;
const bgColor = bgComponentColor || getListboxStyle('', 'backgroundColor') || theme.palette.background.default;
const searchBgColor = getSearchBGColor(bgColor, getListboxStyle);
const searchColor = getSearchColor(getListboxStyle);
const headerFontStyle = ((_themeOverrides$heade2 = themeOverrides.header) === null || _themeOverrides$heade2 === void 0 ? void 0 : _themeOverrides$heade2.fontStyle) || {};
const contentFontStyle = ((_themeOverrides$conte = themeOverrides.content) === null || _themeOverrides$conte === void 0 ? void 0 : _themeOverrides$conte.fontStyle) || {};
// Ensure we only return falseValue when the component is used, and thus has a false value.
const getWithFallback = (value, trueValue, falseValue) => value === true && trueValue || value === false && falseValue || undefined;
return {
background: {
backgroundColor: bgColor,
backgroundImage: bgImage !== null && bgImage !== void 0 && bgImage.url && !(bgImage !== null && bgImage !== void 0 && bgImage.url.startsWith('url(')) ? "url('".concat(bgImage.url, "')") : undefined,
backgroundRepeat: 'no-repeat',
backgroundSize: bgImage === null || bgImage === void 0 ? void 0 : bgImage.size,
backgroundPosition: bgImage === null || bgImage === void 0 ? void 0 : bgImage.pos
},
header: {
color: headerColor,
fontSize: ((_themeOverrides$heade3 = themeOverrides.header) === null || _themeOverrides$heade3 === void 0 ? void 0 : _themeOverrides$heade3.fontSize) || getListboxStyle('title.main', 'fontSize'),
fontFamily: ((_themeOverrides$heade4 = themeOverrides.header) === null || _themeOverrides$heade4 === void 0 ? void 0 : _themeOverrides$heade4.fontFamily) || getListboxStyle('title.main', 'fontFamily'),
fontWeight: getWithFallback(headerFontStyle.bold, 'bold', 'normal') || getListboxStyle('title.main', 'fontWeight') || 'bold',
textDecoration: headerFontStyle.underline ? 'underline' : 'initial',
fontStyle: getWithFallback(headerFontStyle.italic, 'italic', 'normal') || getListboxStyle('title.main', 'fontStyle') || 'initial'
},
content: {
backgroundColor: checkboxes ? undefined : selections.possible,
color: selections.possibleContrast || getListboxStyle('content', 'color'),
fontSize: ((_themeOverrides$conte2 = themeOverrides.content) === null || _themeOverrides$conte2 === void 0 ? void 0 : _themeOverrides$conte2.fontSize) || getListboxStyle('content', 'fontSize'),
fontFamily: ((_themeOverrides$conte3 = themeOverrides.content) === null || _themeOverrides$conte3 === void 0 ? void 0 : _themeOverrides$conte3.fontFamily) || getListboxStyle('content', 'fontFamily'),
fontWeight: getWithFallback(contentFontStyle.bold, 'bold', 'normal') || getListboxStyle('content', 'fontWeight') || 'normal',
textDecoration: contentFontStyle.underline ? 'underline' : 'initial',
fontStyle: getWithFallback(contentFontStyle.italic, 'italic', 'normal') || getListboxStyle('content', 'fontStyle') || 'initial'
},
search: {
color: searchColor,
borderColor: theme.palette.divider,
highlightBorderColor: theme.palette.custom.focusBorder,
backgroundColor: searchBgColor,
backdropFilter: 'blur(8px)'
},
selections
};
}
function useListboxStyling(_ref4) {
let {
app,
themeApi,
theme,
queryParams,
components,
checkboxes
} = _ref4;
return getStyles({
app,
themeApi,
theme,
queryParams,
components,
checkboxes
});
}
function ListBoxPopover(_ref) {
let {
alignTo,
anchorOrigin = {
vertical: 'bottom',
horizontal: 'center'
},
transformOrigin = {
vertical: 'top',
horizontal: 'center'
},
show,
close,
app,
fieldName,
stateName = '$',
autoFocus,
components,
checkboxes: checkboxesOption,
selectDisabled = () => false,
sortCriteria = [{
qSortByState: 1,
qSortByAscii: 1,
qSortByNumeric: 1,
qSortByLoadOrder: 1
}],
direction = 'ltr'
} = _ref;
const isMasterDim = Boolean(fieldName === null || fieldName === void 0 ? void 0 : fieldName.qLibraryId);
const open = show && Boolean(alignTo.current);
const [listCount, setListCount] = reactExports.useState(0);
const theme = useTheme$1();
const searchInputRef = reactExports.useRef();
const [model] = useSessionModel({
qInfo: {
qType: 'njsListbox'
},
qListObjectDef: {
qStateName: stateName,
qShowAlternatives: true,
qInitialDataFetch: [{
qTop: 0,
qLeft: 0,
qWidth: 0,
qHeight: 0
}],
qDef: {
qSortCriterias: sortCriteria,
qFieldDefs: isMasterDim ? undefined : [fieldName]
},
qLibraryId: isMasterDim ? fieldName.qLibraryId : undefined
}
}, app, fieldName, stateName);
const lock = reactExports.useCallback(() => {
model.lock('/qListObjectDef');
}, [model]);
const unlock = reactExports.useCallback(() => {
model.unlock('/qListObjectDef');
}, [model]);
const {
translator,
themeApi,
keyboardNavigation,
hostConfig
} = reactExports.useContext(InstanceContext);
const moreAlignTo = reactExports.useRef();
const containerRef = reactExports.useRef();
const [selections] = useObjectSelections(app, model, containerRef);
const [layout] = useLayout$1(model);
const [selectionState$1] = reactExports.useState(() => selectionState({
selectDisabled
}));
const keyboard = useTempKeyboard({
containerRef,
enabled: keyboardNavigation
});
const {
checkboxes = checkboxesOption
} = layout || {};
const styles = useListboxStyling({
themeApi,
theme,
components,
checkboxes
});
reactExports.useEffect(() => {
if (selections && open) {
if (!selections.isModal(model)) {
selections.goModal('/qListObjectDef');
}
}
}, [selections, open]);
if (!model || !layout || !translator || !styles) {
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,
selectionState: selectionState$1,
selections
});
const onCtrlF = () => {
searchInputRef.current.focus();
};
const hasSelections$1 = hasSelections(layout);
return /*#__PURE__*/React.createElement(Popover, {
className: "listbox-container",
open: open,
onClose: popoverClose,
anchorEl: alignTo.current,
anchorOrigin: anchorOrigin,
transformOrigin: transformOrigin,
slotProps: {
paper: {
style: {
minWidth: '250px'
}
}
},
onKeyDown: e => e.key === 'Enter' ? popoverClose() : undefined,
direction: direction
}, /*#__PURE__*/React.createElement(Grid, {
container: true,
direction: "column",
gap: 0,
ref: containerRef
}, /*#__PURE__*/React.createElement(Grid, {
item: true,
container: true,
style: {
direction,
padding: theme.spacing(1)
}
}, /*#__PURE__*/React.createElement(Grid, {
item: true
}, isLocked ? /*#__PURE__*/React.createElement(IconButton, {
onClick: unlock,
disabled: !isLocked,
size: "large"
}, /*#__PURE__*/React.createElement(Lock, {
title: translator.get('Listbox.Unlock')
})) : /*#__PURE__*/React.createElement(IconButton, {
onClick: lock,
disabled: !hasSelections$1,
size: "large"
}, /*#__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, {
layout: layout,
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(Grid, {
item: true
}, /*#__PURE__*/React.createElement(ListBoxSearch$1, {
ref: searchInputRef,
popoverOpen: open,
styles: styles,
visible: true,
model: model,
listCount: listCount,
selections: selections,
selectionState: selectionState$1,
keyboard: {
enabled: false,
innerTabStops: true,
focusSelection: keyboard.focusSelection
},
autoFocus: autoFocus !== null && autoFocus !== void 0 ? autoFocus : true,
direction: direction
})), /*#__PURE__*/React.createElement(ListBox, {
model: model,
app: app,
layout: layout,
selections: selections,
selectionState: selectionState$1,
direction: direction,
onSetListCount: c => setListCount(c),
onCtrlF: onCtrlF,
styles: styles,
keyboard: keyboard
}))));
}
function OneField(_ref) {
let {
field,
api,
stateIx = 0,
skipHandleShowListBoxPopover = false,
moreAlignTo = null,
onClose = () => {}
} = _ref;
const {
translator
} = reactExports.useContext(InstanceContext);
const alignTo = moreAlignTo || reactExports.useRef();
const theme = useTheme$1();
const [showListBoxPopover, setShowListBoxPopover] = reactExports.useState(false);
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
}
}, field.label), /*#__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, {
size: "large"
}, /*#__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]);
},
size: "large"
}, /*#__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,
gap: 1,
ref: alignTo,
sx: {
backgroundColor: theme.palette.background.paper,
position: 'relative',
cursor: 'pointer',
padding: '4px',
'&:hover': {
backgroundColor: theme.palette.action.hover
}
},
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 PREFIX$6 = 'MultiState';
const classes$6 = {
item: "".concat(PREFIX$6, "-item")
};
const StyledGrid$5 = styled(Grid)(_ref => {
let {
theme
} = _ref;
return {
["&.".concat(classes$6.item)]: {
backgroundColor: theme.palette.background.paper,
position: 'relative',
cursor: 'pointer',
padding: '4px',
'&:hover': {
backgroundColor: theme.palette.action.hover
},
height: '100%',
alignItems: 'center'
}
};
});
function MultiState(_ref2) {
let {
field,
api,
moreAlignTo = null,
onClose = () => {}
} = _ref2;
// If originated from the `more` item show fields directly
const [showFields, setShowFields] = reactExports.useState(!!moreAlignTo);
const [showStateIx, setShowStateIx] = reactExports.useState(-1);
// If originated from the `more` item align it
const [anchorEl, setAnchorEl] = reactExports.useState(moreAlignTo ? moreAlignTo.current : null);
const alignTo = moreAlignTo || reactExports.useRef();
const {
translator
} = reactExports.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, {
style: {
padding: '0px 8px'
},
color: "secondary",
badgeContent: field.states.length
}, /*#__PURE__*/React.createElement(Typography, {
component: "span",
noWrap: true,
style: {
fontSize: '12px',
lineHeight: '16px',
fontWeight: 600
}
}, field.label))), /*#__PURE__*/React.createElement(Grid, {
item: true
}, /*#__PURE__*/React.createElement("div", {
style: {
width: '12px'
}
})), /*#__PURE__*/React.createElement(Grid, {
item: true
}, /*#__PURE__*/React.createElement(IconButton, {
size: "large"
}, /*#__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.label,
onClick: e => handleShowState(e, ix)
}, /*#__PURE__*/React.createElement(Box, {
border: 1,
width: "100%",
borderRadius: 1,
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(StyledGrid$5, {
container: true,
gap: 0,
className: classes$6.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 PREFIX$5 = 'More';
const classes$5 = {
item: "".concat(PREFIX$5, "-item"),
badge: "".concat(PREFIX$5, "-badge")
};
const StyledGrid$4 = styled(Grid)(_ref => {
let {
theme
} = _ref;
return {
["&.".concat(classes$5.item)]: {
backgroundColor: theme.palette.background.paper,
position: 'relative',
cursor: 'pointer',
padding: '4px',
'&:hover': {
backgroundColor: theme.palette.action.hover
},
height: '100%',
alignItems: 'center'
},
["& .".concat(classes$5.badge)]: {
padding: theme.spacing(0, 1)
}
};
});
function More(_ref2) {
let {
items = [],
api
} = _ref2;
const theme = useTheme$1();
const [showMoreItems, setShowMoreItems] = reactExports.useState(false);
const [showItemIx, setShowItemIx] = reactExports.useState(-1);
const [anchorEl, setAnchorEl] = reactExports.useState(null);
const alignTo = reactExports.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(StyledGrid$4, {
container: true,
gap: 0,
className: classes$5.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, {
size: "large"
}, /*#__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: 1,
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 = 120;
const MIN_WIDTH_MORE = 72;
function getItems(layout) {
if (!layout) {
return [];
}
const fields = {};
// There is one qSelectionObject for the default state $,
// and an array of one qSelectionObject for each alternate state.
function collectFields(qSelectionObject, state) {
qSelectionObject.qSelections.forEach(selection => {
const name = selection.qField;
let currentField = fields[name];
if (currentField === undefined) {
var _selection$qDimension;
currentField = {
name,
label: ((_selection$qDimension = selection.qDimensionReferences) === null || _selection$qDimension === void 0 || (_selection$qDimension = _selection$qDimension.find(element => element.qLabel)) === null || _selection$qDimension === void 0 ? void 0 : _selection$qDimension.qLabel) || selection.qReadableName || name,
states: [],
selections: []
};
fields[name] = currentField;
}
currentField.states.push(state);
currentField.selections.push(selection);
});
}
if (layout.qSelectionObject) {
collectFields(layout.qSelectionObject, '$');
}
if (layout.alternateStates) {
layout.alternateStates.forEach(s => collectFields(s.qSelectionObject, s.stateName));
}
return Object.keys(fields).map(key => fields[key]).filter(f => !f.selections.some(s => s.qIsHidden));
}
function SelectedFields(_ref) {
let {
api,
app
} = _ref;
const theme = useTheme$1();
const [currentSelectionsModel] = useCurrentSelectionsModel(app);
const [layout] = useLayout$1(currentSelectionsModel);
const [state, setState] = reactExports.useState({
items: [],
more: []
});
const {
modalObjectStore
} = reactExports.useContext(InstanceContext).selectionStore;
const [containerRef, containerRect] = useRect$1();
const [maxItems, setMaxItems] = reactExports.useState(0);
const isInListboxPopover = () => {
const {
model
} = modalObjectStore.get(app.id) || {};
return (model === null || model === void 0 ? void 0 : model.genericType) === 'njsListbox';
};
reactExports.useEffect(() => {
if (!containerRect) return;
const {
width
} = containerRect;
const maxWidth = Math.floor(width) - MIN_WIDTH_MORE;
const items = Math.floor(maxWidth / MIN_WIDTH);
setMaxItems(items);
}, [containerRect]);
reactExports.useEffect(() => {
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,
gap: 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, "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));
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] = reactExports.useState(null);
reactExports.useEffect(() => {
if (!appLayout || !currentSelectionsModel || !currentSelectionsLayout) return;
patchAlternateState(currentSelectionsModel, currentSelectionsLayout, appLayout);
}, [appLayout, currentSelectionsModel, currentSelectionsLayout]);
reactExports.useEffect(() => {
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];
}
function Nav(_ref) {
let {
api,
app
} = _ref;
const {
translator
} = reactExports.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(),
size: "large"
}, /*#__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(),
size: "large"
}, /*#__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(),
size: "large"
}, /*#__PURE__*/React.createElement(ClearSelections, null))));
}
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$1() {
return idGen.map(toChar).join('');
}
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,
gap: 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, uid$1());
}
/**
* 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.
* 5) Use 'export' statement over 'module.exports' assignment
**/
// Check `document` and `window` in case of server-side rendering
let windowObject;
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;
}
let cancelFrame = null;
let requestFrame = null;
const TIMEOUT_DURATION = 20;
const clearTimeoutFn = windowObject.clearTimeout;
const setTimeoutFn = windowObject.setTimeout;
const cancelAnimationFrameFn = windowObject.cancelAnimationFrame || windowObject.mozCancelAnimationFrame || windowObject.webkitCancelAnimationFrame;
const 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([animationFrameID, timeoutID]) {
cancelAnimationFrameFn(animationFrameID);
clearTimeoutFn(timeoutID);
};
requestFrame = function requestAnimationFrameWithSetTimeoutFallback(callback) {
const animationFrameID = requestAnimationFrameFn(function animationFrameCallback() {
clearTimeoutFn(timeoutID);
callback();
});
const timeoutID = setTimeoutFn(function timeoutCallback() {
cancelAnimationFrameFn(animationFrameID);
callback();
}, TIMEOUT_DURATION);
return [animationFrameID, timeoutID];
};
}
function createDetectElementResize(nonce) {
let animationKeyframes;
let animationName;
let animationStartEvent;
let animationStyle;
let checkTriggers;
let resetTriggers;
let scrollListener;
const attachEvent = typeof document !== "undefined" && document.attachEvent;
if (!attachEvent) {
resetTriggers = function (element) {
const 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 (element) {
return element.offsetWidth !== element.__resizeLast__.width || element.offsetHeight !== element.__resizeLast__.height;
};
scrollListener = function (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;
}
const 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 */
let animation = false;
let keyframeprefix = "";
animationStartEvent = "animationstart";
const domPrefixes = "Webkit Moz O ms".split(" ");
let startEvents = "webkitAnimationStart animationstart oAnimationStart MSAnimationStart".split(" ");
let pfx = "";
{
const elm = document.createElement("fakeelement");
if (elm.style.animationName !== undefined) {
animation = true;
}
if (animation === false) {
for (let 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 + "; ";
}
const createStyles = function (doc) {
if (!doc.getElementById("detectElementResize")) {
//opacity:0 works around a chrome bug https://code.google.com/p/chromium/issues/detail?id=286360
const 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);
}
};
const addResizeListener = function (element, fn) {
if (attachEvent) {
element.attachEvent("onresize", fn);
} else {
if (!element.__resizeTriggers__) {
const doc = element.ownerDocument;
const 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";
const expandTrigger = doc.createElement("div");
expandTrigger.className = "expand-trigger";
expandTrigger.appendChild(doc.createElement("div"));
const 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);
}
};
const removeResizeListener = function (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,
removeResizeListener
};
}
class AutoSizer extends reactExports.Component {
constructor(...args) {
super(...args);
this.state = {
height: this.props.defaultHeight || 0,
scaledHeight: this.props.defaultHeight || 0,
scaledWidth: this.props.defaultWidth || 0,
width: this.props.defaultWidth || 0
};
this._autoSizer = null;
this._detectElementResize = null;
this._parentNode = null;
this._resizeObserver = null;
this._timeoutId = null;
this._onResize = () => {
this._timeoutId = null;
const {
disableHeight,
disableWidth,
onResize
} = this.props;
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.
const style = window.getComputedStyle(this._parentNode) || {};
const paddingLeft = parseFloat(style.paddingLeft || "0");
const paddingRight = parseFloat(style.paddingRight || "0");
const paddingTop = parseFloat(style.paddingTop || "0");
const paddingBottom = parseFloat(style.paddingBottom || "0");
const rect = this._parentNode.getBoundingClientRect();
const scaledHeight = rect.height - paddingTop - paddingBottom;
const scaledWidth = rect.width - paddingLeft - paddingRight;
const height = this._parentNode.offsetHeight - paddingTop - paddingBottom;
const width = this._parentNode.offsetWidth - paddingLeft - paddingRight;
if (!disableHeight && (this.state.height !== height || this.state.scaledHeight !== scaledHeight) || !disableWidth && (this.state.width !== width || this.state.scaledWidth !== scaledWidth)) {
this.setState({
height,
width,
scaledHeight,
scaledWidth
});
if (typeof onResize === "function") {
onResize({
height,
scaledHeight,
scaledWidth,
width
});
}
}
}
};
this._setRef = autoSizer => {
this._autoSizer = autoSizer;
};
}
componentDidMount() {
const {
nonce
} = this.props;
const parentNode = this._autoSizer ? this._autoSizer.parentNode : null;
if (parentNode != null && parentNode.ownerDocument && parentNode.ownerDocument.defaultView && parentNode instanceof 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 = parentNode;
// Use ResizeObserver from the same context where parentNode (which we will observe) was defined
// Using just global can result into onResize events not being emitted in cases with multiple realms
const ResizeObserverInstance = parentNode.ownerDocument.defaultView.ResizeObserver;
if (ResizeObserverInstance != null) {
this._resizeObserver = new ResizeObserverInstance(() => {
// Guard against "ResizeObserver loop limit exceeded" error;
// could be triggered if the state update causes the ResizeObserver handler to run long.
// See https://github.com/bvaughn/react-virtualized-auto-sizer/issues/55
this._timeoutId = setTimeout(this._onResize, 0);
});
this._resizeObserver.observe(parentNode);
} else {
// Defer requiring resize handler in order to support server-side rendering.
// See issue #41
this._detectElementResize = createDetectElementResize(nonce);
this._detectElementResize.addResizeListener(parentNode, this._onResize);
}
this._onResize();
}
}
componentWillUnmount() {
if (this._parentNode) {
if (this._detectElementResize) {
this._detectElementResize.removeResizeListener(this._parentNode, this._onResize);
}
if (this._timeoutId !== null) {
clearTimeout(this._timeoutId);
}
if (this._resizeObserver) {
this._resizeObserver.disconnect();
}
}
}
render() {
const {
children,
defaultHeight,
defaultWidth,
disableHeight = false,
disableWidth = false,
doNotBailOutOnEmptyChildren = false,
nonce,
onResize,
style = {},
tagName = "div",
...rest
} = this.props;
const {
height,
scaledHeight,
scaledWidth,
width
} = this.state;
// 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.
const outerStyle = {
overflow: "visible"
};
const childParams = {};
// Avoid rendering children before the initial measurements have been collected.
// At best this would just be wasting cycles.
let bailoutOnChildren = false;
if (!disableHeight) {
if (height === 0) {
bailoutOnChildren = true;
}
outerStyle.height = 0;
childParams.height = height;
childParams.scaledHeight = scaledHeight;
}
if (!disableWidth) {
if (width === 0) {
bailoutOnChildren = true;
}
outerStyle.width = 0;
childParams.width = width;
childParams.scaledWidth = scaledWidth;
}
if (doNotBailOutOnEmptyChildren) {
bailoutOnChildren = false;
}
return reactExports.createElement(tagName, {
ref: this._setRef,
style: {
...outerStyle,
...style
},
...rest
}, !bailoutOnChildren && children(childParams));
}
}
/* eslint-disable no-param-reassign */
function getListboxContainerKeyboardNavigation(_ref) {
let {
keyboard,
hovering,
updateKeyScroll,
currentScrollIndex,
isModal,
constraints,
selections
} = _ref;
const handleKeyDown = event => {
const {
keyCode,
shiftKey = false
} = event.nativeEvent;
const prevent = () => {
event.stopPropagation();
event.preventDefault();
};
if (!keyboard.enabled) {
// Other keys should not be handled unless keyboard is enabled.
return;
}
const container = event.currentTarget.closest('.listbox-container');
const inSelection = isModal();
switch (keyCode) {
case KEYS.TAB:
// Only react to tab after enter/space have been pressed or the target element is inside listbox (mouse case) or target is selection toolbar
if (document.activeElement === container || !inSelection && !container.contains(document.activeElement)) return;
if (shiftKey) {
const focused = focusRow(container) || focusSearch(container);
if (!focused) {
blur$1(event, keyboard);
}
} else {
const focused = focusCyclicButton(container) || focusSearch(container) || focusRow(container);
if (!focused) {
break;
}
}
prevent();
break;
case KEYS.ENTER:
case KEYS.SPACE:
if (!event.target.classList.contains('listbox-container')) {
break; // don't mess with keydown handlers within the listbox (e.g. row seletion)
}
keyboard.focus();
prevent();
break;
case KEYS.ESCAPE:
blur$1(event, keyboard);
if (selections.isActive()) {
selections.cancel();
}
break;
}
};
const focusOnHoverDisabled = () => {
const selectNotAllowed = (constraints === null || constraints === void 0 ? void 0 : constraints.select) || (constraints === null || constraints === void 0 ? void 0 : constraints.active);
const appInModal = isModal();
return selectNotAllowed || appInModal;
};
const globalKeyDown = event => {
if (!hovering.current || focusOnHoverDisabled()) {
return;
}
const {
keyCode,
ctrlKey = false,
shiftKey = false
} = event;
switch (keyCode) {
case KEYS.ARROW_UP:
updateKeyScroll({
up: 1
});
break;
case KEYS.ARROW_DOWN:
updateKeyScroll({
down: 1
});
break;
case KEYS.PAGE_UP:
updateKeyScroll({
up: currentScrollIndex.stop - currentScrollIndex.start
});
break;
case KEYS.PAGE_DOWN:
updateKeyScroll({
down: currentScrollIndex.stop - currentScrollIndex.start
});
break;
case KEYS.HOME:
updateKeyScroll({
scrollPosition: ctrlKey && shiftKey ? 'overflowStart' : 'start'
});
break;
case KEYS.END:
updateKeyScroll({
scrollPosition: ctrlKey && shiftKey ? 'overflowEnd' : 'end'
});
break;
default:
return;
}
event.preventDefault();
};
const handleOnMouseEnter = () => {
hovering.current = true;
};
const handleOnMouseLeave = () => {
if (hovering.current) {
hovering.current = false;
}
};
return {
handleKeyDown,
handleOnMouseEnter,
handleOnMouseLeave,
globalKeyDown
};
}
const StyledDiv = styled('div')(() => ({
display: 'flex',
width: '100%',
height: '100%',
alignItems: 'center',
justifyContent: 'center'
}));
function ListBoxError(_ref) {
let {
text
} = _ref;
const {
translator: translatorDynamic
} = reactExports.useContext(InstanceContext);
return /*#__PURE__*/React.createElement(StyledDiv, null, translatorDynamic.get(text));
}
function isDirectQueryEnabled(_ref) {
let {
appLayout
} = _ref;
const isDQ = !!(appLayout !== null && appLayout !== void 0 && appLayout.qIsDirectQueryMode);
return isDQ;
}
function getContainerPadding(_ref) {
let {
isGridMode,
dense,
height,
layoutOrder
} = _ref;
let containerPadding;
if (isGridMode) {
const itemHeight = getItemHeight({
isGridMode,
dense
});
let paddingY;
if (itemHeight > height) {
paddingY = '0px';
} else {
paddingY = '2px';
}
containerPadding = layoutOrder === 'row' ? "".concat(paddingY, " 4px") : "".concat(paddingY, " 6px ").concat(paddingY, " 4px");
} else {
containerPadding = undefined;
}
return containerPadding;
}
function showToolbarDetached(_ref) {
var _titleRef$current$cli, _titleRef$current, _titleRef$current2, _titleRef$current3;
let {
containerRect,
titleRef,
iconsWidth,
paddingLeft,
paddingRight
} = _ref;
const containerWidth = containerRect.width;
const preventTruncation = 2;
const padding = paddingLeft + paddingRight;
const contentWidth = ((_titleRef$current$cli = titleRef === null || titleRef === void 0 || (_titleRef$current = titleRef.current) === null || _titleRef$current === void 0 ? void 0 : _titleRef$current.clientWidth) !== null && _titleRef$current$cli !== void 0 ? _titleRef$current$cli : 0) + iconsWidth + padding + preventTruncation;
const actionToolbarWidth = 128;
const notSufficientSpace = containerWidth < contentWidth + actionToolbarWidth;
const isTruncated = (titleRef === null || titleRef === void 0 || (_titleRef$current2 = titleRef.current) === null || _titleRef$current2 === void 0 ? void 0 : _titleRef$current2.scrollWidth) > (titleRef === null || titleRef === void 0 || (_titleRef$current3 = titleRef.current) === null || _titleRef$current3 === void 0 ? void 0 : _titleRef$current3.offsetWidth);
const isDetached = !!(notSufficientSpace || isTruncated);
return isDetached;
}
function getListboxActionProps(_ref) {
let {
isDetached,
showToolbar,
containerRef,
isLocked,
listboxSelectionToolbarItems,
extraItems,
selections,
keyboard,
autoConfirm,
disablePortal
} = _ref;
return {
autoConfirm,
isDetached,
show: showToolbar && !isDetached,
popover: {
show: showToolbar && isDetached,
anchorEl: containerRef.current
},
extraItems,
more: {
enabled: !isLocked,
actions: listboxSelectionToolbarItems,
popoverProps: {
elevation: 0
},
popoverPaperStyle: {
boxShadow: '0 12px 8px -8px rgba(0, 0, 0, 0.2)',
minWidth: '250px'
},
disablePortal
},
selections: {
show: showToolbar,
api: selections,
onConfirm: () => {
keyboard === null || keyboard === void 0 || keyboard.focus();
},
onCancel: () => {
keyboard === null || keyboard === void 0 || keyboard.focus();
}
}
};
}
const iconStyle = {
fontSize: '12px'
};
const UnlockButton = styled(ButtonBase)(_ref => {
let {
theme,
isLoading
} = _ref;
return {
position: 'absolute',
top: 0,
left: 0,
height: 48,
zIndex: 2,
// so it goes on top of action buttons
background: theme.palette.custom.disabledBackground,
opacity: 1,
color: theme.palette.custom.disabledContrastText,
width: '100%',
display: 'flex',
justifyContent: isLoading ? 'center' : 'flex-start',
paddingLeft: 16,
paddingRight: 16,
borderRadius: 0,
'& *, & p': {
color: theme.palette.custom.disabledContrastText
},
'& i': {
padding: "".concat(ICON_PADDING, "px")
}
};
});
const StyledGridHeader = styled(Grid, {
shouldForwardProp: p => !['styles', 'isRtl'].includes(p)
})(_ref2 => {
let {
styles,
isRtl
} = _ref2;
return _objectSpread2(_objectSpread2({
flexDirection: isRtl ? 'row-reverse' : 'row',
wrap: 'nowrap',
minHeight: 32,
alignContent: 'center'
}, styles.header), {}, {
'& *': {
color: styles.header.color
}
});
});
const HeaderTitle = styled(Typography)(_ref3 => {
let {
styles
} = _ref3;
return _objectSpread2(_objectSpread2({}, styles.header), {}, {
display: 'block',
// needed for text-overflow to work
alignItems: 'center',
paddingRight: '1px' // make place for italic font style
});
});
function UnlockCoverButton(_ref4) {
let {
translator,
toggleLock,
keyboard,
isLoading
} = _ref4;
const fontSize = '14px';
const unLockText = translator.get('SelectionToolbar.ClickToUnlock');
const component = /*#__PURE__*/React.createElement(UnlockButton, {
title: unLockText,
tabIndex: keyboard.enabled ? 0 : -1,
onClick: toggleLock,
"data-testid": "listbox-unlock-button",
id: "listbox-unlock-button",
isLoading: isLoading
}, isLoading ? /*#__PURE__*/React.createElement(CircularProgress, {
size: 16,
variant: "indeterminate",
color: "primary"
}) : /*#__PURE__*/React.createElement(Lock, {
disableRipple: true,
style: iconStyle
}), !isLoading && /*#__PURE__*/React.createElement(Typography, {
fontSize: fontSize
}, unLockText));
return component;
}
const cyclic = props => _objectSpread2(_objectSpread2({}, props), {}, {
shapes: [{
type: 'path',
attrs: {
d: 'M 6 2 h 10 V 1 H 6 Z m 5 5 h 5 V 6 h -5 Z m 5 5 h -5 v -1 h 5 Z M 5 10 h 1 v 2.663 a 3.5 3.5 0 1 0 -2.922 0.036 l -0.406 0.914 A 4.501 4.501 0 1 1 7.329 13 H 9 v 1 H 5 Z'
}
}]
});
var CyclicIcon = props => SvgIcon(cyclic(props));
const drillDown = props => _objectSpread2(_objectSpread2({}, props), {}, {
shapes: [{
type: 'path',
attrs: {
d: 'M7 4h9v1H7zm2 4h7v1H9zm2 4h5v1h-5zM1 4v3.526a3.5 3.5 0 0 0 3.5 3.5h2.31L5.22 9.402l.715-.7L8.7 11.527 5.935 14.35l-.714-.7 1.59-1.624H4.5a4.5 4.5 0 0 1-4.5-4.5V4z'
}
}]
});
var DrillDownIcon = props => SvgIcon(drillDown(props));
const reload = props => _objectSpread2(_objectSpread2({}, props), {}, {
shapes: [{
type: 'path',
attrs: {
d: 'M1 8a7 7 0 1 1 10 6.326V11h-1v5h5v-1h-3.124A8 8 0 1 0 8 16v-1a7 7 0 0 1-7-7Z'
}
}]
});
var ReloadIcon = props => SvgIcon(reload(props));
const dimensionTypes = {
drillDown: 'H',
cyclic: 'C'
};
const createDimensionIconData = _ref => {
let {
dimInfo,
app,
selections,
isPopover,
active,
keyboard
} = _ref;
switch (dimInfo.qGrouping) {
case dimensionTypes.drillDown:
return {
icon: DrillDownIcon,
tooltip: 'Listbox.DrillDown',
onClick: undefined
};
case dimensionTypes.cyclic:
{
const clickable = app && active;
const stepToNextField = () => {
if (!isPopover) {
selections.confirm();
}
app.getDimension(dimInfo.qLibraryId).then(dimensionModel => {
if (!dimensionModel.stepCycle) {
// eslint-disable-next-line no-console
console.log("engine api spec version doesn't have support for function stepCycle");
return;
}
dimensionModel.stepCycle(1);
}).catch(() => null);
};
return {
icon: clickable ? ReloadIcon : CyclicIcon,
tooltip: 'Listbox.Cyclic',
onClick: clickable ? stepToNextField : undefined,
onKeyDown: clickable ? event => {
const container = event.currentTarget.closest('.listbox-container');
switch (event.keyCode) {
case KEYS.SPACE:
case KEYS.ENTER:
stepToNextField();
break;
case KEYS.TAB:
{
const useDefaultBrowserSupport = !keyboard.enabled;
if (useDefaultBrowserSupport) {
return;
}
let focused;
if (event.shiftKey) {
focused = keyboard.focusSelection();
} else {
focused = focusSearch(container) || focusRow(container);
}
if (!focused) {
blur$1(event, keyboard);
}
}
break;
default:
return;
}
event.preventDefault();
event.stopPropagation();
} : undefined
};
}
default:
return undefined;
}
};
var iconUtils = {
createDimensionIconData
};
const StyledButton = styled(Button)(() => ({
borderRadius: 4,
width: 24,
height: 24,
minWidth: 22,
padding: 0
}));
function DimensionIcon(_ref) {
let {
iconData,
translator,
iconStyle,
disabled,
keyboard
} = _ref;
if (!iconData) return undefined;
const {
icon,
tooltip,
onClick = undefined,
onKeyDown = undefined
} = iconData;
const Icon = icon;
const title = translator.get(tooltip);
const isButton = onClick;
return isButton ? /*#__PURE__*/React.createElement(StyledButton, {
variant: "outlined",
onClick: onClick,
tabIndex: keyboard.innerTabStops ? 0 : -1,
title: title,
size: "large",
disableRipple: true,
disabled: disabled,
onKeyDown: onKeyDown,
className: "listbox-cyclic-button",
"data-testid": "listbox-cyclic-button"
}, /*#__PURE__*/React.createElement(Icon, {
style: iconStyle
})) : /*#__PURE__*/React.createElement(Icon, {
title: title,
size: "large",
style: _objectSpread2(_objectSpread2({}, iconStyle), {}, {
padding: "".concat(ICON_PADDING, "px")
})
});
}
// ms that needs to pass before the lock button can be toggled again
const lockTimeFrameMs = 500;
let lastTime = 0;
function getToggleLock(_ref) {
let {
isLocked,
setLocked,
settingLockedState,
model,
setSettingLockedState
} = _ref;
return () => {
const now = new Date();
const curTime = now - lastTime;
if (curTime < lockTimeFrameMs) {
return Promise.resolve();
}
if (settingLockedState) {
return () => {};
}
setSettingLockedState(true);
lastTime = now;
const func = isLocked ? model.unlock : model.lock;
setLocked(!isLocked);
return func.call(model, '/qListObjectDef').catch(() => {
setLocked(isLocked); // revert to the layout value
}).finally(() => {
setTimeout(() => {
setSettingLockedState(false);
}, 0);
});
};
}
function ListBoxHeader(_ref2) {
var _layout$qListObject, _layout$qListObject3, _layout$qListObject4;
let {
layout,
translator,
styles,
isRtl,
showLock,
showSearchIcon,
constraints,
onShowSearch,
classes,
containerRect,
isPopover,
showToolbar,
showDetachedToolbarOnly,
containerRef,
model,
selectionState,
isDirectQuery,
selections,
keyboard,
autoConfirm,
app,
disablePortal
} = _ref2;
const [isToolbarDetached, setIsToolbarDetached] = reactExports.useState(showDetachedToolbarOnly);
const [isLocked, setLocked] = reactExports.useState(layout === null || layout === void 0 || (_layout$qListObject = layout.qListObject) === null || _layout$qListObject === void 0 || (_layout$qListObject = _layout$qListObject.qDimensionInfo) === null || _layout$qListObject === void 0 ? void 0 : _layout$qListObject.qLocked);
const [settingLockedState, setSettingLockedState] = reactExports.useState(false);
reactExports.useEffect(() => {
var _layout$qListObject2;
setLocked(layout === null || layout === void 0 || (_layout$qListObject2 = layout.qListObject) === null || _layout$qListObject2 === void 0 || (_layout$qListObject2 = _layout$qListObject2.qDimensionInfo) === null || _layout$qListObject2 === void 0 ? void 0 : _layout$qListObject2.qLocked);
}, [layout === null || layout === void 0 || (_layout$qListObject3 = layout.qListObject) === null || _layout$qListObject3 === void 0 || (_layout$qListObject3 = _layout$qListObject3.qDimensionInfo) === null || _layout$qListObject3 === void 0 ? void 0 : _layout$qListObject3.qLocked]);
const titleRef = reactExports.useRef(null);
const iconData = iconUtils.createDimensionIconData({
dimInfo: layout === null || layout === void 0 || (_layout$qListObject4 = layout.qListObject) === null || _layout$qListObject4 === void 0 ? void 0 : _layout$qListObject4.qDimensionInfo,
app,
selections,
isPopover,
active: !(constraints !== null && constraints !== void 0 && constraints.active),
keyboard
});
const showUnlock = showLock && isLocked;
const showLockIcon = !showLock && isLocked; // shows instead of the cover button when field/dim is locked.
const showLeftIcon = showSearchIcon || showLockIcon || iconData; // the left-most icon outside of the actions/selections toolbar.
const paddingLeft = CELL_PADDING_LEFT - (showLeftIcon ? ICON_PADDING : 0);
const paddingRight = isRtl ? CELL_PADDING_LEFT - (showLeftIcon ? ICON_PADDING : 0) : HEADER_PADDING_RIGHT;
// Calculate explicit width for icons container. Search and lock cannot exist combined.
const iconsWidth = (showSearchIcon ? BUTTON_ICON_WIDTH : 0) + (showLockIcon ? BUTTON_ICON_WIDTH : 0) + (iconData ? BUTTON_ICON_WIDTH : 0);
const toggleLock = getToggleLock({
isLocked,
setLocked,
settingLockedState,
setSettingLockedState,
model
});
const listboxSelectionToolbarItems = createListboxSelectionToolbar({
layout,
model,
translator,
selectionState,
isDirectQuery,
selections
});
const extraItems = isLocked || !showLock ? undefined : [{
key: 'lock',
type: undefined,
label: translator.get('SelectionToolbar.ClickToLock'),
getSvgIconShape: unlock,
enabled: () => !settingLockedState && !selectionState.selectDisabled() && hasSelections(layout),
action: toggleLock
}];
const searchIconComp = constraints !== null && constraints !== void 0 && constraints.active ? /*#__PURE__*/React.createElement(SearchIcon, {
title: translator.get('Listbox.Search'),
size: "large",
style: _objectSpread2(_objectSpread2({}, iconStyle), {}, {
padding: "".concat(ICON_PADDING, "px")
})
}) : /*#__PURE__*/React.createElement(IconButton, {
onClick: onShowSearch,
tabIndex: -1,
title: translator.get('Listbox.Search'),
size: "large",
disableRipple: true,
"data-testid": "search-toggle-btn"
}, /*#__PURE__*/React.createElement(SearchIcon, {
style: iconStyle
}));
reactExports.useEffect(() => {
if (!titleRef.current || !containerRect) {
return;
}
const mustShowDetached = showToolbarDetached({
containerRect,
titleRef,
iconsWidth,
paddingLeft,
paddingRight
});
const isDetached = showDetachedToolbarOnly || mustShowDetached;
setIsToolbarDetached(isDetached);
}, [iconsWidth, paddingLeft, paddingRight, titleRef.current, showDetachedToolbarOnly, Object.entries(containerRect || {}).sort().join(',')]);
const toolbarProps = getListboxActionProps({
isDetached: isPopover ? false : isToolbarDetached,
showToolbar,
containerRef,
isLocked,
extraItems,
listboxSelectionToolbarItems,
selections,
keyboard,
autoConfirm,
disablePortal
});
const actionsToolbar = /*#__PURE__*/React.createElement(ActionsToolbar, _extends$1({
isRtl: isRtl,
layout: layout
}, toolbarProps));
if (showDetachedToolbarOnly) {
return actionsToolbar;
}
// Always show a lock symbol when locked and showLock is false
const lockedIconComp = showLockIcon ? /*#__PURE__*/React.createElement(Lock, {
size: "large",
style: _objectSpread2(_objectSpread2({}, iconStyle), {}, {
padding: "".concat(ICON_PADDING, "px")
})
}) : undefined;
return /*#__PURE__*/React.createElement(StyledGridHeader, {
item: true,
container: true,
styles: styles,
isRtl: isRtl,
marginY: 1,
paddingLeft: "".concat(paddingLeft, "px"),
paddingRight: "".concat(paddingRight, "px"),
className: "header-container"
}, showUnlock && /*#__PURE__*/React.createElement(UnlockCoverButton, {
isLoading: settingLockedState,
translator: translator,
toggleLock: toggleLock,
keyboard: keyboard
}), showLeftIcon && /*#__PURE__*/React.createElement(Grid, {
item: true,
container: true,
alignItems: "center",
width: iconsWidth,
className: "header-action-container"
}, lockedIconComp || showSearchIcon && searchIconComp, /*#__PURE__*/React.createElement(DimensionIcon, {
iconData: iconData,
iconStyle: iconStyle,
disabled: selections.isActive() && isPopover,
translator: translator,
keyboard: keyboard
})), /*#__PURE__*/React.createElement(Grid, {
item: true,
xs: true,
minWidth: 0 // needed to text-overflow see: https://css-tricks.com/flexbox-truncated-text/
,
justifyContent: isRtl ? 'flex-end' : 'flex-start',
className: classes.listBoxHeader
}, /*#__PURE__*/React.createElement(HeaderTitle, {
variant: "h6",
noWrap: true,
ref: titleRef,
title: layout.title,
styles: styles
}, layout.title)), /*#__PURE__*/React.createElement(Grid, {
item: true,
display: "flex"
}, actionsToolbar));
}
const StyledBorder = styled('div')(_ref => {
let {
theme,
width,
height
} = _ref;
return {
position: 'absolute',
pointerEvents: 'none',
zIndex: 1,
width,
height,
boxShadow: "inset 0 0 0 2px ".concat(theme.palette.custom.focusBorder)
};
});
function ListBoxFocusBorder(_ref2) {
let {
width,
height,
disabled,
childNode,
containerNode
} = _ref2;
const [isOnlyContainerFocused, setIsOnlyContainerFocused] = reactExports.useState(false);
const checkFocus = reactExports.useCallback(() => {
const containerFocused = containerNode && containerNode.contains(document.activeElement);
const childFocused = childNode && childNode.contains(document.activeElement);
setIsOnlyContainerFocused(containerFocused && !childFocused);
}, [containerNode, childNode]);
reactExports.useEffect(() => {
if (!containerNode) {
return undefined;
}
containerNode.addEventListener('focusin', checkFocus);
containerNode.addEventListener('focusout', checkFocus);
checkFocus();
return () => {
containerNode.removeEventListener('focusin', checkFocus);
containerNode.removeEventListener('focusout', checkFocus);
};
}, [checkFocus, containerNode]);
const show = !disabled && isOnlyContainerFocused;
if (!show) {
return null;
}
return /*#__PURE__*/React.createElement(StyledBorder, {
"aria-hidden": "true",
width: width,
height: height
});
}
const PREFIX$4 = 'ListBoxInline';
const classes$4 = {
listBoxHeader: "".concat(PREFIX$4, "-listBoxHeader"),
screenReaderOnly: "".concat(PREFIX$4, "-screenReaderOnly"),
listboxWrapper: "".concat(PREFIX$4, "-listboxWrapper")
};
const StyledGrid$3 = styled(Grid, {
shouldForwardProp: p => !['containerPadding', 'styles'].includes(p)
})(_ref => {
let {
containerPadding,
styles
} = _ref;
return _objectSpread2(_objectSpread2({}, styles.background), {}, {
// sets background color and image of listbox
["& .".concat(classes$4.listBoxHeader)]: {
alignSelf: 'center',
display: 'flex'
},
["& .".concat(classes$4.screenReaderOnly)]: {
position: 'absolute',
height: 0,
width: 0,
overflow: 'hidden'
},
["& .".concat(classes$4.listboxWrapper)]: {
padding: containerPadding
},
'&:focus-visible': {
outline: 'none'
}
});
});
const isModal = _ref2 => {
var _app$isInModalSelecti, _app$isInModalSelecti2;
let {
app,
appSelections
} = _ref2;
return (_app$isInModalSelecti = (_app$isInModalSelecti2 = app.isInModalSelection) === null || _app$isInModalSelecti2 === void 0 ? void 0 : _app$isInModalSelecti2.call(app)) !== null && _app$isInModalSelecti !== void 0 ? _app$isInModalSelecti : appSelections.isInModal();
};
function ListBoxInline(_ref3) {
var _layout$qListObject, _layout$title, _layoutOptions$dense, _containerRef$current2;
let {
options,
layout
} = _ref3;
const {
app,
direction,
frequencyMode,
checkboxes: checkboxesOption,
search = true,
focusSearch = false,
rangeSelect = true,
model,
selections,
update = undefined,
fetchStart = undefined,
postProcessPages = undefined,
calculatePagesHeight,
showGray = true,
scrollState = undefined,
renderedCallback,
toolbar = true,
isPopover = false,
showLock = false,
components,
selectDisabled = () => false,
disablePortal = true
} = options;
const theme = useTheme$1();
const {
translator,
keyboardNavigation,
themeApi,
queryParams,
constraints
} = reactExports.useContext(InstanceContext);
const {
checkboxes = checkboxesOption
} = layout || {};
const styles = useListboxStyling({
app,
themeApi,
theme,
queryParams,
components,
checkboxes
});
const isDirectQuery = isDirectQueryEnabled({
appLayout: app === null || app === void 0 ? void 0 : app.layout
});
const containerRef = reactExports.useRef();
const searchInputRef = reactExports.useRef();
const [containerRectRef, containerRect, containerNode] = useRect$1();
const [showToolbar, setShowToolbar] = reactExports.useState(false);
const [showSearch, setShowSearch] = reactExports.useState(false);
const hovering = reactExports.useRef(false);
const [keyScroll, setKeyScroll] = reactExports.useState({
down: 0,
up: 0,
scrollPosition: ''
});
const updateKeyScroll = newState => setKeyScroll(current => _objectSpread2(_objectSpread2({}, current), newState));
const [currentScrollIndex, setCurrentScrollIndex] = reactExports.useState({
start: 0,
stop: 0
});
const [appSelections] = useAppSelections(app);
const [selectionState$1] = reactExports.useState(() => selectionState({
selectDisabled
}));
const keyboard = useTempKeyboard({
containerRef,
enabled: keyboardNavigation
});
const isModalMode = reactExports.useCallback(() => isModal({
app,
appSelections
}), [app, appSelections]);
const isInvalid = layout === null || layout === void 0 ? void 0 : layout.qListObject.qDimensionInfo.qError;
const errorText = isInvalid && constraints.active ? 'Visualization.Invalid.Dimension' : 'Visualization.Incomplete';
const [, setHasFocus] = reactExports.useState(false); // Force render on focus change to show/hide ListBoxFocusBorder
const [listboxChildNode, setListboxChildNode] = reactExports.useState(null);
const listboxChildRef = reactExports.useCallback(node => {
setListboxChildNode(node);
}, []);
const {
handleKeyDown,
handleOnMouseEnter,
handleOnMouseLeave,
globalKeyDown
} = reactExports.useMemo(() => getListboxContainerKeyboardNavigation({
keyboard,
hovering,
updateKeyScroll,
currentScrollIndex,
constraints,
isModal: isModalMode,
selections
}), [keyboard, hovering, updateKeyScroll, containerRef, currentScrollIndex, app, appSelections, constraints, isModalMode]);
reactExports.useEffect(() => {
document.addEventListener('keydown', globalKeyDown);
return () => {
document.removeEventListener('keydown', globalKeyDown);
};
}, [globalKeyDown]);
reactExports.useEffect(() => {
if (search === true) {
setShowSearch(true);
}
const show = () => {
setShowToolbar(true);
};
const hide = () => {
setShowToolbar(false);
if (search === 'toggle') {
setShowSearch(false);
}
};
if (isPopover) {
// When isPopover, toolbar == false will be ignored.
if (!selections.isActive()) {
selections.on('activated', show);
selections.on('deactivated', hide);
}
setShowToolbar(isPopover);
}
if (toolbar && selections) {
if (!selections.isModal()) {
selections.on('activated', show);
selections.on('deactivated', hide);
}
setShowToolbar(isPopover || selections.isActive());
}
return () => {
if (selections && selections.removeListener) {
selections.removeListener('activated', show);
selections.removeListener('deactivated', hide);
}
};
}, [toolbar, selections, isPopover]);
const {
wildCardSearch,
searchEnabled,
autoConfirm = false,
layoutOptions = {}
} = layout !== null && layout !== void 0 ? layout : {};
const isLocked = layout === null || layout === void 0 || (_layout$qListObject = layout.qListObject) === null || _layout$qListObject === void 0 || (_layout$qListObject = _layout$qListObject.qDimensionInfo) === null || _layout$qListObject === void 0 ? void 0 : _layout$qListObject.qLocked;
const showSearchIcon = searchEnabled !== false && search === 'toggle' && !isLocked;
const canShowTitle = (layout === null || layout === void 0 || (_layout$title = layout.title) === null || _layout$title === void 0 ? void 0 : _layout$title.length) && (layout === null || layout === void 0 ? void 0 : layout.showTitle) !== false;
const showDetachedToolbarOnly = toolbar && !canShowTitle && !isPopover;
const showAttachedToolbar = toolbar && canShowTitle || isPopover;
const isRtl = direction === 'rtl';
if (!model || !layout || !translator || !styles) {
return null;
}
const showSearchToggle = search === 'toggle' && showSearch;
const searchVisible = search === true || showSearchToggle && searchEnabled !== false;
const dense = (_layoutOptions$dense = layoutOptions.dense) !== null && _layoutOptions$dense !== void 0 ? _layoutOptions$dense : false;
const handleShowSearch = () => {
var _containerRef$current;
const newValue = !showSearch;
setShowSearch(newValue);
if (newValue && (_containerRef$current = containerRef.current) !== null && _containerRef$current !== void 0 && _containerRef$current.scrollIntoView) {
containerRef.current.scrollIntoView({
block: 'nearest',
inline: 'nearest',
behavior: 'instant'
});
}
};
const onCtrlF = () => {
if (search === 'toggle') {
handleShowSearch();
} else {
searchInputRef.current.focus();
}
};
const shouldAutoFocus = searchVisible && (search === 'toggle' || focusSearch);
// Add a container padding for grid mode to harmonize with the grid item margins (should sum to 8px).
const isGridMode = (layoutOptions === null || layoutOptions === void 0 ? void 0 : layoutOptions.dataLayout) === 'grid';
const containerPadding = getContainerPadding({
isGridMode,
dense,
height: (_containerRef$current2 = containerRef.current) === null || _containerRef$current2 === void 0 ? void 0 : _containerRef$current2.clientHeight,
layoutOrder: layoutOptions.layoutOrder
});
if (isInvalid) {
renderedCallback === null || renderedCallback === void 0 || renderedCallback();
}
const listBoxMinHeight = showAttachedToolbar ? DENSE_ROW_HEIGHT + SCROLL_BAR_WIDTH : 0;
const listBoxHeader = /*#__PURE__*/React.createElement(ListBoxHeader, {
app: app,
showSearchIcon: showSearchIcon,
onShowSearch: handleShowSearch,
isPopover: isPopover,
showToolbar: showToolbar,
isDirectQuery: isDirectQuery,
autoConfirm: autoConfirm,
showDetachedToolbarOnly: showDetachedToolbarOnly,
layout: layout,
translator: translator,
styles: styles,
isRtl: isRtl,
showLock: showLock,
constraints: constraints,
classes: classes$4,
containerRect: containerRect,
containerRef: containerRef,
model: model,
selectionState: selectionState$1,
selections: selections,
keyboard: keyboard,
disablePortal: disablePortal
});
return /*#__PURE__*/React.createElement(React.Fragment, null, showDetachedToolbarOnly && listBoxHeader, /*#__PURE__*/React.createElement(StyledGrid$3, {
className: "listbox-container",
container: true,
tabIndex: keyboard.enabled ? -1 : undefined,
direction: "column",
gap: 0,
containerPadding: containerPadding,
styles: styles,
style: {
height: '100%',
flexFlow: 'column nowrap'
},
onKeyDown: handleKeyDown,
onMouseEnter: handleOnMouseEnter,
onMouseLeave: handleOnMouseLeave,
ref: el => {
containerRef.current = el;
containerRectRef === null || containerRectRef === void 0 || containerRectRef(el);
},
"aria-label": keyboard.active ? translator.get('Listbox.ScreenReaderInstructions') : '',
onFocus: () => setHasFocus(true),
onBlur: () => setHasFocus(false)
}, /*#__PURE__*/React.createElement(ListBoxFocusBorder, {
width: containerRect === null || containerRect === void 0 ? void 0 : containerRect.width,
height: containerRect === null || containerRect === void 0 ? void 0 : containerRect.height,
disabled: isModalMode() || isPopover,
childNode: listboxChildNode,
containerNode: containerNode
}), showAttachedToolbar && listBoxHeader, /*#__PURE__*/React.createElement(Grid, {
item: true,
container: true,
direction: "column",
height: "100%",
minHeight: listBoxMinHeight,
role: "region",
"aria-label": translator.get('Listbox.ResultFilterLabel'),
ref: listboxChildRef
}, /*#__PURE__*/React.createElement(Grid, {
item: true
}, /*#__PURE__*/React.createElement(ListBoxSearch$1, {
ref: searchInputRef,
selections: selections,
selectionState: selectionState$1,
model: model,
dense: dense,
keyboard: keyboard,
visible: searchVisible,
search: search,
autoFocus: shouldAutoFocus,
beginSelectionOnFocus: !isPopover,
wildCardSearch: wildCardSearch,
searchEnabled: searchEnabled,
direction: direction,
hide: showSearchIcon && handleShowSearch,
styles: styles
})), /*#__PURE__*/React.createElement(Grid, {
item: true,
xs: true,
className: classes$4.listboxWrapper
}, isInvalid ? /*#__PURE__*/React.createElement(ListBoxError, {
text: errorText
}) : /*#__PURE__*/React.createElement(AutoSizer, null, _ref4 => {
let {
height,
width
} = _ref4;
return /*#__PURE__*/React.createElement(ListBox, {
model: model,
app: app,
constraints: constraints,
layout: layout,
selections: selections,
selectionState: selectionState$1,
direction: direction,
frequencyMode: frequencyMode,
rangeSelect: rangeSelect,
checkboxes: checkboxes,
height: height,
width: width,
update: update,
fetchStart: fetchStart,
postProcessPages: postProcessPages,
calculatePagesHeight: calculatePagesHeight,
keyboard: keyboard,
showGray: showGray,
scrollState: scrollState,
keyScroll: {
state: keyScroll,
reset: () => setKeyScroll({
up: 0,
down: 0,
scrollPosition: ''
})
},
currentScrollIndex: {
state: currentScrollIndex,
set: setCurrentScrollIndex
},
renderedCallback: renderedCallback,
onCtrlF: onCtrlF,
isModal: isModalMode,
styles: styles
});
})))));
}
const ListBoxInlineMemoed = React.memo(ListBoxInline);
function IsolateUseLayoutWrapper(_ref5) {
let {
options = {}
} = _ref5;
const {
model
} = options;
const [layout] = useLayout$1(model);
return /*#__PURE__*/React.createElement(ListBoxInlineMemoed, {
options: options,
layout: layout
});
}
function useExistingModel(_ref) {
let {
app,
qId,
options = {}
} = _ref;
const [model, setModel] = reactExports.useState();
const [modelStore] = useModelStore();
const {
sessionModel
} = options;
const forbiddenOptions = ['dense', 'frequencyMode', 'checkboxes', 'histogram', 'title', 'stateName', 'listLayout'];
const usedOptions = Object.keys(options);
const usedForbiddenOptions = usedOptions.filter(usedOption => forbiddenOptions.includes(usedOption));
if (usedForbiddenOptions.length) {
throw new Error("Option \"".concat(usedForbiddenOptions.join(', '), "\" is not applicable for existing objects."));
}
reactExports.useEffect(() => {
let isCleaned = false;
let cleanupFn = () => {};
async function fetchObject(modelId) {
const m = modelStore.get(modelId) || (await app.getObject(modelId));
return m;
}
async function fetchModel() {
const m = await Promise.resolve(sessionModel || fetchObject(qId));
if (isCleaned) {
return;
}
if (!modelStore.get(m.id)) {
modelStore.set(m.id, m);
const onClosed = () => {
modelStore.clear(m.id);
};
m.once('closed', onClosed);
cleanupFn = () => {
m.removeListener('closed', onClosed);
};
}
setModel(m);
}
fetchModel();
return () => {
isCleaned = true;
cleanupFn();
};
}, []);
return model;
}
/**
* see: https://qlik.dev/apis/json-rpc/qix/schemas#%23%2Fdefinitions%2Fschemas%2Fentries%2FValueExpression
* @name ValueExpression
* @type object
* @property {string} qValueExpression.qExpr
*/
/**
* Extends `ListObjectDef`, see Engine API: `ListObjectDef`.
* @interface ListObjectDef
* @extends qix.ListObjectDef
* @property {boolean} [frequencyEnabled=false] Show frequency count. also requires qListObjectDef.qFrequencyMode to be set
*/
/**
* @name ListboxProperties
* @type object
*/
/**
* @lends ListboxProperties
*/
const listdef = {
qInfo: {
qType: 'njsListbox'
},
/**
* @type {ListObjectDef}
*/
qListObjectDef: {
qStateName: '',
qShowAlternatives: true,
frequencyEnabled: false,
qFrequencyMode: 'N',
qInitialDataFetch: [{
qTop: 0,
qLeft: 0,
qWidth: 0,
qHeight: 0
}],
qDef: {
qSortCriterias: [{
qSortByState: 1,
qSortByAscii: 1,
qSortByNumeric: 1,
qSortByLoadOrder: 1
}]
}
},
/**
* Show histogram bar.
* also requires (qListObjectDef.qFrequencyMode 'V' and frequencyMax) or qListObjectDef.qFrequencyMode 'P'
* @type {boolean=}
* @default
*/
histogram: false,
/**
* frequencyMax calculation
* needed for histogram when not using qListObjectDef.qFrequencyMode: 'P'
* use an expression in the form `Max(AGGR(Count([field]), [field]))` (when needed)
* or 'fetch' that triggers an extra engine call but needed for library dimension that could change field when using the object
* @type {('fetch' | ValueExpression)=}
*/
frequencyMax: undefined,
/**
* Show values as checkboxes instead of as fields.
* @type {boolean=}
* @default
*/
checkboxes: false,
/**
* Enables search.
* @type {boolean=}
* @default
*/
searchEnabled: true,
/**
* Show title.
* @type {boolean=}
* @default
*/
showTitle: true,
/**
* Pre-fill search input field with wildcard characters.
* @type {boolean=}
* @default
*/
wildCardSearch: false,
/**
* Automatically confirm selections when clicking outside a listbox, without showing the selections toolbar.
* @type {boolean=}
* @default
*/
autoConfirm: false,
/**
* Layout settings.
* @type {object=}
*/
layoutOptions: {
/**
* Dense mode.
* @type {boolean=}
* @default
*/
dense: false,
/**
* Layout mode.
* @type {('singleColumn' | 'grid')=}
* @default
*/
dataLayout: 'singleColumn',
/**
* Layout order.
* Only used when dataLayout is 'grid'
* @type {('row' | 'column')=}
* @default
*/
layoutOrder: 'row',
/**
* Max visible columns.
* Only used when dataLayout is 'grid'
* and layoutOrder is 'row'
* @type {object=}
*/
maxVisibleColumns: {
/**
* Automatically fit as many columns as possible.
* Only used when dataLayout is 'grid'
* and layoutOrder is 'row'
* @type {boolean=}
* @default
*/
auto: true,
/**
* Fixed number of max visible columns.
* Only used when dataLayout is 'grid'
* layoutOrder is 'row'
* and auto is false
* @type {number=}
* @default
*/
maxColumns: 3
},
/**
* Max visible rows.
* Only used when dataLayout is 'grid'
* and layoutOrder is 'column'
* @type {object=}
*/
maxVisibleRows: {
/**
* Automatically fits as many rows as possible.
* Only used when dataLayout is 'grid'
* and layoutOrder is 'column'
* @type {boolean=}
* @default
*/
auto: true,
/**
* Fixed number of max visible rows.
* Only used when dataLayout is 'grid'
* layoutOrder is 'column'
* and auto is false
* @type {number=}
* @default
*/
maxRows: 3
}
},
/**
* Listbox title
* @type {string=}
* @default
*/
title: ''
};
function useOnTheFlyModel(_ref) {
var _options$title;
let {
app,
fieldIdentifier,
stateName,
options = {}
} = _ref;
const [fieldDef, setFieldDef] = reactExports.useState('');
const [isFetching, setIsFetching] = reactExports.useState(true);
const [model, setModel] = reactExports.useState();
const [fallbackTitle, setFallbackTitle] = reactExports.useState();
const title = (_options$title = options.title) !== null && _options$title !== void 0 ? _options$title : fallbackTitle;
let {
histogram = false,
frequencyMode = 'N'
} = options;
if (fieldDef && fieldDef.failedToFetchFieldDef) {
histogram = false;
frequencyMode = 'N';
}
reactExports.useEffect(() => {
async function fetchMasterItem() {
try {
const dim = await app.getDimension(fieldIdentifier.qLibraryId);
const dimLayout = await dim.getLayout();
setFallbackTitle(dimLayout.qDim.title);
if (dimLayout.qDim.qGrouping === 'N') {
setFieldDef(dimLayout.qDim.qFieldDefs ? dimLayout.qDim.qFieldDefs[0] : '');
} else {
setFieldDef({
multiFieldDim: true
});
}
setIsFetching(false);
} catch (e) {
setIsFetching(false);
setFieldDef({
failedToFetchFieldDef: true
});
throw new Error("Disabling frequency count and histogram: ".concat(e && e.message));
}
}
const isFrequencyMaxNeeded = histogram || frequencyMode !== 'N';
const shouldFetchMasterItem = fieldIdentifier.qLibraryId && isFrequencyMaxNeeded;
if (shouldFetchMasterItem) {
fetchMasterItem();
} else {
setIsFetching(false);
setFallbackTitle(fieldIdentifier);
}
}, []);
const {
dense,
checkboxes,
listLayout,
properties = {}
} = options;
const getListdefFrequencyMode = () => histogram && frequencyMode === 'N' ? 'V' : frequencyMode;
const layoutOptions = {
dense
};
if (listLayout === 'horizontal') {
layoutOptions.dataLayout = 'grid';
layoutOptions.layoutOrder = 'column';
layoutOptions.maxVisibleColumns = {
auto: true
};
layoutOptions.maxVisibleRows = {
auto: false,
maxRows: 1
};
}
const id = reactExports.useRef();
if (!id.current) {
id.current = uid$1();
}
const listdef$1 = originalExtend(true, {}, listdef, {
qInfo: {
qId: id.current
},
qListObjectDef: {
qStateName: stateName,
qFrequencyMode: getListdefFrequencyMode()
},
histogram,
checkboxes,
layoutOptions,
title
});
originalExtend(true, listdef$1, properties);
// Something something lib dimension
let fieldName;
if (fieldIdentifier.qLibraryId) {
listdef$1.qListObjectDef.qLibraryId = fieldIdentifier.qLibraryId;
fieldName = fieldIdentifier.qLibraryId;
} else {
listdef$1.qListObjectDef.qDef.qFieldDefs = [fieldIdentifier];
fieldName = fieldIdentifier;
}
if (frequencyMode !== 'P' && histogram) {
if (fieldDef !== null && fieldDef !== void 0 && fieldDef.multiFieldDim) {
listdef$1.frequencyMax = 'fetch';
// maybe for all lib dimension to handle if it properties change
} else {
const field = fieldIdentifier.qLibraryId ? fieldDef : fieldName;
listdef$1.frequencyMax = {
qValueExpression: getFrequencyMaxExpression(field)
};
}
}
const [sessionModel] = useSessionModel(listdef$1, isFetching ? null : app, fieldName, stateName);
reactExports.useEffect(() => {
if (!sessionModel) {
return;
}
setModel(sessionModel);
}, [sessionModel]);
return model;
}
function identify(_ref) {
let {
qId,
options
} = _ref;
return {
// External or internal ("on the fly") session model.
isExistingObject: !!(qId || options.sessionModel),
// External or internal selectionsApi.
hasExternalSelectionsApi: !!options.selectionsApi
};
}
function getFrequencyModeLetter(frequencyMode) {
let freqLetter;
switch (true) {
case ['none', 'N', 'NX_FREQUENCY_NONE'].includes(frequencyMode):
freqLetter = 'N';
break;
case ['value', 'V', 'NX_FREQUENCY_VALUE', 'default'].includes(frequencyMode):
freqLetter = 'V';
break;
case ['percent', 'P', 'NX_FREQUENCY_PERCENT'].includes(frequencyMode):
freqLetter = 'P';
break;
case ['relative', 'R', 'NX_FREQUENCY_RELATIVE'].includes(frequencyMode):
freqLetter = 'R';
break;
default:
freqLetter = 'N';
break;
}
return freqLetter;
}
const _excluded$3 = ["__DO_NOT_USE__"];
/**
* @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 {boolean=} [options.calculatePagesHeight=false] Override each page's qHeight with its actual row count.
* @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 {function():object[]} [options.postProcessPages] A function for client-side post-processing of returned pages.
* @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 {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$1 = function () {
let usersOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
__DO_NOT_USE__ = {}
} = usersOptions,
exposedOptions = _objectWithoutProperties(usersOptions, _excluded$3);
const DO_NOT_USE_DEFAULTS = {
update: undefined,
fetchStart: undefined,
showGray: true,
focusSearch: false,
sessionModel: undefined,
selectionsApi: undefined,
selectDisabled: undefined,
postProcessPages: undefined,
calculatePagesHeight: false
};
const squashedOptions = _objectSpread2(_objectSpread2(_objectSpread2({}, exposedOptions), DO_NOT_USE_DEFAULTS), __DO_NOT_USE__);
return squashedOptions;
};
const ListBoxWrapper = reactExports.forwardRef((_ref, ref) => {
let {
app,
fieldIdentifier,
qId,
stateName,
element,
initialOptions,
renderedCallback
} = _ref;
const [options, setOptions] = reactExports.useState(initialOptions);
const {
isExistingObject,
hasExternalSelectionsApi
} = identify({
qId,
options
});
if (!isExistingObject) {
Object.assign(options, {
frequencyMode: getFrequencyModeLetter(options.frequencyMode) // stick to letter option hereafter
});
}
const [changeCount, setChangeCount] = reactExports.useState(0);
reactExports.useEffect(() => {
if (changeCount) {
throw new Error('Source or selection Api can not change after a listbox has been mounted');
}
setChangeCount(changeCount + 1);
}, [isExistingObject, hasExternalSelectionsApi]);
const model = isExistingObject ? useExistingModel({
app,
qId,
options
}) : useOnTheFlyModel({
app,
fieldIdentifier,
stateName,
options
});
const elementRef = reactExports.useRef(element);
const selections = hasExternalSelectionsApi ? options.selectionsApi : useObjectSelections(app, model, [elementRef, '.njs-action-toolbar-more', '.njs-action-toolbar-popover'], options)[0];
const opts = reactExports.useMemo(() => _objectSpread2(_objectSpread2({}, options), {}, {
selections,
model,
app,
renderedCallback
}), [options, selections, model, app]);
reactExports.useImperativeHandle(ref, () => ({
setOptions: newOptions => setOptions(newOptions)
}), []);
if (!selections || !model) {
return null;
}
return /*#__PURE__*/React.createElement(IsolateUseLayoutWrapper, {
options: opts
});
});
function ListBoxPortal(_ref2) {
let {
element,
app,
fieldIdentifier,
qId,
stateName = '$',
options = {},
renderedCallback
} = _ref2;
const listRef = React.createRef();
const portal = ReactDOM.createPortal(/*#__PURE__*/React.createElement(ListBoxWrapper, {
ref: listRef,
app: app,
element: element,
fieldIdentifier: fieldIdentifier,
qId: qId,
stateName: stateName,
initialOptions: options,
renderedCallback: renderedCallback
}), element, uid$1());
return [portal, listRef];
}
const DEFAULTS = {
show: true,
anchorOrigin: {
vertical: 'bottom',
horizontal: 'center'
},
transformOrigin: {
vertical: 'top',
horizontal: 'center'
}
};
const getOptions = function () {
let usersOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const squashedOptions = _objectSpread2({}, DEFAULTS);
originalExtend(true, squashedOptions, usersOptions);
return squashedOptions;
};
function ListBoxPopoverWrapper(_ref) {
let {
app,
fieldIdentifier,
stateName,
element,
options = {}
} = _ref;
const [showState, setShowstate] = reactExports.useState(!!options.show);
const handleCloseShowState = () => {
setShowstate(false);
if (options.onPopoverClose) {
options.onPopoverClose();
}
};
return /*#__PURE__*/React.createElement(ListBoxPopover, {
show: showState,
app: app,
alignTo: {
current: element
},
anchorOrigin: options.anchorOrigin,
transformOrigin: options.transformOrigin,
close: handleCloseShowState,
fieldName: fieldIdentifier,
stateName: stateName,
autoFocus: options.autoFocus,
components: options.components,
sortCriteria: options.sortCriteria,
direction: options.direction
});
}
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$2 = 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$2(d) : _objectSpread2(_objectSpread2({}, d), {}, {
qDef: d.qDef || {}
});
dimension.qDef.cId = dimension.qDef.cId || uid$1();
// ====== 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);
}
return dimension;
},
removeDimension(idx) {
const dimension = hc.qDimensions.splice(idx, 1)[0];
removeIndex(hc.qInterColumnSortOrder, idx);
def.dimensions.removed(dimension, objectProperties, idx);
return dimension;
},
addMeasure(m) {
const measure = typeof m === 'string' ? nxMeasure(m) : _objectSpread2(_objectSpread2({}, m), {}, {
qDef: m.qDef || {}
});
measure.qDef.cId = measure.qDef.cId || uid$1();
// ====== 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;
}
const nxDimension$1 = f => ({
qDef: {
qFieldDefs: [f]
}
});
function loHandler(_ref) {
let {
dc: lo,
def,
properties
} = _ref;
lo.qInitialDataFetch = lo.qInitialDataFetch || [];
const objectProperties = properties;
const handler = {
dimensions() {
if (!lo.qLibraryId && (!lo.qDef || !lo.qDef.qFieldDefs || lo.qDef.qFieldDefs.length === 0)) return [];
return [lo];
},
measures() {
return [];
},
addDimension(d) {
const dimension = typeof d === 'string' ? nxDimension$1(d) : _objectSpread2(_objectSpread2({}, d), {}, {
qDef: d.qDef || {}
});
dimension.qDef.cId = dimension.qDef.cId || uid$1();
dimension.qDef.qSortCriterias = lo.qDef.qSortCriterias || [{
qSortByState: 1,
qSortByLoadOrder: 1,
qSortByNumeric: 1,
qSortByAscii: 1
}];
Object.keys(dimension).forEach(k => {
lo[k] = dimension[k];
});
def.dimensions.added(dimension, objectProperties);
return dimension;
},
removeDimension(idx) {
const dimension = lo;
delete lo.qDef;
delete lo.qLibraryId;
def.dimensions.removed(dimension, objectProperties, idx);
return dimension;
},
addMeasure() {},
removeMeasure() {},
maxDimensions() {
return 1;
},
maxMeasures() {
return 0;
},
canAddDimension() {
return handler.dimensions().length === 0;
},
canAddMeasure() {
return false;
}
};
return handler;
}
const nxDimension = f => ({
qDef: {
qFieldDefs: [f]
}
});
const toListBox = d => {
let listboxProps;
if (typeof d === 'string') {
listboxProps = originalExtend(true, {}, listdef, {
qListObjectDef: nxDimension(d)
});
} else if (d.qListObjectDef) {
listboxProps = originalExtend(true, {}, listdef, d);
} else {
listboxProps = originalExtend(true, {}, listdef, {
qListObjectDef: d
});
}
return listboxProps;
};
function filterpaneHandler(_ref) {
let {
/* dc, def, properties, */children,
halo
} = _ref;
const handler = {
async addDimension(d) {
const listboxProps = toListBox(d);
const dimension = listboxProps.qListObjectDef;
dimension.qDef.cId = dimension.qDef.cId || uid$1(); // maybe not needed
if (!listboxProps.title) {
if (dimension.qLibraryId) {
const dimModel = await halo.app.getDimension(dimension.qLibraryId);
const dimProps = await dimModel.getProperties();
if (dimProps.qDim.qLabelExpression) {
listboxProps.title = {
qStringExpression: {
qExpr: dimProps.qDim.qLabelExpression
}
};
} else {
listboxProps.title = dimProps.qDim.title;
}
} else {
var _dimension$qDef$qFiel, _dimension$qDef$qFiel2;
listboxProps.title = dimension.qDef.title || ((_dimension$qDef$qFiel = dimension.qDef.qFieldLabels) === null || _dimension$qDef$qFiel === void 0 ? void 0 : _dimension$qDef$qFiel[0]) || ((_dimension$qDef$qFiel2 = dimension.qDef.qFieldDefs) === null || _dimension$qDef$qFiel2 === void 0 ? void 0 : _dimension$qDef$qFiel2[0]);
}
}
// def.dimensions.added(dimension, properties, listboxProps);
children.push({
qProperty: listboxProps,
qChildren: []
});
},
addMeasure() {}
};
return handler;
}
function getCreateHandler(propertyPath) {
if (propertyPath.match('/qListObjectDef')) {
return loHandler;
}
if (propertyPath.match('/qChildListDef')) {
return filterpaneHandler;
}
return hcHandler;
}
/**
* @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';
}
async function populateData(_ref, halo) {
let {
sn,
properties,
fields,
children
} = _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 createHandler = getCreateHandler(propertyPath);
const handler = createHandler({
dc: p,
def: target,
properties,
children,
halo
});
for (let i = 0; i < fields.length; ++i) {
const f = fields[i];
const type = fieldType(f);
if (type === 'measure') {
// eslint-disable-next-line no-await-in-loop
await handler.addMeasure(f);
} else {
// eslint-disable-next-line no-await-in-loop
await handler.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 {qix.NxDimension[]} dimensions
* @property {qix.NxMeasure[]} measures
* @property {qix.NxDimension[]} excludedDimensions
* @property {qix.NxMeasure[]} 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;
}
/**
* Move an element from position old_index to position new_index in
* the array.
* @param array
* @param oldIndex
* @param newIndex
*/
function move(array, oldIndex, newIndex) {
if (newIndex < 0) throw Error('newIndex cannot be a negative value!');
if (newIndex >= array.length) {
let k = newIndex - array.length + 1;
while (k) {
array.push(undefined);
k--;
}
}
const movingValue = array.at(oldIndex);
array.splice(oldIndex, 1);
array.splice(newIndex, 0, movingValue);
}
var arrayUtil = {
isOrderedSubset,
indexAdded,
indexRemoved,
move
};
/* eslint-disable no-prototype-builtins */
/* eslint-disable no-param-reassign */
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 = originalExtend(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 originalExtend(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) {
arrayUtil.indexAdded(newHyperCubeDef.qInterColumnSortOrder, i);
++i;
} else {
--i;
arrayUtil.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 = originalExtend(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 = originalExtend(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 (arrayUtil.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 */
/* eslint-disable no-prototype-builtins */
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,
properties,
viewDataMode = false
} = _ref2;
const propertyTree = properties ? {
qProperty: properties
} : await model.getFullPropertyTree();
const sourceQae = cellRef.current.getQae();
const exportProperties = getExportPropertiesFnc(sourceQae);
if (!exportProperties) {
throw new Error('Source chart does not support conversion');
}
const targetSnType = await getType$1({
halo,
name: newType
});
const targetQae = targetSnType.qae;
const importProperties = getImportPropertiesFnc(targetQae);
if (!importProperties) {
throw new Error('Target chart does not support conversion');
}
const exportFormat = exportProperties({
propertyTree,
hypercubePath: helpers.getHypercubePath(sourceQae),
viewDataMode
});
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),
viewDataMode
});
return newPropertyTree;
};
/**
* @interface ConversionType
* @since 1.1.0
* @property {importProperties} importProperties
* @property {exportProperties} exportProperties
*/
/**
* @entry
* @namespace
* @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 = exports("d", {
/**
* @type {hyperCubeConversion}
* @since 1.1.0
* @description Provides conversion functionality to extensions with hyperCubes.
*/
hypercube
});
/* eslint no-param-reassign: 0, no-restricted-globals: 0 */
const extend = originalExtend.bind(null, true);
const JSONPatch = {};
const {
isArray
} = Array;
function isObject$1(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$1(a) && isObject$1(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$1(val) && isObject$1(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$1(target) && isObject$1(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(EventEmitter.prototype).forEach(key => {
obj[key] = EventEmitter.prototype[key];
});
EventEmitter.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: [],
menus: [],
actions: {
list: []
},
pendingEffects: [],
pendingLayoutEffects: [],
pendingPromises: [],
resizer: {
setters: [],
explicitResize
},
accessibility: {
setter: null
},
contraintsWarning: true
};
}
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 runMenu(component, menu, event, menuBuilder) {
try {
return Promise.all(component.__hooks.menus.map(h => Promise.resolve(h.fn(menu, event, menuBuilder)))).then(menus => menus[menus.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,
runMenu,
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;
}
/**
* Callback function that should return a function that in turns gets
* called before the hook runs again or when the component is destroyed.
* For example to remove any listeners added in the callback itself.
* @typedef {function():(void | function():void)} EffectCallback
*/
/**
* Triggers a callback function when a dependent value changes.
*
* Omitting the dependency array will have the hook run on each update
* and an empty dependency array runs only once.
* @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');
* };
* }, []);
*
* useEffect(() => {
* const clickHandler = () => { console.log('click') };
* const button = element.querySelector('.button');
* button.addEventListener('click', clickHandler);
* return () => {
* button.removeEventListener('click', clickHandler);
* };
* }, []);
*/
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];
}
/**
* Reference object returned from useRef
* @interface Ref
* @template R
* @property {R} current Current value
*/
/**
* Creates a reference to a value not needed for rendering
*
* While Nebula does not have a virtual DOM, it is still useful
* to have a reference to an object that is retained across
* renders and in it self does not trigger a render.
* @entry
* @template R
* @param {R} initialValue - The initial value.
* @returns {Ref<R>} An object with the current value
* @example
* import { useRef } from '@nebula.js/stardust';
* // ...
* // initiate with simple value
* const timesRendered = useRef(0);
*
* useEffect(() => {
* render(layout);
* // increments the render counter, a useState would trigger another render
* timesRendered.current += 1;
* },[layout]);
*
*/
function useRef(initialValue) {
return useMemo(() => ({
current: initialValue
}), []);
}
/**
* Runs a callback function when a dependent changes.
*
* Useful for async operations that otherwise cause no side effects.
* Do not add for example listeners withing the callback as there is no teardown function.
* @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 or rejected error
* @example
* import { usePromise } from '@nebula.js/stardust';
* import { useModel } from '@nebula.js/stardust';
* // ...
* const model = useModel();
* const [resolved, rejected] = usePromise(() => model.getLayout(), [model]);
*/
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 {qix.GenericObjectLayout}
* @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 {qix.GenericObjectLayout}
* @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 {qix.NxAppLayout} 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 {qix.GenericObject|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 {qix.Doc|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 {qix.Global|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.getContrastingColorTo('#ff0000'));
*/
function useTheme() {
return useInternalContext('theme');
}
/**
* Gets the embed instance used.
* @entry
* @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 navigation api to control sheet navigation. When useNavigation is used in Sense, it returns Sense.navigation.
* @entry
* @experimental
* @since 5.4.0
* @returns {Navigation} navigation api.
* @example
* import { useNavigation } from "@nebula.js/stardust";
* // ...
* const navigation = useNavigation();
* const [activeSheetId, setActiveSheetId] = useState(navigation?.getCurrentSheetId() || "");
*/
function useNavigation() {
return useInternalContext('navigation');
}
/**
* 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
* @deprecated Use Interactions instead
* @property {boolean=} passive=false Whether or not passive constraints are on. Should block any passive interaction by users, ie: tooltips
* @property {boolean=} active=false Whether or not active constraints are on. Should block any active interaction by users, ie: scroll, click
* @property {boolean=} select=false Whether or not select constraints are on. Should block any selection action. Implied when active is true.
* @property {boolean=} edit=true Whether or not edit actions are available. Should block any edit action.
*/
/**
* 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 be respected when implementing the visualization.
* @entry
* @deprecated Change to useInteractions instead
* @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() {
{
if (currentComponent.__hooks.contraintsWarning) {
// eslint-disable-next-line no-console
console.warn('useContraints has been deprecated, please change to useInteractions instead. Note that interactions uses inverted values compared to contraints.');
currentComponent.__hooks.contraintsWarning = false;
}
}
return useInternalContext('constraints');
}
/**
* @interface Interactions
* @property {boolean=} passive=true Whether or not passive interactions are on. Allows passive interaction by users, ie: tooltips
* @property {boolean=} active=true Whether or not active interactions are on. Allows active interaction by users, ie: scroll, click
* @property {boolean=} select=true Whether or not select interactions are on. Allows selection actions. Implied when active is false.
* @property {boolean=} edit=false Whether or not edit actions are on. Allows edit actions.
*/
/**
* Gets the desired interaction states that should be applied when rendering the visualization.
*
* The interactions are set on the embed configuration before the visualization is rendered
* and should be respected when implementing the visualization.
* @entry
* @returns {Interactions}
* @example
* // configure embed to disallow active interactions when rendering
* embed(app, {
* context: {
* interactions: {
* active: false, // do not allow interactions
* }
* }
* }).render({ element, id: 'sdfsdf' });
*
* @example
* import { useInteractionState } from '@nebula.js/stardust';
* // ...
* const interactions = useInteractionState();
* useEffect(() => {
* if (!interactions.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);
* };
* }, [interactions])
*
*/
function useInteractionState() {
return useInternalContext('interactions');
}
/**
* 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');
}
/**
* 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
* @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(qix.GenericObjectLayout): Promise<qix.GenericObjectLayout>} 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;
}
/**
* Registers a callback that is called when the context menu opens
* @entry
* @param {function(menu, event): void} addItemCallback
* @ignore
* @example
* import { onContextMenu } from '@nebula.js/stardust';
* onContextMenu((menu, event) => {
* menu.addItem(item, index);
* });
*/
function onContextMenu(cb) {
const h = getHook(++currentIndex);
if (!h.value) {
h.value = 1;
currentComponent.__hooks.menus.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
* @returns {RenderState} The render state.
* @example
* import { useRenderState } from '@nebula.js/stardust';
*
* const renderState = useRenderState();
* useState(() => {
* if(needPropertiesUpdate(...)) {
* useRenderState.pending();
* updateProperties(...);
* } else {
* useRenderState.restore();
* ...
* }
* }, [...]);
*/
function useRenderState() {
getHook(++currentIndex);
const hooks = currentComponent.__hooks;
return {
pending: () => {
hooks.waitForData = true;
},
restore: () => {
hooks.waitForData = false;
}
};
}
/**
* @class Emitter
* @description The emitter instance. Implements https://nodejs.org/api/events.html#class-eventemitter.
*/
/**
* Gets an event emitter instance for the visualization.
* @entry
* @returns {Emitter}
* @example
* // In a Nebula visualization
* import { useEmitter } from '@nebula.js/stardust';
* useEffect(()=> {
* // on some trigger
* emitter.emit("trigger", params)
* }, [...])
*
* // In a mashup
* const viz = await n.render({
* element: el,
* id: 'abcdef'
* });
* viz.addListener("trigger", ()=> {
* // do something
* })
*/
function useEmitter() {
return useInternalContext('emitter');
}
/**
* @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(boolean)=} blur Function used by the visualization to tell Nebula it wants to relinquish focus
* @property {function=} focus Function used by the visualization to tell Nebula it wants to focus
* @property {function(boolean)=} focusSelection Function used by the visualization to tell Nebula that 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 () {
let resetFocus = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
const acc = this.__hooks.accessibility;
if (acc && 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 && acc.enabled && !acc.active) {
focusHandler && focusHandler.blurCallback && focusHandler.blurCallback(false);
focus(this);
}
}.bind(currentComponent);
currentComponent.__hooks.accessibility.focusFunction = focusFunction;
const focusSelectionFunction = function () {
let focusLast = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
const acc = this.__hooks.accessibility;
if (acc && 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(EventEmitter.prototype).forEach(key => {
obj[key] = EventEmitter.prototype[key];
});
EventEmitter.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', 'interactions'];
const forcedConstraints = {};
const forcedInteractions = {};
// select should be a constraint when a real model is not available
if (!opts.model || !opts.model.session) {
forcedConstraints.select = true;
forcedConstraints.edit = true;
forcedInteractions.select = false;
forcedInteractions.edit = false;
}
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
emitter: opts.emitter,
// ---- singletons ----
deviceType: galaxy.deviceType,
theme: undefined,
translator: galaxy.translator,
navigation: opts.navigation,
// --- dynamic values ---
layout: {},
appLayout: {},
keyboardNavigation: opts.keyboardNavigation,
externalFocusManagement: opts.externalFocusManagement || false,
focusHandler: opts.focusHandler,
constraints: forcedConstraints,
interactions: forcedInteractions,
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 (key === 'interactions') {
s = JSON.stringify(_objectSpread2(_objectSpread2({}, ref[key]), forcedInteractions));
}
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);
},
onContextMenu(menu, event, menuBuilder) {
return generator.component.runMenu(this, menu, event, menuBuilder);
},
focus() {
const ref = generator.component.getImperativeHandle(this);
if (ref && typeof ref.focus === 'function') {
ref.focus();
return;
}
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];
}
// try/catch here to guard against charts not checking properties correctly
try {
generator.qae.properties.onChange.call({
model: opts.model
}, ...args);
} catch (_unused) {
{
console.warn('Error in chart setProperties interceptor onChange call '); // eslint-disable-line no-console
}
}
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);
try {
generator.qae.properties.onChange.call({
model: opts.model
}, currentProperties);
} catch (_unused2) {
{
console.warn('Error in chart applyPatches interceptor onChange call '); // eslint-disable-line no-console
}
}
// 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 = () => {
if (opts.model.__snInterceptor) {
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 TOTAL_MAX = {
DIMENSIONS: 1000,
// Maximum number of active dimensions + disabled dimensions
MEASURES: 1000 // Maximum number of active measures + disabled measures
};
const AUTOCALENDAR_NAME = '.autoCalendar';
const INITIAL_SORT_CRITERIAS = [{
qSortByLoadOrder: 1,
qSortByNumeric: 1,
qSortByAscii: 1
}];
const uid = () => {
const idGen = [[10, 31], [0, 31], [0, 31], [0, 31], [0, 31], [0, 31]];
const toChar = _ref => {
let [min, max] = _ref;
return min + (Math.random() * (max - min) | 0).toString(32);
};
return idGen.map(toChar).join('');
};
const getField = expression => {
let exp = expression;
exp = exp.trim();
if (exp.charAt(0) === '=') {
exp = exp.substring(1);
exp = exp.trim();
}
const lastIndex = exp.length - 1;
if (exp.charAt(0) === '[' && exp.charAt(lastIndex) === ']') {
exp = exp.substring(1, lastIndex);
exp = exp.trim();
}
return exp;
};
const findFieldById = (fields, id) => fields && fields.find(field => {
var _field$qDef;
return ((_field$qDef = field.qDef) === null || _field$qDef === void 0 ? void 0 : _field$qDef.cId) === id;
}) || null;
const findLibraryItem = (id, masterItemList) => masterItemList && masterItemList.find(item => item.qInfo.qId === id) || null;
const findFieldByName = (name, fieldList) => fieldList && fieldList.find(field => field.qName === name) || null;
const initializeId = field => {
var _field$qDef$cId, _field$qDef2;
return _objectSpread2(_objectSpread2({}, field), {}, {
qDef: _objectSpread2(_objectSpread2({}, field.qDef), {}, {
cId: (_field$qDef$cId = (_field$qDef2 = field.qDef) === null || _field$qDef2 === void 0 ? void 0 : _field$qDef2.cId) !== null && _field$qDef$cId !== void 0 ? _field$qDef$cId : uid()
})
});
};
const initializeDim = field => {
var _field$qOtherTotalSpe;
return _objectSpread2(_objectSpread2({}, initializeId(field)), {}, {
qOtherTotalSpec: (_field$qOtherTotalSpe = field.qOtherTotalSpec) !== null && _field$qOtherTotalSpe !== void 0 ? _field$qOtherTotalSpe : {}
});
};
const setAutoSort = (fields, dimension, self) => {
const dim = dimension;
fields.forEach((field, index) => {
const tags = field.qTags;
const sortCriterias = {
qSortByLoadOrder: 1
};
if (typeof self.dimensionDefinition.autoSort === 'function') {
self.dimensionDefinition.autoSort(dim, self.properties, tags, sortCriterias, self);
} else {
// Default auto sorting
sortCriterias.qSortByNumeric = 1;
sortCriterias.qSortByAscii = 1;
}
if (!dim.qDef.qSortCriterias) {
dim.qDef.qSortCriterias = [sortCriterias];
} else {
dim.qDef.qSortCriterias[index] = sortCriterias;
}
});
};
const isDateField = field => {
var _field$qTags, _field$qTags2;
return (field === null || field === void 0 ? void 0 : field.qDerivedFieldData) && ((field === null || field === void 0 || (_field$qTags = field.qTags) === null || _field$qTags === void 0 ? void 0 : _field$qTags.indexOf('$date')) > -1 || (field === null || field === void 0 || (_field$qTags2 = field.qTags) === null || _field$qTags2 === void 0 ? void 0 : _field$qTags2.indexOf('$timestamp')) > -1);
};
const isGeoField = field => field.qTags.indexOf('$geoname') > -1;
const trimAutoCalendarName = fieldName => fieldName ? fieldName.split(AUTOCALENDAR_NAME).join('') : '';
const useMasterNumberFormat = formatting => {
const format = formatting;
format.quarantine = {
qNumFormat: format.qNumFormat || {},
isCustomFormatted: format.isCustomFormatted || false
};
format.qNumFormat = null;
format.isCustomFormatted = undefined;
};
const notSupportedError = new Error('Not supported in this object, need to implement in subclass.');
const setFieldProperties = hcFieldProperties => {
if (!hcFieldProperties) {
return [];
}
const updatedProperties = [...hcFieldProperties];
return updatedProperties.map(field => {
var _field$qDef;
if ((_field$qDef = field.qDef) !== null && _field$qDef !== void 0 && _field$qDef.autoSort && field.autoSort !== undefined) {
return _objectSpread2(_objectSpread2({}, field), {}, {
qDef: _objectSpread2(_objectSpread2({}, field.qDef), {}, {
autoSort: field.autoSort
}),
autoSort: undefined
});
}
return field;
});
};
const getHyperCube = (layout, path) => {
if (!layout) {
return undefined;
}
return path && utils.getValue(layout, path) ? utils.getValue(layout, path).qHyperCube : layout.qHyperCube;
};
function setDefaultProperties(self) {
var _current$getDimension, _current$getMeasures, _current$hcProperties, _current$hcProperties2, _current$hcProperties3, _current$getAlternati, _current$getAlternati2;
const current = self;
current.hcProperties.qDimensions = (_current$getDimension = current.getDimensions()) !== null && _current$getDimension !== void 0 ? _current$getDimension : [];
current.hcProperties.qMeasures = (_current$getMeasures = current.getMeasures()) !== null && _current$getMeasures !== void 0 ? _current$getMeasures : [];
current.hcProperties.qInterColumnSortOrder = (_current$hcProperties = current.hcProperties.qInterColumnSortOrder) !== null && _current$hcProperties !== void 0 ? _current$hcProperties : [];
current.hcProperties.qLayoutExclude = (_current$hcProperties2 = current.hcProperties.qLayoutExclude) !== null && _current$hcProperties2 !== void 0 ? _current$hcProperties2 : {
qHyperCubeDef: {
qDimensions: [],
qMeasures: []
}
};
current.hcProperties.qLayoutExclude.qHyperCubeDef = (_current$hcProperties3 = current.hcProperties.qLayoutExclude.qHyperCubeDef) !== null && _current$hcProperties3 !== void 0 ? _current$hcProperties3 : {
qDimensions: [],
qMeasures: []
};
current.hcProperties.qLayoutExclude.qHyperCubeDef.qDimensions = (_current$getAlternati = current.getAlternativeDimensions()) !== null && _current$getAlternati !== void 0 ? _current$getAlternati : [];
current.hcProperties.qLayoutExclude.qHyperCubeDef.qMeasures = (_current$getAlternati2 = current.getAlternativeMeasures()) !== null && _current$getAlternati2 !== void 0 ? _current$getAlternati2 : [];
}
function setPropForLineChartWithForecast(self) {
const current = self;
if (current.hcProperties.isHCEnabled && current.hcProperties.qDynamicScript.length === 0 && current.hcProperties.qMode === 'S') {
current.hcProperties.qDynamicScript = [];
}
}
function getDeletedFields(fields, indexes) {
// Keep the original deleted order
return fields.filter((_, idx) => indexes.includes(idx));
}
function getRemainedFields(fields, indexes) {
return fields.filter((_, idx) => !indexes.includes(idx));
}
// ----------------------------------
// ----------- DIMENSIONS -----------
// ----------------------------------
function addAlternativeDimension(self, dimension) {
let index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
const altDimensions = self.getAlternativeDimensions();
const idx = index !== null && index !== void 0 ? index : altDimensions.length;
altDimensions.splice(idx, 0, dimension);
return Promise.resolve(dimension);
}
function addDimensionToColumnSortOrder(self, dimensions, index) {
arrayUtil.indexAdded(self.hcProperties.qInterColumnSortOrder, index !== null && index !== void 0 ? index : dimensions.length - 1);
}
function addDimensionToColumnOrder(self, dimension) {
if (dimension && typeof self.dimensionDefinition.add === 'function') {
return Promise.resolve(self.dimensionDefinition.add.call(null, dimension, self.properties, self)).then(() => dimension);
}
return Promise.resolve(dimension);
}
function moveDimensionToColumnOrder(self, dimension) {
if (typeof self.dimensionDefinition.move === 'function') {
return Promise.resolve(self.dimensionDefinition.move.call(self, dimension, self.properties, self)).then(() => dimension);
}
return Promise.resolve(dimension);
}
function replaceDimensionOrder(self, index, dimension) {
if (!dimension) {
return undefined;
}
const dimensions = self.getDimensions();
const replacedDimension = dimensions[index];
const newDimension = _objectSpread2(_objectSpread2({}, dimension), {}, {
qDef: _objectSpread2(_objectSpread2({}, dimension.qDef), {}, {
cId: uid()
})
});
dimensions[index] = newDimension;
if (newDimension && typeof self.dimensionDefinition.replace === 'function') {
self.dimensionDefinition.replace.call(null, newDimension, replacedDimension, index, self.properties, self);
}
return newDimension;
}
function removeDimensionFromColumnSortOrder(self, index) {
arrayUtil.indexRemoved(self.hcProperties.qInterColumnSortOrder, index);
}
function removeDimensionFromColumnOrder(self, index) {
const [dimension] = self.getDimensions().splice(index, 1);
if (dimension && typeof self.dimensionDefinition.remove === 'function') {
return Promise.resolve(self.dimensionDefinition.remove.call(null, dimension, self.properties, self, index));
}
return Promise.resolve();
}
function isTotalDimensionsExceeded(self, dimensions) {
const altDimensions = self.getAlternativeDimensions();
return altDimensions.length + dimensions.length >= TOTAL_MAX.DIMENSIONS;
}
function isDimensionAlternative(self, alternative) {
const dimensions = self.getAlternativeDimensions();
return alternative || self.maxDimensions() <= dimensions.length && dimensions.length < TOTAL_MAX.DIMENSIONS;
}
async function addActiveDimension(self, dimension, initialLength, existingDimensions, addedDimensions, addedActive) {
await self.autoSortDimension(dimension);
// Update sorting order
arrayUtil.indexAdded(self.hcProperties.qInterColumnSortOrder, initialLength + addedActive);
existingDimensions.push(dimension);
addedDimensions.push(dimension);
if (typeof self.dimensionDefinition.add === 'function') {
self.dimensionDefinition.add.call(self, dimension, self.properties, self);
}
}
function moveDimensionFromMainToAlternative(fromIndex, toIndex, dimensions, altDimensions) {
const alternativeToIndex = toIndex - dimensions.length;
let [movingDimension] = altDimensions.splice(0, 1);
dimensions.push(movingDimension);
[movingDimension] = dimensions.splice(fromIndex, 1);
altDimensions.splice(alternativeToIndex, 0, movingDimension);
return Promise.resolve(movingDimension);
}
function moveDimensionWithinAlternative(fromIndex, toIndex, dimensions, altDimensions) {
const alternativeFromIdx = fromIndex - dimensions.length;
const alternativeToIndex = toIndex - dimensions.length;
arrayUtil.move(altDimensions, alternativeFromIdx, alternativeToIndex);
}
// ----------------------------------
// ------------ MEASURES ------------
// ----------------------------------
function addAlternativeMeasure(self, measure) {
let index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
const measures = self.getAlternativeMeasures();
const idx = index !== null && index !== void 0 ? index : measures.length;
measures.splice(idx, 0, measure);
return Promise.resolve(measure);
}
function addMeasureToColumnSortOrder(self, measures) {
arrayUtil.indexAdded(self.hcProperties.qInterColumnSortOrder, self.getDimensions().length + measures.length - 1);
}
function addMeasureToColumnOrder(self, measure) {
if (measure && typeof self.measureDefinition.add === 'function') {
return Promise.resolve(self.measureDefinition.add.call(null, measure, self.properties, self));
}
return Promise.resolve();
}
function moveMeasureColumnOrder(self, measure) {
if (typeof self.measureDefinition.move === 'function') {
return Promise.resolve(self.measureDefinition.move.call(null, measure, self.properties, self, true)).then(() => measure);
}
return Promise.resolve(measure);
}
function isTotalMeasureExceeded(self, measures) {
// Adding more measures than TOTAL_MAX_MEASURES is not allowed and we expect this.maxMeasures() to always be <= TOTAL_MAX_MEASURES
const altMeasures = self.getAlternativeMeasures();
return altMeasures.length + measures.length >= TOTAL_MAX.MEASURES;
}
function isMeasureAlternative(self, alternative) {
const measures = self.getMeasures();
return alternative || self.maxMeasures() <= measures.length && measures.length < TOTAL_MAX.MEASURES;
}
function addActiveMeasure(self, measure, existingMeasures, addedMeasures, addedActive) {
const dimensions = self.getDimensions();
const meas = _objectSpread2({}, measure);
meas.qSortBy = {
qSortByLoadOrder: 1,
qSortByNumeric: -1
};
arrayUtil.indexAdded(self.hcProperties.qInterColumnSortOrder, dimensions.length + existingMeasures.length + addedActive);
existingMeasures.push(meas);
addedMeasures.push(meas);
if (typeof self.measureDefinition.add === 'function') {
self.measureDefinition.add.call(null, meas, self.properties, self);
}
return Promise.resolve(addedMeasures);
}
function removeMeasureFromColumnSortOrder(self, index) {
arrayUtil.indexRemoved(self.hcProperties.qInterColumnSortOrder, self.getDimensions().length + index);
}
function removeMeasureFromColumnOrder(self, index) {
const [measure] = self.getMeasures().splice(index, 1);
if (measure && typeof self.measureDefinition.remove === 'function') {
return Promise.resolve(self.measureDefinition.remove.call(null, measure, self.properties, self, index));
}
return Promise.resolve();
}
function removeAltMeasureByIndex(self, index) {
return self.getAlternativeMeasures().splice(index, 1);
}
function replaceMeasureToColumnOrder(self, index, measure) {
const measures = self.getMeasures();
const replacedMeasure = measures[index];
const newMeasure = _objectSpread2(_objectSpread2({}, measure), {}, {
qDef: _objectSpread2(_objectSpread2({}, measure.qDef), {}, {
cId: uid()
})
});
measures[index] = newMeasure;
if (newMeasure && typeof self.measureDefinition.replace === 'function') {
self.dimensionDefinition.replace.call(null, newMeasure, replacedMeasure, index, self.properties, self);
}
return newMeasure;
}
function moveMeasureFromMainToAlternative(fromIndex, toIndex, measures, altMeasures) {
const alternativeToIndex = toIndex - measures.length;
let [movingMeasure] = altMeasures.splice(0, 1);
measures.push(movingMeasure);
[movingMeasure] = measures.splice(fromIndex, 1);
altMeasures.splice(alternativeToIndex, 0, movingMeasure);
return Promise.resolve(movingMeasure);
}
function moveMeasureFromAlternativeToMain(fromIndex, toIndex, measures, altMeasures) {
const alternativeFromIndex = fromIndex - measures.length;
let [movingMeasure] = measures.splice(measures.length - 1, 1);
altMeasures.splice(0, 0, movingMeasure);
[movingMeasure] = altMeasures.splice(alternativeFromIndex + 1, 1);
measures.splice(toIndex, 0, movingMeasure);
return Promise.resolve(movingMeasure);
}
function moveMeasureWithinAlternative(fromIndex, toIndex, measures, altMeasures) {
const alternativeFromIndex = fromIndex - measures.length;
const alternativeToIndex = toIndex - measures.length;
arrayUtil.move(altMeasures, alternativeFromIndex, alternativeToIndex);
}
/**
* @private
* @class DataPropertyHandler
* @description A class to handle data properties for dimensions and measures in a data model.
* @param {object} opts - Parameters to add a hypercube handlers
* @param {qix.Doc} opts.app
* @param {object} opts.dimensionDefinition
* @param {object} opts.measureDefinition
* @param {object} opts.dimensionProperties
* @param {object} opts.measureProperties
* @param {object} opts.globalChangeListeners
* @entry
* @export
* @example
* import DataPropertyHandler from '@nebula.js/stardust';
*
* class PivotHyperCubeHandler extends DataPropertyHandler {
*
* addDimensionAsFirstRow: (hypercube: HyperCubeDef, dimension: NxDimension) => {
* const dimensions = this.getDimensions().length;
* const { qInterColumnSortOrder } = hypercube;
*
* if(dimensions !== 0 && dimensions < this.maxDimensions()) {
* hypercube.qNoOfLeftDims = 1;
* qInterColumnSortOrder?.unshift(dimensions);
* dimensions.splice(0, 0, dimension);
* }
* }
* }
*/
class DataPropertyHandler {
constructor(opts) {
var _options$dimensionPro, _options$measurePrope;
const options = opts || {};
this.dimensionDefinition = options.dimensionDefinition || {
max: 0
};
this.measureDefinition = options.measureDefinition || {
max: 0
};
this.dimensionProperties = (_options$dimensionPro = options.dimensionProperties) !== null && _options$dimensionPro !== void 0 ? _options$dimensionPro : {};
this.measureProperties = (_options$measurePrope = options.measureProperties) !== null && _options$measurePrope !== void 0 ? _options$measurePrope : {};
this.globalChangeListeners = options.globalChangeListeners;
this.app = options.app;
}
/**
* @private
* @typeof {object} LibraryDimension
* @property {string} id
* @property {qix.NxDimension=} defaults
*/
/**
* @private
* @typeof {object} FieldDimension
* @property {string} field
* @property {string=} label
* @property {qix.NxDimension=} defaults
*/
/**
* @private
* @typeof {object} LibraryMeasure
* @property {string} id
* @property {qix.NxMeasure=} defaults
*/
/**
* @private
* @typeof {object} ExpressionMeasure
* @property {string} expression
* @property {string=} label
* @property {qix.NxMeasure=} defaults
*/
/**
* Sets the properties for the handler.
* @private
* @param {object=} properties - The properties object to set.
* @description Updates the handler's properties and analysis type flag.
* @memberof DataPropertyHandler
* @example
* handler.setProperties({ metaData: { isAnalysisType: true } });
*/
setProperties(properties) {
var _this$properties;
this.properties = properties;
this.isAnalysisType = (_this$properties = this.properties) === null || _this$properties === void 0 || (_this$properties = _this$properties.metaData) === null || _this$properties === void 0 ? void 0 : _this$properties.isAnalysisType;
}
/**
* Sets the global change listeners.
* @private
* @param {Function[]} arr - Array of listener functions.
* @description Assigns global change listeners to the handler.
* @memberof DataPropertyHandler
* @example
* handler.setGlobalChangeListeners([listener1, listener2]);
*/
setGlobalChangeListeners(arr) {
this.globalChangeListeners = arr;
}
/**
* @private
* @param {object=} layout - The layout object to set.
* @description Sets the layout for the handler.
* @memberof DataPropertyHandler
* @example
* handler.setLayout(layoutObj);
*/
setLayout(layout) {
this.layout = layout;
}
/**
* @private
* @throws {Error}
* @description Throws an error indicating the method must be overridden.
* @memberof DataPropertyHandler
* @example
* DataPropertyHandler.type(); // Throws error
*/
// eslint-disable-next-line class-methods-use-this
type() {
throw new Error('Must override this method');
}
// ---------------------------------------
// ---------------DIMENSION---------------
// ---------------------------------------
/**
* @private
* @returns {Array} Empty array.
* @description Returns the default dimension array.
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
getDimensions() {
return [];
}
/**
* Gets a dimension by id from dimensions or alternative dimensions.
* @private
* @param {string} id
* @returns {qix.NxDimension} - The found dimension.
* @description Searches for a dimension by id in both main and alternative dimensions.
* @memberof DataPropertyHandler
* @example
* const dim = handler.getDimension('dimId');
*/
getDimension(id) {
var _findFieldById;
const dimensions = this.getDimensions();
const alternativeDimensions = this.getAlternativeDimensions();
return (_findFieldById = findFieldById(dimensions, id)) !== null && _findFieldById !== void 0 ? _findFieldById : findFieldById(alternativeDimensions, id);
}
/**
* Throws an error indicating the method must be implemented in subclasses.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
getAlternativeDimensions() {
throw new Error('Method not implemented.');
}
/**
* Throws an error indicating addDimension is not supported in the base class.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
addDimension() {
throw notSupportedError;
}
/**
* Throws an error indicating addDimensions is not supported in the base class.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
addDimensions() {
throw notSupportedError;
}
/**
* Throws an error indicating removeDimension is not supported in the base class.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
removeDimension() {
throw notSupportedError;
}
/**
* Throws an error indicating removeDimensions is not supported in the base class.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
removeDimensions() {
throw notSupportedError;
}
/**
* Throws an error indicating autoSortDimension is not supported in the base class.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
autoSortDimension() {
throw notSupportedError;
}
/**
* Throws an error indicating replaceDimension is not supported in the base class.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
replaceDimension() {
throw notSupportedError;
}
/**
* Throws an error indicating getSorting is not supported in the base class.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
getSorting() {
throw notSupportedError;
}
/**
* Creates a type of library dimension with a field definition.
* @private
* @property {string} id
* @property {qix.NxDimension=} defaults
* @returns {qix.NxDimension} The created dimension object.
* @description Initializes a dimension and applying default properties and sort criteria.
* @memberof DataPropertyHandler
* @example
* const dim = handler.createLibraryDimension('dimId', { qDef: { qSortCriterias: [{ qSortByAscii: 1 }] } });
*/
createLibraryDimension(id, defaults) {
let dimension = originalExtend(true, {}, this.dimensionProperties || {}, defaults || {});
dimension = initializeDim(dimension);
dimension.qLibraryId = id;
dimension.qDef.autoSort = true;
dimension.qDef.qSortCriterias = INITIAL_SORT_CRITERIAS;
delete dimension.qDef.qFieldDefs;
delete dimension.qDef.qFieldLabels;
return dimension;
}
/**
* Creates a type of field dimension with a field definition.
* @private
* @property {string} field
* @property {string=} label
* @property {qix.NxDimension=} defaults
* @returns {qix.NxDimension} The created dimension object.
* @description Initializes a dimension with field definitions, labels, and default properties.
* @memberof DataPropertyHandler
* @example
* handler.createFieldDimension('currentField', 'label');
*/
createFieldDimension(field, label, defaults) {
let dimension = originalExtend(true, {}, this.dimensionProperties || {}, defaults || {});
dimension = initializeDim(dimension);
if (!field) {
dimension.qDef.qFieldDefs = [];
dimension.qDef.qFieldLabels = [];
dimension.qDef.qSortCriterias = [];
}
dimension.qDef.qFieldDefs = [field];
dimension.qDef.qFieldLabels = label ? [label] : [''];
dimension.qDef.qSortCriterias = INITIAL_SORT_CRITERIAS;
dimension.qDef.autoSort = true;
return dimension;
}
/**
* Adds a field dimension to the handler.
* @private
* @property {string} field
* @property {string=} label
* @property {qix.NxDimension=} defaults
* @returns {Promise<qix.NxDimension=>} The result of addDimension.
* @description Creates and adds a field dimension.
* @memberof DataPropertyHandler
* @example
* handler.addFieldDimension('currentField', 'label');
*/
addFieldDimension(field, label, defaults) {
const dimension = this.createFieldDimension(field, label, defaults);
return this.addDimension(dimension);
}
/**
* @private
* @param {FieldDimension[]} fieldDimensions - Array of field dimension.
* @returns {Promise<qix.NxDimension[]>} The result of addDimensions.
* @description Creates and adds multiple field dimensions.
* @memberof DataPropertyHandler
* @example
* handler.addFieldDimensions([{ field: 'A', label: 'AA' }, { field: 'B', label: 'BB' }]);
*/
addFieldDimensions(fieldDimensions) {
const dimensions = fieldDimensions.map(_ref => {
let {
field,
label,
defaults
} = _ref;
return this.createFieldDimension(field, label, defaults);
});
return this.addDimensions(dimensions);
}
/**
* Adds a library dimension to the handler.
* @private
* @property {string} id
* @property {qix.NxDimension=} defaults
* @returns {Promise<qix.NxDimension=>} The result of addDimension.
* @description Creates and adds a library dimension.
* @memberof DataPropertyHandler
* @example
* handler.addLibraryDimension('A', { qDef: { qSortCriterias: [{ qSortByAscii: 1 }] }});
*/
addLibraryDimension(id, defaults) {
const dimension = this.createLibraryDimension(id, defaults);
return this.addDimension(dimension);
}
/**
* Adds multiple library dimensions to the handler.
* @private
* @param {LibraryDimension[]} libraryDimensions - Array of library dimension.
* @returns {Promise<qix.NxDimension[]>} The result of addDimensions.
* @description Creates and adds multiple library dimensions.
* @memberof DataPropertyHandler
* @example
* handler.addLibraryDimensions([{ id: 'A' }, { id: 'B', defaults: { qDef: { qSortCriterias: [{ qSortByAscii: 1 }] } } }]);
*/
addLibraryDimensions(libraryDimensions) {
const dimensions = libraryDimensions.map(_ref2 => {
let {
id,
defaults
} = _ref2;
return this.createLibraryDimension(id, defaults);
});
const result = this.addDimensions(dimensions);
return result;
}
/**
* Adds multiple alternative library dimensions to the handler.
* @private
* @param {string[]} ids - Array of dimension ids.
* @returns {Promise<qix.NxDimension[]>} The result of addDimensions.
* @description Creates and adds multiple alternative library dimensions.
* @memberof DataPropertyHandler
* @example
* await handler.addAltLibraryDimensions([{ id: 'A' }, { id: 'B' }]);
*/
async addAltLibraryDimensions(ids) {
const dimensions = ids.map(_ref3 => {
let {
id
} = _ref3;
return this.createLibraryDimension(id);
});
return this.addDimensions(dimensions, true);
}
/**
* Adds multiple alternative field dimensions to the handler.
* @private
* @param {string[]} fields - Array of field dimension.
* @returns {Promise<qix.NxDimension[]>} The result of addDimensions.
* @description Creates and adds multiple alternative field dimensions.
* @memberof DataPropertyHandler
* @example
* await handler.addAltFieldDimensions([{ field: 'A' }, { field: 'B' }]);
*/
async addAltFieldDimensions(fields) {
const dimensions = fields.map(_ref4 => {
let {
field
} = _ref4;
return this.createFieldDimension(field);
});
return this.addDimensions(dimensions, true);
}
/**
* Adds an alternative field dimension to the handler.
* @private
* @param {string} field
* @returns {Promise<qix.NxDimension=>} The result of addDimension.
* @description Creates and adds an alternative field dimension.
* @memberof DataPropertyHandler
* @example
* handler.addAlternativeFieldDimension('field');
*/
addAlternativeFieldDimension(field) {
const dimension = this.createFieldDimension(field);
return this.addDimension(dimension, true);
}
/**
* Adds an alternative library dimension to the handler.
* @private
* @property {string} id
* @property {qix.NxDimension=} defaults
* @returns {Promise<qix.NxDimension=>} The result of addDimension.
* @description Creates and adds an alternative library dimension.
* @memberof DataPropertyHandler
* @example
* handler.addAlternativeLibraryDimension('A', { qDef: { qSortCriterias: [{ qSortByAscii: -1 }] } });
*/
addAlternativeLibraryDimension(id, defaults) {
const dimension = this.createLibraryDimension(id, defaults);
return this.addDimension(dimension, true);
}
/**
* Gets the minimum number of dimensions allowed.
* @private
* @returns {number} The minimum number of dimensions.
* @description Returns the minimum number of dimensions allowed by the handler.
* @memberof DataPropertyHandler
* @example
* const min = handler.minDimensions();
*/
minDimensions() {
if (typeof this.dimensionDefinition.min === 'function') {
return this.dimensionDefinition.min.call(null, this.properties, this);
}
return this.dimensionDefinition.min || 0;
}
/**
* Gets the maximum number of dimensions allowed.
* @private
* @param {number} [decrement=0] - The number to decrement from the current number of measures.
* @returns {number} The maximum number of dimensions allowed.
* @description Checks if the max property is a function and calls it with the current number of measures, or returns a default value.
* @memberof DataPropertyHandler
* @example
* const max = handler.maxDimensions();
*/
maxDimensions() {
let decrement = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
const measureLength = this.getMeasures().length - decrement;
if (typeof this.dimensionDefinition.max === 'function') {
var _this$dimensionDefini;
const dimParams = [measureLength];
return (_this$dimensionDefini = this.dimensionDefinition.max) === null || _this$dimensionDefini === void 0 ? void 0 : _this$dimensionDefini.apply(null, dimParams);
}
return Number.isNaN(+this.dimensionDefinition.max) ? 10000 : this.dimensionDefinition.max;
}
/**
* Checks if a new dimension can be added.
* @private
* @returns {boolean} True if a new dimension can be added, false otherwise.
* @description Returns whether the handler can add another dimension.
* @memberof DataPropertyHandler
* @example
* if (handler.canAddDimension()) { handler.addFieldDimension('A'); }
*/
canAddDimension() {
return this.getDimensions().length < this.maxDimensions();
}
// ---------------------------------------
// ----------------MEASURE----------------
// ---------------------------------------
/**
* @private
* @returns {Array} Empty array.
* @description Returns the default measure array.
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
getMeasures() {
return [];
}
/**
* Throws an error indicating the method must be implemented in subclasses.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
getAlternativeMeasures() {
throw new Error('Method not implemented.');
}
/**
* Throws an error indicating addMeasure is not supported in the base class.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
addMeasure() {
throw notSupportedError;
}
/**
* Throws an error indicating addMeasures is not supported in the base class.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
addMeasures() {
throw notSupportedError;
}
/**
* Throws an error indicating removeMeasure is not supported in the base class.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
removeMeasure() {
throw notSupportedError;
}
/**
* Throws an error indicating removeMeasures is not supported in the base class.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
removeMeasures() {
throw notSupportedError;
}
/**
* Throws an error indicating autoSortMeasure is not supported in the base class.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
autoSortMeasure() {
throw notSupportedError;
}
/**
* Throws an error indicating replaceMeasure is not supported in the base class.
* @private
* @throws {Error}
* @memberof DataPropertyHandler
*/
// eslint-disable-next-line class-methods-use-this
replaceMeasure() {
throw notSupportedError;
}
/**
* Gets a measure by id from measures or alternative measures.
* @private
* @param {string} id - The measure id to find.
* @returns {qix.NxMeasure} The found measure or undefined.
* @description Searches for a measure by id in both main and alternative measures.
* @memberof DataPropertyHandler
* @example
* const measure = handler.getMeasure('measId');
*/
getMeasure(id) {
var _findFieldById2;
const measures = this.getMeasures();
const alternativeMeasures = this.getAlternativeMeasures();
return (_findFieldById2 = findFieldById(measures, id)) !== null && _findFieldById2 !== void 0 ? _findFieldById2 : findFieldById(alternativeMeasures, id);
}
/**
* Creates an expression measure.
* @private
* @property {string} expression
* @property {string=} label
* @property {qix.NxMeasure=} defaults
* @returns {Promise<qix.NxMeasure=>} The created measure object.
* @description Initializes a measure with an expression, label, and default properties.
* @memberof DataPropertyHandler
* @example
* const meas = handler.createExpressionMeasure('Sum(Sales)', 'Total Sales');
*/
createExpressionMeasure(expression, label, defaults) {
var _measure$qDef, _measure$qDef$qNumFor;
const measure = originalExtend(true, {}, this.measureProperties || {}, defaults || {});
measure.qDef = (_measure$qDef = measure.qDef) !== null && _measure$qDef !== void 0 ? _measure$qDef : {};
measure.qDef.qNumFormat = (_measure$qDef$qNumFor = measure.qDef.qNumFormat) !== null && _measure$qDef$qNumFor !== void 0 ? _measure$qDef$qNumFor : {};
measure.qDef.qDef = expression;
measure.qDef.qLabel = label;
measure.qDef.autoSort = true;
return measure;
}
/**
* Adds an expression measure to the handler.
* @private
* @property {string} expression
* @property {string=} label
* @property {qix.NxMeasure=} defaults
* @returns {Promise<qix.NxMeasure=>} The result of addMeasure.
* @description Creates and adds an expression measure.
* @memberof DataPropertyHandler
* @example
* handler.addExpressionMeasure('Sum(Sales)', 'Total Sales');
*/
addExpressionMeasure(expression, label, defaults) {
const measure = this.createExpressionMeasure(expression, label, defaults);
return this.addMeasure(measure);
}
/**
* Adds multiple expression measures to the handler.
* @private
* @param {ExpressionMeasure[]} expressionMeasures - Array of expression measures.
* @returns {Promise<qix.NxMeasure[]>} The result of addMeasures.
* @description Creates and adds multiple expression measures.
* @memberof DataPropertyHandler
* @example
* handler.addExpressionMeasures([{ expression: 'Sum(A)' }, { expression: 'Sum(B)', label: 'B' }]);
*/
addExpressionMeasures(expressionMeasures) {
const measures = expressionMeasures.map(_ref5 => {
let {
expression,
label,
defaults
} = _ref5;
return this.createExpressionMeasure(expression, label, defaults);
});
return this.addMeasures(measures, false);
}
/**
* Creates a library measure.
* @private
* @property {string} id
* @property {qix.NxMeasure=} defaults
* @returns {qix.NxMeasure} The created measure object.
* @description Initializes a library measure with default properties.
* @memberof DataPropertyHandler
* @example
* const meas = handler.createLibraryMeasure('measId', { qDef: { qNumFormat: { qType: 'F' } } });
*/
createLibraryMeasure(id, defaults) {
var _measure$qDef2, _measure$qDef$qNumFor2;
const measure = originalExtend(true, {}, this.measureProperties || {}, defaults || {});
measure.qDef = (_measure$qDef2 = measure.qDef) !== null && _measure$qDef2 !== void 0 ? _measure$qDef2 : {};
measure.qDef.qNumFormat = (_measure$qDef$qNumFor2 = measure.qDef.qNumFormat) !== null && _measure$qDef$qNumFor2 !== void 0 ? _measure$qDef$qNumFor2 : {};
useMasterNumberFormat(measure.qDef);
measure.qLibraryId = id;
measure.qDef.autoSort = true;
delete measure.qDef.qDef;
delete measure.qDef.qLabel;
return measure;
}
/**
* Adds a library measure to the handler.
* @private
* @property {string} id
* @property {qix.NxMeasure=} defaults
* @returns {Promise<qix.NxMeasure=>} The result of addMeasure.
* @description Creates and adds a library measure.
* @memberof DataPropertyHandler
* @example
* handler.addLibraryMeasure('measId', { qDef: { qNumFormat: { qType: 'F' } } });
*/
addLibraryMeasure(id, defaults) {
const measure = this.createLibraryMeasure(id, defaults);
return this.addMeasure(measure);
}
/**
* Adds multiple library measures to the handler.
* @private
* @param {LibraryMeasure[]} libraryMeasures - Array of library measures.
* @returns {Promise<qix.NxMeasure[]>} The result of addMeasures.
* @description Creates and adds multiple library measures.
* @memberof DataPropertyHandler
* @example
* handler.addLibraryMeasures([{ id: 'A' }, { id: 'B', defaults: { qDef: { qNumFormat: { ... } } } }]);
*/
addLibraryMeasures(libraryMeasures) {
const measures = libraryMeasures.map(_ref6 => {
let {
id,
defaults
} = _ref6;
return this.createLibraryMeasure(id, defaults);
});
return this.addMeasures(measures, false);
}
/**
* Adds multiple alternative library measures to the handler.
* @private
* @param {LibraryMeasure[]} libraryMeasures - Array of library measure.
* @returns {Promise<qix.NxMeasure[]>} The result of addMeasures.
* @description Creates and adds multiple alternative library measures.
* @memberof DataPropertyHandler
* @example
* handler.addAltLibraryMeasures([{ id: 'A' }, { id: 'B', defaults: { qDef: { qNumFormat: { ... } } } }]);
*/
addAltLibraryMeasures(libraryMeasures) {
const measures = libraryMeasures.map(_ref7 => {
let {
id,
defaults
} = _ref7;
return this.createLibraryMeasure(id, defaults);
});
return this.addMeasures(measures, true);
}
/**
* Adds multiple alternative expression measures to the handler.
* @private
* @param {ExpressionMeasure[]} expressionMeasures - Array of expression measure.
* @returns {Promise<qix.NxMeasure[]>} The result of addMeasures.
* @description Creates and adds multiple alternative expression measures.
* @memberof DataPropertyHandler
* @example
* handler.addAltExpressionMeasures([{ expression: 'Sum(A)' }, { expression: 'Sum(B)' }]);
*/
addAltExpressionMeasures(expressionMeasures) {
const measures = expressionMeasures.map(_ref8 => {
let {
expression
} = _ref8;
return this.createExpressionMeasure({
expression
});
});
return this.addMeasures(measures, true);
}
/**
* Adds an alternative expression measure to the handler.
* @private
* @property {string} expression
* @property {string=} label
* @property {qix.NxMeasure=} defaults
* @returns {Promise<qix.NxMeasure=>} The result of addMeasure.
* @description Creates and adds an alternative expression measure.
* @memberof DataPropertyHandler
* @example
* handler.addAlternativeExpressionMeasure('Sum(Sales)', 'Total Sales');
*/
addAlternativeExpressionMeasure(expression, label, defaults) {
const measure = this.createExpressionMeasure(expression, label, defaults);
return this.addMeasure(measure, true);
}
/**
* Adds an alternative library measure to the handler.
* @private
* @property {string} id
* @property {qix.NxMeasure=} defaults
* @returns {qix.NxMeasure=} The result of addMeasure.
* @description Creates and adds an alternative library measure.
* @memberof DataPropertyHandler
* @example
* handler.addAlternativeLibraryMeasure('measId', { qDef: { qNumFormat: { qType: 'F' } } });
*/
addAlternativeLibraryMeasure(id, defaults) {
const measure = this.createLibraryMeasure(id, defaults);
return this.addMeasure(measure, true);
}
/**
* Gets the minimum number of measures allowed.
* @private
* @returns {number} The minimum number of measures.
* @description Returns the minimum number of measures allowed by the handler.
* @memberof DataPropertyHandler
* @example
* const min = handler.minMeasures();
*/
minMeasures() {
if (typeof this.measureDefinition.min === 'function') {
return this.measureDefinition.min.call(null, this.properties, this);
}
return this.measureDefinition.min || 0;
}
/**
* Gets the maximum number of measures allowed.
* @private
* @param {number} [decrement=0] - The number to decrement from the current number of dimensions.
* @returns {number} The maximum number of measures allowed.
* @description Checks if the max property is a function and calls it with the current number of dimensions, or returns a default value.
* @memberof DataPropertyHandler
* @example
* const max = handler.maxMeasures();
*/
maxMeasures() {
let decrement = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
if (typeof this.measureDefinition.max === 'function') {
const dimLength = this.getDimensions().length - decrement;
const measureParams = [dimLength];
return this.measureDefinition.max.apply(null, measureParams);
}
return Number.isNaN(+this.measureDefinition.max) ? 10000 : this.measureDefinition.max;
}
/**
* Checks if a new measure can be added.
* @private
* @returns {boolean} True if a new measure can be added, false otherwise.
* @description Returns whether the handler can add another measure.
* @memberof DataPropertyHandler
* @example
* if (handler.canAddMeasure()) { handler.addExpressionMeasure('Sum(A)'); }
*/
canAddMeasure() {
return this.getMeasures().length < this.maxMeasures();
}
// ---------------------------------------
// ---------------OTHERS------------------
// ---------------------------------------
/**
* Calls all global change listeners with the current properties, handler, and layout.
* @private
* @param {object} layout - The layout object to pass to listeners.
* @description Invokes all registered global change listeners.
* @memberof DataPropertyHandler
* @example
* handler.updateGlobalChangeListeners(layoutObj);
*/
updateGlobalChangeListeners(layout) {
if (this.globalChangeListeners) {
(this.globalChangeListeners || []).forEach(func => {
if (func && typeof func === 'function') {
func(this.properties, this, {
layout
});
}
});
}
}
} exports("M", DataPropertyHandler);
function getAutoSortLibraryDimension(self, dimension) {
return self.app.getDimensionList().then(dimensionList => {
const libDim = (dimension === null || dimension === void 0 ? void 0 : dimension.qLibraryId) && findLibraryItem(dimension.qLibraryId, dimensionList);
if (libDim) {
setAutoSort(libDim.qData.info, dimension, self);
}
return dimension;
});
}
const getDataGeoField = field => {
const item = field;
item.isDateField = isDateField(item);
item.isGeoField = isGeoField(item);
return item;
};
const getDerivedFields = field => {
const derivedFields = [];
if (!field.qDerivedFieldData) {
return derivedFields;
}
field.qDerivedFieldData.qDerivedFieldLists.forEach(derived => {
derived.qFieldDefs.forEach(derivedField => {
derivedFields.push({
qName: derivedField.qName,
displayName: trimAutoCalendarName(derivedField.qName),
qSrcTables: field.qSrcTables,
qTags: derivedField.qTags,
isDerived: true,
isDerivedFromDate: field.isDateField,
sourceField: field.qName,
derivedDefinitionName: derived.qDerivedDefinitionName
});
});
});
return derivedFields;
};
const expandFieldsWithDerivedData = list => {
const fieldList = [];
list.forEach(field => {
fieldList.push(getDataGeoField(field));
const derivedFields = getDerivedFields(field);
fieldList.push(...derivedFields);
});
return fieldList;
};
const findFieldInExpandedList = (name, fieldList) => {
const expandedList = expandFieldsWithDerivedData(fieldList.slice(0));
const fieldName = getField(name);
return expandedList && findFieldByName(fieldName, expandedList) || null;
};
function getAutoSortDimension(self, dimension) {
return self.app.getFieldList().then(fieldList => {
var _dimension$qDef;
const field = (dimension === null || dimension === void 0 || (_dimension$qDef = dimension.qDef) === null || _dimension$qDef === void 0 ? void 0 : _dimension$qDef.qFieldDefs) && findFieldInExpandedList(dimension.qDef.qFieldDefs[0], fieldList);
if (field) {
setAutoSort([field], dimension, self);
}
return dimension;
});
}
function updateDimensionOrders(self, dimension, index) {
const dimensions = self.getDimensions();
dimensions.splice(index, 0, dimension);
return self.autoSortDimension(dimension).then(async () => {
addDimensionToColumnSortOrder(self, dimensions, index);
await addDimensionToColumnOrder(self, dimension);
return dimension;
});
}
function addMainDimension(self, dimension, index) {
const dimensions = self.getDimensions();
const idx = index !== null && index !== void 0 ? index : dimensions.length;
if (dimensions.length < self.maxDimensions()) {
return updateDimensionOrders(self, dimension, idx);
}
return Promise.resolve(dimension);
}
function addMainMeasure(self, measure, index) {
const measures = self.getMeasures();
const idx = index !== null && index !== void 0 ? index : measures.length;
if (measures.length < self.maxMeasures()) {
measures.splice(idx, 0, measure);
return self.autoSortMeasure(measure).then(() => {
addMeasureToColumnSortOrder(self, measures);
addMeasureToColumnOrder(self, measure).then(() => measure);
return measure;
});
}
return Promise.resolve();
}
async function removeMainDimension(self, index) {
removeDimensionFromColumnSortOrder(self, index);
await removeDimensionFromColumnOrder(self, index);
}
function removeAlternativeMeasure(self, indexes) {
const current = self;
const measures = current.getAlternativeMeasures();
const remainedFields = getRemainedFields(measures, indexes);
current.hcProperties.qLayoutExclude.qHyperCubeDef.qMeasures = remainedFields;
}
async function removeMainMeasure(self, index) {
removeMeasureFromColumnSortOrder(self, index);
await removeMeasureFromColumnOrder(self, index);
}
function removeAlternativeDimension(self, index) {
const [dimension] = self.getAlternativeDimensions().splice(index, 1);
if (dimension && typeof self.dimensionDefinition.remove === 'function') {
dimension.isAlternative = true;
return Promise.resolve(self.dimensionDefinition.remove.call(null, dimension, self.properties, self, index)).then(() => {
delete dimension.isAlternative;
});
}
return undefined;
}
function reinsertMainDimension(self, dimension, index) {
const dimensions = self.getDimensions();
const idx = index !== null && index !== void 0 ? index : dimensions.length;
if (dimensions.length < self.maxDimensions()) {
dimensions.splice(idx, 0, dimension);
addDimensionToColumnSortOrder(self, dimensions);
return moveDimensionToColumnOrder(self, dimension);
}
return Promise.resolve(dimension);
}
function reinsertMainMeasure(self, measure, index) {
const measures = self.getMeasures();
const idx = index !== null && index !== void 0 ? index : measures.length;
if (measures.length < self.maxMeasures()) {
measures.splice(idx, 0, measure);
addMeasureToColumnSortOrder(self, measures);
return moveMeasureColumnOrder(self, measure);
}
return Promise.resolve(measure);
}
/**
* HyperCubeHandler for managing hypercube data structure.
* @private
* @class HyperCubeHandler
* @description This class provides methods to handle hypercube properties, dimensions, and measures.
* @param {object} opts Parameters to add a hypercube handlers
* @param {qix.Doc} opts.app
* @param {object} opts.dimensionDefinition
* @param {object} opts.measureDefinition
* @param {object} opts.dimensionProperties
* @param {object} opts.measureProperties
* @param {object} opts.globalChangeListeners
* @param {object} opts.path
* @entry
* @export
* @example
* import { HyperCubeHandler } from '@nebula.js/stardust';
*
* class PivotHyperCubeHandler extends HyperCubeHandler {
*
* adjustPseudoDimOrder: (pseudoIdx?: number) => {
* const numberOfDims = this.getDimensions().length;
* const interColumnSortOrder = this.hcProperties.qInterColumnSortOrder;
*
* if (!interColumnSortOrder) {
* return;
* }
*
* interColumnSortOrder.splice(pseudoIdx || 0, 1);
* interColumnSortOrder.push(numberOfDims);
* interColumnSortOrder.splice((pseudoIdx || -1) + 1, 0, -1);
* };
* }
*/
class HyperCubeHandler extends DataPropertyHandler {
constructor(opts) {
super(opts);
this.path = opts.path;
}
/**
* @private
* @param {object=} properties
* @returns early return if properties is falsy
*/
setProperties(properties) {
if (!properties) {
return;
}
super.setProperties(properties);
this.hcProperties = this.path ? utils.getValue(properties, "".concat(this.path, ".qHyperCubeDef")) : properties.qHyperCubeDef;
if (!this.hcProperties) {
return;
}
setDefaultProperties(this);
setPropForLineChartWithForecast(this);
// Set auto-sort property (compatibility 0.85 -> 0.9), can probably be removed in 1.0
this.hcProperties.qDimensions = setFieldProperties(this.hcProperties.qDimensions);
this.hcProperties.qMeasures = setFieldProperties(this.hcProperties.qMeasures);
}
// ----------------------------------
// ----------- DIMENSIONS -----------
// ----------------------------------
/**
* @private
* @returns {qix.NxDimension[]} dimensions
* @description Returns the dimensions of the hypercube.
* @memberof HyperCubeHandler
* @example
* const dimensions = hyperCubeHandler.getDimensions();
*/
getDimensions() {
return this.hcProperties ? this.hcProperties.qDimensions : [];
}
/**
* @private
* @returns {qix.NxDimension[]} alternative dimensions
* @description Returns the alternative dimensions of the hypercube.
* @memberof HyperCubeHandler
* @example
* const alternativeDimensions = hyperCubeHandler.getAlternativeDimensions();
*/
getAlternativeDimensions() {
var _this$hcProperties$qL, _this$hcProperties;
return (_this$hcProperties$qL = (_this$hcProperties = this.hcProperties) === null || _this$hcProperties === void 0 || (_this$hcProperties = _this$hcProperties.qLayoutExclude) === null || _this$hcProperties === void 0 || (_this$hcProperties = _this$hcProperties.qHyperCubeDef) === null || _this$hcProperties === void 0 ? void 0 : _this$hcProperties.qDimensions) !== null && _this$hcProperties$qL !== void 0 ? _this$hcProperties$qL : [];
}
/**
* @private
* @param {string} cId
* @returns {qix.NxDimensionInfo} dimension layout
* @description Returns the dimension layout of the hypercube for a given cId.
* @memberof HyperCubeHandler
* @example
* const dimensionLayout = hyperCubeHandler.getDimensionLayout('cId');
*/
getDimensionLayout(cId) {
return this.getDimensionLayouts().filter(item => cId === item.cId)[0];
}
/**
* @private
* @returns {qix.NxDimensionInfo[]} dimension layouts
* @description Returns the dimension layouts of the hypercube.
* @memberof HyperCubeHandler
* @example
* const dimensionLayouts = hyperCubeHandler.getDimensionLayouts();
*/
getDimensionLayouts() {
const hc = getHyperCube(this.layout, this.path);
return hc ? hc.qDimensionInfo : [];
}
/**
* @private
* @param {qix.NxDimension} dimension
* @param {boolean} alternative
* @param {number=} idx
* @returns {qix.NxDimension} dimension
* @description Adds a dimension to the hypercube and updates the orders of the dimensions.
* If the dimension is an alternative, it will be added to the alternative dimensions.
* @memberof HyperCubeHandler
* @example
* const dimension = hyperCubeHandler.addDimension({qDef :{ cId: 'id', qSortCriterias: [{qSortByLoadOrder: 1}]}}, true, 1);
*/
addDimension(dimension, alternative, idx) {
const dim = initializeDim(dimension);
if (isDimensionAlternative(this, alternative)) {
return addAlternativeDimension(this, dim, idx);
}
return addMainDimension(this, dim, idx);
}
/**
* @private
* @param {qix.NxDimension[]} dimensions
* @param {boolean} alternative
* @returns {qix.NxDimension[]} added dimensions
* @description Adds multiple dimensions to the hypercube.
* If the dimensions are alternatives, they will be added to the alternative dimensions.
* If the total number of dimensions exceeds the limit, it will stop adding dimensions.
* @memberof HyperCubeHandler
* @example
* const addedDimensions = await hyperCubeHandler.addDimensions([{qDef :{ cId: 'id01'}}, {qDef :{ cId: 'id02'}}], false);
*/
async addDimensions(dimensions) {
let alternative = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
const existingDimensions = this.getDimensions();
const initialLength = existingDimensions.length;
const addedDimensions = [];
let addedActive = 0;
// eslint-disable-next-line no-restricted-syntax
var _iteratorAbruptCompletion = false;
var _didIteratorError = false;
var _iteratorError;
try {
for (var _iterator = _asyncIterator(dimensions), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {
const dimension = _step.value;
{
if (isTotalDimensionsExceeded(this, existingDimensions)) {
return addedDimensions;
}
const dim = initializeDim(dimension);
if (isDimensionAlternative(this, alternative)) {
const altDim = await addAlternativeDimension(this, dim);
addedDimensions.push(altDim);
} else if (existingDimensions.length < this.maxDimensions()) {
await addActiveDimension(this, dim, initialLength, existingDimensions, addedDimensions, addedActive);
addedActive++;
}
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (_iteratorAbruptCompletion && _iterator.return != null) {
await _iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return addedDimensions;
}
/**
* @private
* @param {number} index
* @param {boolean} alternative
* @description Removes a dimension from the hypercube by index.
* If the dimension is an alternative, it will be removed from the alternative dimensions.
* @memberof HyperCubeHandler
* @example
* hyperCubeHandler.removeDimension(0, true);
*/
removeDimension(index, alternative) {
if (alternative) {
return removeAlternativeDimension(this, index);
}
return removeMainDimension(this, index);
}
/**
* @private
* @param {number[]} indexes
* @param {boolean} alternative
* @returns {qix.NxDimension[]} deleted dimensions
* @description Removes multiple dimensions from the hypercube by indexes.
* If the dimensions are alternatives, they will be removed from the alternative dimensions.
* If the indexes are empty, it will return an empty array.
* @memberof HyperCubeHandler
* @example
* const deletedDimensions = await hyperCubeHandler.removeDimensions({1, 0}, false);
*/
async removeDimensions(indexes, alternative) {
const altDimensions = this.getAlternativeDimensions();
const dimensions = this.getDimensions();
if (indexes.length === 0) return [];
let deletedDimensions = [];
// Start deleting from the end of the list first otherwise the idx is messed up
const sortedIndexes = [...indexes].sort((a, b) => b - a);
if (alternative && altDimensions.length > 0) {
// Keep the original deleted order
deletedDimensions = getDeletedFields(altDimensions, indexes);
// eslint-disable-next-line no-restricted-syntax
var _iteratorAbruptCompletion2 = false;
var _didIteratorError2 = false;
var _iteratorError2;
try {
for (var _iterator2 = _asyncIterator(sortedIndexes), _step2; _iteratorAbruptCompletion2 = !(_step2 = await _iterator2.next()).done; _iteratorAbruptCompletion2 = false) {
const index = _step2.value;
{
await removeAlternativeDimension(this, index);
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (_iteratorAbruptCompletion2 && _iterator2.return != null) {
await _iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
} else if (dimensions.length > 0) {
// Keep the original deleted order
deletedDimensions = getDeletedFields(dimensions, indexes);
// eslint-disable-next-line no-restricted-syntax
var _iteratorAbruptCompletion3 = false;
var _didIteratorError3 = false;
var _iteratorError3;
try {
for (var _iterator3 = _asyncIterator(sortedIndexes), _step3; _iteratorAbruptCompletion3 = !(_step3 = await _iterator3.next()).done; _iteratorAbruptCompletion3 = false) {
const index = _step3.value;
{
await removeMainDimension(this, index);
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (_iteratorAbruptCompletion3 && _iterator3.return != null) {
await _iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
}
return deletedDimensions;
}
/**
* Replaces a dimension in the hypercube.
* @private
* @param {number} index - The index of the dimension to replace.
* @param {qix.NxDimension} dimension - The new dimension to replace the old one.
* @returns {Promise<qix.NxDimension>} replaced dimension.
* @memberof HyperCubeHandler
* @example
* const replacedDimension = await hyperCubeHandler.replaceDimension(2, {qDef :{ cId: 'id'}});
*/
replaceDimension(index, dimension) {
return this.autoSortDimension(dimension).then(() => replaceDimensionOrder(this, index, dimension));
}
/**
* Reinserts a dimension into the hypercube.
* @private.
* @param {qix.NxDimension} dimension - The dimension to reinsert.
* @param {boolean} alternative - Whether the dimension is an alternative.
* @param {number} index - The index to insert the dimension at.
* @returns {Promise<qix.NxDimension>} The reinserted dimension.
* @memberof HyperCubeHandler
* @example
* await hyperCubeHandler.reinsertDimension({qDef :{ cId: 'id'}}, false, 2);
*/
reinsertDimension(dimension, alternative, index) {
const dim = initializeId(dimension);
if (isDimensionAlternative(this, alternative)) {
return addAlternativeDimension(this, dim, index).then(() => {
moveDimensionToColumnOrder(this, dim);
});
}
return reinsertMainDimension(this, dim, index);
}
/**
* Moves a dimension within the hypercube.
* @private
* @param {number} fromIndex - The current index of the dimension.
* @param {number} toIndex - The new index of the dimension.
* @returns {Promise<qix.NxDimension[]>} updated dimensions.
* @memberof HyperCubeHandler
* @example
* await hyperCubeHandler.moveDimension(2, 1);
*/
moveDimension(fromIndex, toIndex) {
const dimensions = this.getDimensions();
const altDimensions = this.getAlternativeDimensions();
if (fromIndex < dimensions.length && toIndex < dimensions.length) {
return Promise.resolve(arrayUtil.move(dimensions, fromIndex, toIndex));
}
if (fromIndex < dimensions.length && toIndex >= dimensions.length) {
return moveDimensionFromMainToAlternative(fromIndex, toIndex, dimensions, altDimensions);
}
if (fromIndex >= dimensions.length && toIndex < dimensions.length) {
return Promise.resolve(moveMeasureFromAlternativeToMain(fromIndex, toIndex, dimensions, altDimensions));
}
return Promise.resolve(moveDimensionWithinAlternative(fromIndex, toIndex, dimensions, altDimensions));
}
/**
* @private
* @param {qix.NxDimension} dimension
* @returns {qix.NxDimension} dimension with auto-sort properties
* @description Automatically sorts the dimension based on its properties.
* If the dimension has a qLibraryId, it will use the library dimension auto-sort.
* Otherwise, it will use the field dimension auto-sort.
* @memberof HyperCubeHandler
* @example
* const sortedDimension = hyperCubeHandler.autoSortDimension({qDef :{ cId: 'id'}});
*/
autoSortDimension(dimension) {
if (dimension.qLibraryId) {
return getAutoSortLibraryDimension(this, dimension);
}
return getAutoSortDimension(this, dimension);
}
// ----------------------------------
// ------------ MEASURES ------------
// ----------------------------------
/**
* @private
* @returns {qix.NxMeasure[]} measures
* @description Returns the measures of the hypercube.
* @memberof HyperCubeHandler
* @example
* const measures = hyperCubeHandler.getMeasures();
*/
getMeasures() {
return this.hcProperties ? this.hcProperties.qMeasures : [];
}
/**
* @private
* @returns {qix.NxMeasure[]} alternative measures
* @description Returns the alternative measures of the hypercube.
* @memberof HyperCubeHandler
* @example
* const alternativeMeasures = hyperCubeHandler.getAlternativeMeasures();
*/
getAlternativeMeasures() {
var _this$hcProperties$qL2, _this$hcProperties2;
return (_this$hcProperties$qL2 = (_this$hcProperties2 = this.hcProperties) === null || _this$hcProperties2 === void 0 || (_this$hcProperties2 = _this$hcProperties2.qLayoutExclude) === null || _this$hcProperties2 === void 0 || (_this$hcProperties2 = _this$hcProperties2.qHyperCubeDef) === null || _this$hcProperties2 === void 0 ? void 0 : _this$hcProperties2.qMeasures) !== null && _this$hcProperties$qL2 !== void 0 ? _this$hcProperties$qL2 : [];
}
/**
* @private
* @returns {qix.NxMeasureInfo[]} measure layouts
* @description Returns the measure layouts of the hypercube.
* @memberof HyperCubeHandler
* @example
* const measureLayouts = hyperCubeHandler.getMeasureLayouts();
*/
getMeasureLayouts() {
const hc = getHyperCube(this.layout, this.path);
return hc ? hc.qMeasureInfo : [];
}
/**
* @private
* @param {string} cId
* @returns {object} measure layout
* @description Returns the measure layout of the hypercube for a given cId.
* @memberof HyperCubeHandler
* @example
* const measureLayout = hyperCubeHandler.getMeasureLayout('cid');
*/
getMeasureLayout(cId) {
return this.getMeasureLayouts().filter(item => cId === item.cId)[0];
}
/**
* @private
* @param {qix.NxMeasure} measure
* @param {boolean} alternative
* @param {number=} index
* @returns {Promise<qix.NxMeasure>} added measure
* @description Adds a measure to the hypercube.
* If the measure is an alternative, it will be added to the alternative measures.
* If the total number of measures exceeds the limit, it will stop adding measures.
* @memberof HyperCubeHandler
* @example
* const measure = hyperCubeHandler.addMeasure({qDef :{ cId: 'id'}}, true, 0);
*/
addMeasure(measure, alternative, index) {
const meas = initializeId(measure);
if (isMeasureAlternative(this, alternative)) {
return addAlternativeMeasure(this, meas, index);
}
return addMainMeasure(this, meas, index);
}
/**
* @private
* @param {qix.NxMeasure} measure
* @returns {Promise<qix.NxMeasure>} measure with auto-sort properties
* @description Automatically sorts the measure based on its properties.
* It sets the qSortByLoadOrder and qSortByNumeric properties.
* @memberof HyperCubeHandler
* @example
* const sortedMeasure = hyperCubeHandler.autoSortMeasure({qDef :{ cId: 'id'}});
*/
// eslint-disable-next-line class-methods-use-this
autoSortMeasure(measure) {
const meas = measure;
meas.qSortBy = {
qSortByLoadOrder: 1,
qSortByNumeric: -1
};
return Promise.resolve(meas);
}
/**
* @private
* @param {qix.NxMeasure[]} measures
* @param {boolean} alternative
* @returns {qix.NxMeasure[]} added measures
* @description Adds multiple measures to the hypercube.
* If the measures are alternatives, they will be added to the alternative measures.
* If the total number of measures exceeds the limit, it will stop adding measures.
* @memberof HyperCubeHandler
* @example
* const addedMeasures = await hyperCubeHandler.addMeasures([{qDef :{ cId: 'id01'}}, {qDef :{ cId: 'id02'}}], true);
*/
addMeasures(measures) {
let alternative = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
const existingMeasures = this.getMeasures();
const addedMeasures = [];
let addedActive = 0;
measures.forEach(async measure => {
if (isTotalMeasureExceeded(this, existingMeasures)) {
return false;
}
const meas = initializeId(measure);
if (isMeasureAlternative(this, alternative || false)) {
addAlternativeMeasure(this, meas);
addedMeasures.push(meas);
} else if (existingMeasures.length < this.maxMeasures()) {
await addActiveMeasure(this, meas, existingMeasures, addedMeasures, addedActive);
addedActive++;
}
return true;
});
return addedMeasures;
}
/**
* @private
* @param {number} index
* @param {boolean} alternative
* @description Removes a measure from the hypercube by index.
* If the measure is an alternative, it will be removed from the alternative measures.
* @memberof HyperCubeHandler
* @example
* hyperCubeHandler.removeMeasure(0, false);
*/
removeMeasure(index, alternative) {
if (alternative) {
return removeAltMeasureByIndex(this, index);
}
return removeMainMeasure(this, index);
}
/**
* @private
* @param {number[]} indexes
* @param {boolean} alternative
* @returns {Promise<number[]>} deleted measures
* @description Removes multiple measures from the hypercube by indexes.
* If the measures are alternatives, they will be removed from the alternative measures.
* If the indexes are empty, it will return an empty array.
* @memberof HyperCubeHandler
* @example
* const deletedMeasures = await hyperCubeHandler.removeMeasures({0,1}, true);
*/
async removeMeasures(indexes, alternative) {
const measures = this.getMeasures();
const altMeasures = this.getAlternativeMeasures();
let deletedMeasures = [];
if (indexes.length === 0) return deletedMeasures;
if (alternative && altMeasures.length > 0) {
// Keep the original deleted order
deletedMeasures = getDeletedFields(altMeasures, indexes);
removeAlternativeMeasure(this, indexes);
} else if (measures.length > 0) {
// Keep the original deleted order
deletedMeasures = getDeletedFields(measures, indexes);
const sortedIndexes = [...indexes].sort((a, b) => b - a);
// eslint-disable-next-line no-restricted-syntax
var _iteratorAbruptCompletion4 = false;
var _didIteratorError4 = false;
var _iteratorError4;
try {
for (var _iterator4 = _asyncIterator(sortedIndexes), _step4; _iteratorAbruptCompletion4 = !(_step4 = await _iterator4.next()).done; _iteratorAbruptCompletion4 = false) {
const index = _step4.value;
{
await removeMainMeasure(this, index);
}
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (_iteratorAbruptCompletion4 && _iterator4.return != null) {
await _iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
}
return deletedMeasures;
}
/**
* @private
* @param {number} index
* @param {qix.NxMeasure} measure
* @returns {Promise<qix.NxMeasure>} replaced measure
* @description Replaces a measure in the hypercube.
* @memberof HyperCubeHandler
* @example
* const updatedMeasure = await hyperCubeHandler.replaceMeasure(0, {qDef :{ cId: 'id'}});
*/
replaceMeasure(index, measure) {
return this.autoSortMeasure(measure).then(() => replaceMeasureToColumnOrder(this, index, measure));
}
/**
* @private
* @param {qix.NxMeasure} measure
* @param {boolean} alternative
* @param {number} index
* @returns {Promise<qix.NxMeasure>} reinserted measure
* @description Reinserts a measure into the hypercube.
* @memberof HyperCubeHandler
* @example
* const reinsertedMeasure = await hyperCubeHandler.reinsertMeasure({qDef :{ cId: 'id'}}, true, 0);
*/
reinsertMeasure(measure, alternative, index) {
const meas = initializeId(measure);
if (isMeasureAlternative(this, alternative)) {
return addAlternativeMeasure(this, meas, index);
}
return reinsertMainMeasure(this, meas, index);
}
/**
* Moves a measure within the hypercube.
* @private
* @param {number} fromIndex
* @param {number} toIndex
* @returns {Promise<void>}
* @description Move measure from one index to another
* @memberof HyperCubeHandler
* @example
* const result = await hyperCubeHandler.moveMeasure(0, 1);
*/
moveMeasure(fromIndex, toIndex) {
const measures = this.getMeasures();
const altMeasures = this.getAlternativeMeasures();
if (fromIndex < measures.length && toIndex < measures.length) {
// Move within main measures
return Promise.resolve(arrayUtil.move(measures, fromIndex, toIndex));
}
if (fromIndex < measures.length && toIndex >= measures.length) {
return moveMeasureFromMainToAlternative(fromIndex, toIndex, measures, altMeasures);
}
if (fromIndex >= measures.length && toIndex < measures.length) {
return moveMeasureFromAlternativeToMain(fromIndex, toIndex, measures, altMeasures);
}
return Promise.resolve(moveMeasureWithinAlternative(fromIndex, toIndex, measures, altMeasures));
}
// ----------------------------------
// ------------ OTHERS---- ----------
// ----------------------------------
/**
* Sets the sorting order for the hypercube.
* @private
* @param {number[]} arr - The new sorting order.
* @memberof HyperCubeHandler
* @example
* const newSortingOrder = [2, 0, 1];
* hyperCubeHandler.setSorting(newSortingOrder);
*/
setSorting(arr) {
if (arr && arr.length === this.hcProperties.qInterColumnSortOrder.length) {
this.hcProperties.qInterColumnSortOrder = arr;
}
}
/**
* Gets the sorting order for the hypercube.
* @private
* @returns {number[]} The current sorting order.
* @memberof HyperCubeHandler
* @example
* const currentSortingOrder = hyperCubeHandler.getSorting();
*/
getSorting() {
return this.hcProperties.qInterColumnSortOrder;
}
/**
* Changes the sorting order for the hypercube.
* @private
* @param {number} fromIdx - The index to move from.
* @param {number} toIdx - The index to move to.
* @memberof HyperCubeHandler
* @example
* const newSortingOrder = hyperCubeHandler.changeSorting(0, 1);
*/
changeSorting(fromIdx, toIdx) {
utils.move(this.hcProperties.qInterColumnSortOrder, fromIdx, toIdx);
}
/**
* Returns whether the hypercube is in straight mode or pivot mode.
* @private
* @returns {string} 'S' for straight mode, 'P' for pivot mode
* @memberof HyperCubeHandler
*/
IsHCInStraightMode() {
return this.hcProperties.qMode === 'S';
}
/**
* @private
* @param {boolean} value
* @description This flag indicates whether we enabled HC modifier and have at least one script
* @memberof HyperCubeHandler
*/
setHCEnabled(value) {
if (this.hcProperties) {
this.hcProperties.isHCEnabled = value;
}
}
/**
* Gets the dynamic scripts for the hypercube.
* @private
* @returns {Array} The dynamic scripts.
* @memberof HyperCubeHandler
*/
getDynamicScripts() {
var _this$hcProperties3;
return ((_this$hcProperties3 = this.hcProperties) === null || _this$hcProperties3 === void 0 ? void 0 : _this$hcProperties3.qDynamicScript) || [];
}
} exports("L", HyperCubeHandler);
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}
*/
/**
* @callback onPropertyChange
* @param {qix.GenericObjectProperties} properties
*/
/**
* @interface QAEProperties
* @property {qix.GenericObjectProperties=} initial
* @property {onPropertyChange=} onChange
*/
/**
* @interface QAEDefinition
* @property {(QAEProperties|qix.GenericObjectProperties)=} properties
* @property {object=} data
* @property {DataTarget[]} data.targets
* @property {importProperties=} importProperties
* @property {exportProperties=} exportProperties
*/
/**
* @interface DataTarget
* @property {string} path
* @property {FieldTarget<qix.NxDimension>=} dimensions
* @property {FieldTarget<qix.NxMeasure>=} measures
*/
/**
* @callback fieldTargetAddedCallback
* @template T
* @param {T} field
* @param {qix.GenericObjectProperties} properties
*/
/**
* @callback fieldTargetRemovedCallback
* @template T
* @param {T} field
* @param {qix.GenericObjectProperties} properties
* @param {number} index
*/
/**
* @interface FieldTarget
* @template T
* @property {function()|number} [min] Number or function that returns the minimum number of fields
* @property {function()|number} [max] Number or function that returns the maximum number of fields
* @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|qChildList)$/.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, /qListObjectDef, or /qChildListDef, 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) {
var _sn$dataHandler, _sn;
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) {
return create$2(generator, params, galaxy);
},
definition: galaxy.flags.isEnabled('NEBULA_DATA_HANDLERS') ? {
dataHandler: (_sn$dataHandler = (_sn = sn) === null || _sn === void 0 ? void 0 : _sn.dataHandler) !== null && _sn$dataHandler !== void 0 ? _sn$dataHandler : opts => new HyperCubeHandler(opts)
} : {}
};
Object.keys(sn).forEach(key => {
if (!generator[key]) {
generator.definition[key] = sn[key];
}
});
return generator;
}
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 PREFIX$3 = 'Progress';
const classes$3 = {
root: "".concat(PREFIX$3, "-root"),
front: "".concat(PREFIX$3, "-front"),
back: "".concat(PREFIX$3, "-back")
};
const Root = styled('div')(_ref => {
let {
theme
} = _ref;
return {
["&.".concat(classes$3.root)]: {
position: 'relative',
display: 'inline-block'
},
["& .".concat(classes$3.front)]: {
color: theme.palette.secondary.main,
animationDuration: '1500ms',
position: 'absolute',
left: 0
},
["& .".concat(classes$3.back)]: {
color: theme.palette.divider
}
};
});
const SIZES = {
small: 16,
medium: 32,
large: 64,
xlarge: 128
};
function Progress(_ref2) {
let {
size = 'medium'
} = _ref2,
props = _objectWithoutProperties(_ref2, _excluded$2);
const s = SIZES[size];
return /*#__PURE__*/React.createElement(Root, {
className: classes$3.root
}, /*#__PURE__*/React.createElement(CircularProgress, _extends$1({
variant: "determinate",
value: 100,
className: classes$3.back,
size: s,
thickness: 3
}, props)), /*#__PURE__*/React.createElement(CircularProgress, _extends$1({
variant: "indeterminate",
disableShrink: true,
className: classes$3.front,
size: s,
thickness: 3
}, props)));
}
const _excluded$1 = ["cancel", "translator"],
_excluded2 = ["retry", "translator"];
const PREFIX$2 = 'LongRunningQuery';
const classes$2 = {
stripes: "".concat(PREFIX$2, "-stripes")
};
const StyledGrid$2 = styled(Grid)(() => ({
["& .".concat(classes$2.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(_ref, _excluded$1);
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(StyledGrid$2, {
container: true,
item: true,
direction: "column",
alignItems: "center",
gap: 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$1({
item: true
}, props), /*#__PURE__*/React.createElement(Button, {
variant: "contained",
onClick: cancel
}, translator.get('Cancel'))));
}
function Retry(_ref2) {
let {
retry,
translator
} = _ref2,
props = _objectWithoutProperties(_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$1({
variant: "contained",
onClick: retry
}, props), translator.get('Retry'))));
}
function LongRunningQuery(_ref3) {
let {
canCancel,
canRetry,
api
} = _ref3;
const {
translator
} = reactExports.useContext(InstanceContext);
return /*#__PURE__*/React.createElement(Grid, {
container: true,
direction: "column",
alignItems: "center",
justifyContent: "center",
className: classes$2.stripes,
style: {
position: 'absolute',
width: '100%',
height: '100%',
left: 0,
top: 0
},
gap: 2
}, canCancel && /*#__PURE__*/React.createElement(Cancel, {
cancel: api.cancel,
translator: translator,
className: classes$2.cancel
}), canRetry && /*#__PURE__*/React.createElement(Retry, {
retry: api.retry,
translator: translator,
className: classes$2.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
},
gap: 2
}, /*#__PURE__*/React.createElement(Progress, {
size: "large"
}));
}
const hiddenScreenReaderText = {
width: 0,
height: 0
};
const PREFIX$1 = 'Header';
const classes$1 = {
containerStyle: "".concat(PREFIX$1, "-containerStyle"),
containerTitleStyle: "".concat(PREFIX$1, "-containerTitleStyle")
};
const StyledGrid$1 = styled(Grid)(_ref => {
let {
theme
} = _ref;
return {
["&.".concat(classes$1.containerStyle)]: {
flexGrow: 0
},
["&.".concat(classes$1.containerTitleStyle)]: {
paddingBottom: theme.spacing(1)
}
};
});
/**
* @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'
};
function Header(_ref2) {
let {
id,
layout,
sn,
anchorEl,
hovering,
focusHandler,
titleStyles = {},
isRtl,
translator
} = _ref2;
const showTitle = layout.showTitles && !!layout.title;
const showSubtitle = layout.showTitles && !!layout.subtitle;
const showInSelectionActions = layout.qSelectionInfo && layout.qSelectionInfo.qInSelections;
const [actions, setActions] = reactExports.useState([]);
reactExports.useEffect(() => {
if (!sn || !sn.component || !sn.component.isHooked) {
return;
}
sn.component.observeActions(a => {
setActions([...a, ...(sn && sn.selectionToolbar && sn.selectionToolbar.items || [])]);
});
}, [sn]);
const showTitles = showTitle || showSubtitle;
const cls = [classes$1.containerStyle, ...(showTitles ? [classes$1.containerTitleStyle] : [])];
const showPopoverToolbar = hovering || showInSelectionActions;
const Toolbar = /*#__PURE__*/React.createElement(ActionsToolbar, {
show: false,
selections: {
show: showInSelectionActions,
api: sn.component.selections,
onKeyDeactivate: focusHandler.refocusContent
},
actions: actions,
popover: {
show: showPopoverToolbar,
anchorEl
},
focusHandler: focusHandler,
layout: layout,
isRtl: isRtl
});
return /*#__PURE__*/React.createElement(StyledGrid$1, {
item: true,
container: true,
wrap: "nowrap",
className: cls.join(' ')
}, /*#__PURE__*/React.createElement(Grid, {
item: true,
zeroMinWidth: true,
xs: true,
dir: isRtl ? 'rtl' : 'ltr'
}, /*#__PURE__*/React.createElement(Grid, {
container: true,
wrap: "nowrap",
direction: "column"
}, showTitle ? /*#__PURE__*/React.createElement(Tooltip, {
title: layout.title
}, /*#__PURE__*/React.createElement(Typography, {
id: "".concat(id, "_title"),
variant: "h6",
noWrap: true,
className: CellTitle.className,
style: titleStyles.main
}, layout.title)) : /*#__PURE__*/React.createElement("div", {
id: "".concat(id, "_title"),
style: hiddenScreenReaderText,
"aria-label": translator.get('Accessibility.Object.NoTitle')
}), showSubtitle && /*#__PURE__*/React.createElement(Tooltip, {
title: layout.subtitle
}, /*#__PURE__*/React.createElement(Typography, {
variant: "body2",
noWrap: true,
className: CellSubTitle.className,
style: titleStyles.subTitle
}, layout.subtitle)))), /*#__PURE__*/React.createElement(Grid, {
item: true
}, Toolbar));
}
const FilterType = {
VALUES: 'values',
CONDITION: 'condition',
SEARCH: 'search',
CLEAR_SELECTION: 'clear_selection'
};
const SearchMode = {
CONTAINS: 'contains',
MATCHES_EXACTLY: 'matches_exactly',
STARTS_WITH: 'starts_with',
ENDS_WITH: 'ends_with',
BEGINNING_OF_WORD: 'beginning_of_word'
};
const ConditionMode = {
GENERAL: 'general'
};
const ModifierType = {
FIXED_VALUE: 'fixed_value'
};
const generateSearchValue = filter => {
var _filter$options, _filter$options$value, _filter$options$value2;
let prefix = '';
let postfix = '';
const mode = (_filter$options = filter.options) === null || _filter$options === void 0 ? void 0 : _filter$options.mode;
switch (mode) {
case SearchMode.BEGINNING_OF_WORD:
prefix = '*^';
postfix = '*';
break;
case SearchMode.ENDS_WITH:
prefix = '*';
break;
case SearchMode.STARTS_WITH:
postfix = '*';
break;
case SearchMode.MATCHES_EXACTLY:
break;
case SearchMode.CONTAINS:
default:
prefix = '*';
postfix = '*';
break;
}
const value = (_filter$options$value = (_filter$options$value2 = filter.options.values) === null || _filter$options$value2 === void 0 ? void 0 : _filter$options$value2[0]) !== null && _filter$options$value !== void 0 ? _filter$options$value : '';
return value !== '' ? "\"".concat(prefix).concat(value).concat(postfix, "\"") : '';
};
const generateConditionValue = filter => {
var _options$modifier, _options$modifier2, _options$firstValue, _options$firstValue2, _options$firstValue3, _options$conditionFie, _options$conditionFie2;
const {
options
} = filter;
const isGeneralMode = (options === null || options === void 0 ? void 0 : options.mode) === ConditionMode.GENERAL;
const isFixedModifier = (options === null || options === void 0 || (_options$modifier = options.modifier) === null || _options$modifier === void 0 ? void 0 : _options$modifier.type) === ModifierType.FIXED_VALUE;
const modifierOperators = options !== null && options !== void 0 && (_options$modifier2 = options.modifier) !== null && _options$modifier2 !== void 0 && _options$modifier2.operator ? options.modifier.operator.split(' ') : [];
if (modifierOperators.length === 0 || !isFixedModifier && (!((_options$firstValue = options.firstValue) !== null && _options$firstValue !== void 0 && _options$firstValue.aggregator) || !((_options$firstValue2 = options.firstValue) !== null && _options$firstValue2 !== void 0 && _options$firstValue2.field)) || isFixedModifier && !((_options$firstValue3 = options.firstValue) !== null && _options$firstValue3 !== void 0 && _options$firstValue3.fixedValue) || isGeneralMode && (!((_options$conditionFie = options.conditionField) !== null && _options$conditionFie !== void 0 && _options$conditionFie.aggregator) || !((_options$conditionFie2 = options.conditionField) !== null && _options$conditionFie2 !== void 0 && _options$conditionFie2.field))) {
return '';
}
let conditionField;
let firstValue;
let conditionPrefix = '=';
if (isGeneralMode && isFixedModifier) {
var _options$conditionFie3, _options$conditionFie4, _options$firstValue4;
// general mode with fixed modifiers
conditionField = "".concat((_options$conditionFie3 = options.conditionField) === null || _options$conditionFie3 === void 0 ? void 0 : _options$conditionFie3.aggregator, "(").concat(escapeField((_options$conditionFie4 = options.conditionField) === null || _options$conditionFie4 === void 0 ? void 0 : _options$conditionFie4.field), ")");
firstValue = "".concat((_options$firstValue4 = options.firstValue) === null || _options$firstValue4 === void 0 ? void 0 : _options$firstValue4.fixedValue);
} else if (!isGeneralMode && isFixedModifier) {
var _options$firstValue5;
// comparing mode with fixed modifiers
conditionField = "";
firstValue = "".concat((_options$firstValue5 = options.firstValue) === null || _options$firstValue5 === void 0 ? void 0 : _options$firstValue5.fixedValue);
conditionPrefix = '';
} else if (!isGeneralMode && !isFixedModifier) {
var _options$firstValue6, _options$firstValue7;
// comparing mode without fixed modifiers
conditionField = "".concat(escapeField(filter.field));
firstValue = "".concat((_options$firstValue6 = options.firstValue) === null || _options$firstValue6 === void 0 ? void 0 : _options$firstValue6.aggregator, "(total ").concat(escapeField((_options$firstValue7 = options.firstValue) === null || _options$firstValue7 === void 0 ? void 0 : _options$firstValue7.field), ")");
} else {
var _options$conditionFie5, _options$conditionFie6, _options$firstValue8, _options$firstValue9;
// general mode without fixed modifiers
conditionField = "".concat((_options$conditionFie5 = options.conditionField) === null || _options$conditionFie5 === void 0 ? void 0 : _options$conditionFie5.aggregator, "(").concat(escapeField((_options$conditionFie6 = options.conditionField) === null || _options$conditionFie6 === void 0 ? void 0 : _options$conditionFie6.field), ")");
firstValue = "".concat((_options$firstValue8 = options.firstValue) === null || _options$firstValue8 === void 0 ? void 0 : _options$firstValue8.aggregator, "(").concat(escapeField((_options$firstValue9 = options.firstValue) === null || _options$firstValue9 === void 0 ? void 0 : _options$firstValue9.field), ")");
}
const leftConditionResult = "".concat(conditionPrefix).concat(conditionField).concat(modifierOperators[0]).concat(firstValue);
let rightConditionResult = '';
if (modifierOperators.length > 1) {
var _options$secondValue, _options$secondValue2, _options$secondValue3;
if (!isFixedModifier && (!((_options$secondValue = options.secondValue) !== null && _options$secondValue !== void 0 && _options$secondValue.aggregator) || !((_options$secondValue2 = options.secondValue) !== null && _options$secondValue2 !== void 0 && _options$secondValue2.field)) || isFixedModifier && !((_options$secondValue3 = options.secondValue) !== null && _options$secondValue3 !== void 0 && _options$secondValue3.fixedValue)) {
return '';
}
let secondValue;
let rightConditionField;
if (isGeneralMode && isFixedModifier) {
var _options$secondValue4;
// general mode with fixed modifiers
secondValue = "".concat((_options$secondValue4 = options.secondValue) === null || _options$secondValue4 === void 0 ? void 0 : _options$secondValue4.fixedValue);
rightConditionField = " and ".concat(conditionField);
} else if (!isGeneralMode && isFixedModifier) {
var _options$secondValue5;
// comparing mode with fixed modifiers
secondValue = "".concat((_options$secondValue5 = options.secondValue) === null || _options$secondValue5 === void 0 ? void 0 : _options$secondValue5.fixedValue);
rightConditionField = '';
} else if (!isGeneralMode && !isFixedModifier) {
var _options$secondValue6, _options$secondValue7;
// comparing mode without fixed modifiers
secondValue = "".concat((_options$secondValue6 = options.secondValue) === null || _options$secondValue6 === void 0 ? void 0 : _options$secondValue6.aggregator, "(total ").concat(escapeField((_options$secondValue7 = options.secondValue) === null || _options$secondValue7 === void 0 ? void 0 : _options$secondValue7.field), ")");
rightConditionField = " and ".concat(conditionField);
} else {
var _options$secondValue8, _options$secondValue9;
// general mode without fixed modifiers
secondValue = "".concat((_options$secondValue8 = options.secondValue) === null || _options$secondValue8 === void 0 ? void 0 : _options$secondValue8.aggregator, "(").concat(escapeField((_options$secondValue9 = options.secondValue) === null || _options$secondValue9 === void 0 ? void 0 : _options$secondValue9.field), ")");
rightConditionField = " and ".concat(conditionField);
}
rightConditionResult = "".concat(rightConditionField).concat(modifierOperators[1]).concat(secondValue);
}
return "\"".concat(leftConditionResult).concat(rightConditionResult, "\"");
};
const generateFiltersLabels = (filters, translator) => {
if (!Array.isArray(filters)) {
// QB-15075: when the property `filters` was already used by older apps
return [];
}
const EXCLUDE = translator.get('Object.FilterLabel.Exclude');
const filtersToShow = filters.filter(filter => filter.showInFooter !== false);
return filtersToShow.map(filter => {
var _filter$options2;
let label = '';
switch (filter.type) {
case FilterType.SEARCH:
label += generateSearchValue(filter);
break;
case FilterType.CONDITION:
label += generateConditionValue(filter);
break;
case FilterType.CLEAR_SELECTION:
label += translator.get('Object.FilterLabel.All');
break;
case FilterType.VALUES:
default:
label += (_filter$options2 = filter.options) !== null && _filter$options2 !== void 0 && _filter$options2.values ? filter.options.values.join(', ') : translator.get('Object.FilterLabel.Unknown');
break;
}
if (label !== '') {
// Trim quotes
label = label.replace(/^"|"$/g, '');
// Prefix with exclude if filter inverted
if (filter.exclude) label = "".concat(EXCLUDE, " ").concat(label);
}
return {
field: filter.field,
label
};
}).filter(filter => filter.label !== '');
};
const generateFiltersString = (filters, translator) => generateFiltersLabels(filters, translator).map(f => "".concat(f.field, ": ").concat(f.label)).join('; ');
const filter = props => _objectSpread2(_objectSpread2({}, props), {}, {
shapes: [{
type: 'path',
attrs: {
d: 'M14.07 0a1 1 0 0 1 .816 1.577L10 8.5v4.398a1 1 0 0 1-.532.884l-2.734 1.445A.5.5 0 0 1 6 14.785V8.5L1.112 1.577A1 1 0 0 1 1.93 0zm0 1H1.93L7 8.183v5.772l2-1.057V8.183z'
}
}]
});
var FilterIcon = props => SvgIcon(filter(props));
function ItalicText(_ref) {
let {
styles,
children
} = _ref;
return /*#__PURE__*/React.createElement(Typography, {
noWrap: true,
variant: "body2",
style: _objectSpread2(_objectSpread2({}, styles), {}, {
fontStyle: 'italic'
})
}, children);
}
function FiltersFooter(_ref2) {
var _layout$filters;
let {
layout,
translator,
filtersFootnoteString,
footerStyle,
isRtl
} = _ref2;
const filtersFootnoteLabels = generateFiltersLabels((_layout$filters = layout === null || layout === void 0 ? void 0 : layout.filters) !== null && _layout$filters !== void 0 ? _layout$filters : [], translator);
const styles = {
color: footerStyle === null || footerStyle === void 0 ? void 0 : footerStyle.color,
fontFamily: footerStyle === null || footerStyle === void 0 ? void 0 : footerStyle.fontFamily,
fontSize: footerStyle === null || footerStyle === void 0 ? void 0 : footerStyle.fontSize,
fontWeight: footerStyle === null || footerStyle === void 0 ? void 0 : footerStyle.fontWeight
};
return /*#__PURE__*/React.createElement(Tooltip, {
title: filtersFootnoteString
}, /*#__PURE__*/React.createElement(Grid, {
container: true,
wrap: "nowrap",
sx: {
backgroundColor: footerStyle === null || footerStyle === void 0 ? void 0 : footerStyle.backgroundColor,
padding: footerStyle === null || footerStyle === void 0 ? void 0 : footerStyle.padding,
borderTop: footerStyle === null || footerStyle === void 0 ? void 0 : footerStyle.borderTop
},
"data-testid": "filters-footnote",
justifyContent: isRtl ? 'flex-end' : 'flex-start'
}, /*#__PURE__*/React.createElement(Grid, {
item: true,
display: "flex"
}, /*#__PURE__*/React.createElement(FilterIcon, {
style: {
fontSize: '12px',
color: footerStyle.color,
margin: 'auto'
}
}), /*#__PURE__*/React.createElement(ItalicText, {
styles: _objectSpread2(_objectSpread2({}, styles), {}, {
marginLeft: '2px'
})
}, translator.get('Object.FiltersApplied'), " \xA0")), /*#__PURE__*/React.createElement(Grid, {
item: true,
display: "flex"
}, filtersFootnoteLabels.map(filter => /*#__PURE__*/React.createElement(Grid, {
container: true,
wrap: "nowrap",
key: "".concat(filter.field, "-").concat(filter.label)
}, /*#__PURE__*/React.createElement(ItalicText, {
styles: _objectSpread2(_objectSpread2({}, styles), {}, {
fontWeight: 'bold'
})
}, "".concat(filter.field, ":")), /*#__PURE__*/React.createElement(ItalicText, {
styles: styles
}, " \xA0 ", filter.label, " \xA0"))))));
}
const PREFIX = 'Footer';
const classes = {
itemStyle: "".concat(PREFIX, "-itemStyle")
};
const StyledGrid = styled(Grid)(() => ({
["& .".concat(classes.itemStyle)]: {
minWidth: 0,
width: '100%'
}
}));
/**
* @interface
* @extends HTMLElement
* @since 2.0.0
*/
const CellFooter = {
/** @type {'njs-cell-footer'} */
className: 'njs-cell-footer'
};
function Footer(_ref) {
var _layout$filters, _layout$qHyperCube, _layout$filters2;
let {
layout,
titleStyles = {},
translator,
flags,
isCardTheme,
isRtl
} = _ref;
const footerStyle = titleStyles.footer;
const hasFilters = (layout === null || layout === void 0 || (_layout$filters = layout.filters) === null || _layout$filters === void 0 ? void 0 : _layout$filters.length) > 0 && (layout === null || layout === void 0 || (_layout$qHyperCube = layout.qHyperCube) === null || _layout$qHyperCube === void 0 || (_layout$qHyperCube = _layout$qHyperCube.qMeasureInfo) === null || _layout$qHyperCube === void 0 ? void 0 : _layout$qHyperCube.length) > 0;
const filtersFootnoteString = generateFiltersString((_layout$filters2 = layout === null || layout === void 0 ? void 0 : layout.filters) !== null && _layout$filters2 !== void 0 ? _layout$filters2 : [], translator);
const showFilters = !(layout !== null && layout !== void 0 && layout.footnote) && hasFilters && filtersFootnoteString;
const themePaddingEnabled = flags === null || flags === void 0 ? void 0 : flags.isEnabled('VNA-13_CELLPADDING_FROM_THEME');
const paddingTop = isCardTheme ? '1px' : '6px';
return layout && layout.showTitles && (layout.footnote || showFilters) ? /*#__PURE__*/React.createElement(StyledGrid, {
container: true
}, /*#__PURE__*/React.createElement(Grid, {
item: true,
className: classes.itemStyle,
"data-testid": CellFooter.className,
sx: {
paddingTop: theme => themePaddingEnabled ? paddingTop : theme.spacing(1)
}
}, layout.footnote && /*#__PURE__*/React.createElement(Tooltip, {
title: layout.footnote
}, /*#__PURE__*/React.createElement(Typography, {
noWrap: true,
variant: "body2",
className: CellFooter.className,
style: footerStyle,
align: isRtl ? 'right' : 'left'
}, layout.footnote)), showFilters && /*#__PURE__*/React.createElement(FiltersFooter, {
layout: layout,
translator: translator,
filtersFootnoteString: filtersFootnoteString,
footerStyle: footerStyle,
isRtl: isRtl
}))) : 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,
cellId
} = _ref;
const {
component
} = sn;
const {
theme: themeName,
language,
constraints,
interactions,
keyboardNavigation
} = reactExports.useContext(InstanceContext);
const [renderDebouncer] = reactExports.useState(() => new RenderDebouncer());
const [isMounted, setIsMounted] = reactExports.useState(false);
const [renderCnt, setRenderCnt] = reactExports.useState(0);
const [containerRef, containerRect, containerNode] = useRect$1();
const [snNode, setSnNode] = reactExports.useState(null);
const snRef = reactExports.useCallback(ref => {
if (!ref) {
return;
}
setSnNode(ref);
}, []);
// Mount / Unmount
reactExports.useEffect(() => {
if (!snNode) return undefined;
component.created({
options
});
component.mounted(snNode);
setIsMounted(true);
return () => {
renderDebouncer.stop();
component.willUnmount();
};
}, [snNode, component]);
// Render
reactExports.useEffect(() => {
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 (!constraints.edit) {
permissions.push('edit');
}
if (halo.app && halo.app.session) {
permissions.push('fetch');
}
return Promise.resolve(component.render({
layout,
options,
plugins,
embed: halo.public.nebbie,
context: _objectSpread2({
constraints,
interactions,
// 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, interactions, 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,
id: "".concat(cellId, "_content"),
style: {
position: 'absolute',
width: '100%',
height: '100%'
}
}));
}
const THEME_OBJECT_TYPE_MAP = {
linechart: 'lineChart',
barchart: 'barChart',
combochart: 'comboChart',
scatterplot: 'scatterPlot',
piechart: 'pieChart',
straightable: 'straightTable',
pivottable: 'pivotTable',
table: 'straightTable',
'pivot-table': 'pivotTable',
listbox: 'listBox',
referenceline: 'referenceLine',
datacolors: 'dataColors',
'text-image': 'textImage',
boxplot: 'boxPlot',
map: 'mapChart',
mapchart: 'mapChart',
bulletchart: 'bulletChart',
'sn-table': 'straightTableV2'
};
const getThemeObjectType = visualization => {
if (THEME_OBJECT_TYPE_MAP[visualization.toLowerCase()]) {
return THEME_OBJECT_TYPE_MAP[visualization.toLowerCase()];
}
return visualization;
};
const useStyling = _ref => {
let {
layout,
theme,
app,
themeName,
disableThemeBorder,
queryParams
} = _ref;
const {
hostConfig
} = reactExports.useContext(InstanceContext);
const styling = reactExports.useMemo(() => {
if (layout && theme) {
const generalComp = layout.components ? layout.components.find(comp => comp.key === 'general') : null;
const objectType = getThemeObjectType(layout.visualization);
const titleStyles = {
main: resolveTextStyle(generalComp, 'main', theme, objectType),
footer: resolveTextStyle(generalComp, 'footer', theme, objectType),
subTitle: resolveTextStyle(generalComp, 'subTitle', theme, objectType)
};
const bgColor = resolveBgColor(generalComp, theme, objectType);
const bgImage = resolveBgImage(generalComp, app, queryParams, hostConfig === null || hostConfig === void 0 ? void 0 : hostConfig.host);
const border = resolveBorder(generalComp, theme, objectType, disableThemeBorder);
const borderRadius = resolveBorderRadius(generalComp, theme, objectType);
const boxShadow = resolveBoxShadow(generalComp, theme, objectType);
return {
titleStyles,
bgColor,
bgImage,
border,
borderRadius,
boxShadow
};
}
return {};
}, [layout, theme, app, themeName, disableThemeBorder]);
return styling;
};
/**
* @class RenderError
* @extends Error
* @param {string} message
* @param {Error} originalError
* @property {Error} originalError
*/
class RenderError extends Error {
constructor(message, originalError) {
super(message);
this.originalError = originalError;
this.name = 'RenderError';
}
}
const NO_BORDER_IN_CARDS = ['action-button', 'sn-nav-menu', 'filterpane', 'sn-shape'];
const NO_PADDING_IN_CARDS = [...NO_BORDER_IN_CARDS, 'pivot-table', 'table', 'sn-table', 'sn-pivot-table', 'kpi', 'sn-calendar', 'sn-filter-pane', 'sn-layout-container', 'sn-tabbed-container'];
const getPaddTitle = visualization => NO_BORDER_IN_CARDS.indexOf(visualization) === -1;
const getTitlePadding = visualization => {
const paddTitle = getPaddTitle(visualization);
if (paddTitle) {
return '10px 10px 0';
}
return '10px 0 0';
};
const getSubtitlePadding = (visualization, showTitle) => {
const paddTitle = getPaddTitle(visualization);
if (showTitle) {
if (paddTitle) {
return '0 10px';
}
return '0';
}
return getTitlePadding(visualization);
};
const getPadding = _ref => {
let {
layout,
isError,
isCardTheme,
titleStyles,
translator
} = _ref;
if (isCardTheme) {
var _layout$filters, _layout$qHyperCube, _layout$filters2;
const showTitle = (layout === null || layout === void 0 ? void 0 : layout.showTitles) && !!(layout !== null && layout !== void 0 && layout.title);
const showSubtitle = (layout === null || layout === void 0 ? void 0 : layout.showTitles) && !!(layout !== null && layout !== void 0 && layout.subtitle);
const hasFilters = (layout === null || layout === void 0 || (_layout$filters = layout.filters) === null || _layout$filters === void 0 ? void 0 : _layout$filters.length) > 0 && (layout === null || layout === void 0 || (_layout$qHyperCube = layout.qHyperCube) === null || _layout$qHyperCube === void 0 || (_layout$qHyperCube = _layout$qHyperCube.qMeasureInfo) === null || _layout$qHyperCube === void 0 ? void 0 : _layout$qHyperCube.length) > 0;
const visualization = layout === null || layout === void 0 ? void 0 : layout.visualization;
const filtersFootnoteString = generateFiltersString((_layout$filters2 = layout === null || layout === void 0 ? void 0 : layout.filters) !== null && _layout$filters2 !== void 0 ? _layout$filters2 : [], translator);
const showFilters = !(layout !== null && layout !== void 0 && layout.footnote) && hasFilters && filtersFootnoteString;
const showFootnote = (layout === null || layout === void 0 ? void 0 : layout.showTitles) && (!!(layout !== null && layout !== void 0 && layout.footnote) || showFilters);
if (showTitle) {
// eslint-disable-next-line no-param-reassign
titleStyles.main.padding = getTitlePadding(visualization);
}
if (showSubtitle) {
// eslint-disable-next-line no-param-reassign
titleStyles.subTitle.padding = getSubtitlePadding(visualization, showTitle);
}
if (showFootnote) {
if (NO_BORDER_IN_CARDS.indexOf(visualization) === -1) {
// eslint-disable-next-line no-param-reassign
titleStyles.footer.borderTop = '1px solid #d9d9d9';
}
// eslint-disable-next-line no-param-reassign
titleStyles.footer.padding = '6px 10px';
}
let bodyPadding;
if (isError || NO_PADDING_IN_CARDS.indexOf(visualization) === -1) {
bodyPadding = "".concat(showTitle || showSubtitle ? '0' : '10px', " 10px ").concat(showFootnote ? '0' : '5px');
}
return bodyPadding;
}
return undefined;
};
const translationKeys = new Map();
const extensions = [['auto-chart', 'Object.AutoChart'], ['dummy-chart', 'Dummy'], ['barchart', 'Object.BarChart'], ['combochart', 'Object.ComboChart'], ['container', 'Object.Container'], ['distributionplot', 'Object.DistributionPlot'], ['boxplot', 'Object.BoxPlot'], ['filterpane', 'Object.FilterPane'], ['gauge', 'Object.Gauge'], ['histogram', 'Object.Histogram'], ['kpi', 'Object.Kpi'], ['linechart', 'Object.LineChart'], ['listbox', 'Object.Listbox'], ['piechart', 'Object.PieChart'], ['pivot-table', 'Object.PivotTable'], ['map', 'Object.Map'], ['scatterplot', 'Object.ScatterPlot'], ['sn-table', 'Object.StraightTable'], ['text-image', 'Object.TextImage'], ['treemap', 'Object.Treemap'], ['waterfallchart', 'Object.WaterfallChart'], ['mekkochart', 'Object.MekkoChart'], ['action-button', 'Object.ActionButton'], ['sn-nav-menu', 'Object.NavMenu'], ['bulletchart', 'Object.BulletChart'], ['sn-nlg-chart', 'Object.NlgChart'], ['sn-analysis-autochart', 'Common.AnalysisTypes'], ['sn-tabbed-container', 'Object.TabContainer'], ['qlik-sankey-chart-ext', 'Object.SankeyChart'], ['qlik-radar-chart', 'Object.RadarChart'], ['qlik-funnel-chart-ext', 'Object.FunnelChart'], ['sn-grid-chart', 'Object.GridChart'], ['sn-layout-container', 'Object.LayoutContainer']];
extensions.forEach(_ref => {
let [key, value] = _ref;
translationKeys.set(key, value);
});
/**
* @interface
* @extends HTMLElement
*/
const CellElement = {
/** @type {'njs-cell'} */
className: 'njs-cell'
};
/**
* @interface
* @extends HTMLElement
*/
const CellBody = {
/** @type {'njs-cell-body'} */
className: 'njs-cell-body'
};
function support(prop, supportObject, layout) {
const value = supportObject[prop];
if (typeof value === 'function') {
return value.call(null, layout);
}
if (typeof value === 'boolean') {
return value;
}
return false;
}
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] = reactExports.useState(false);
reactExports.useEffect(() => {
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 || c.qItems), 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 || c.qItems).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,
emitter,
onMount,
navigation
} = _ref5;
try {
const snType = await getType({
types,
name: visualization,
version
});
const sn = snType.create({
model,
app,
selections,
nebbie,
focusHandler,
emitter,
navigation
});
if (sn) {
dispatch({
type: 'LOADED',
sn,
visualization
});
onMount();
}
} catch (err) {
if (!version) {
dispatch({
type: 'ERROR',
error: {
title: "Could not find a version of '".concat(visualization, "' that supports current object version. Did you forget to register ").concat(visualization, "?")
}
});
} else {
dispatch({
type: 'ERROR',
error: {
title: err.message,
errorObject: err
}
});
}
onMount();
}
};
function createEmitter() {
return new EventEmitter();
}
const Cell = reactExports.forwardRef((_ref6, ref) => {
var _halo$public$theme, _halo$public$galaxy;
let {
halo,
model: inputModel,
initialSnOptions,
initialSnPlugins,
initialError,
onMount,
currentId,
emitter,
navigation,
onError
} = _ref6;
const {
app,
types
} = halo;
const {
nebbie
} = halo.public;
const {
theme: themeName,
translator,
language,
keyboardNavigation,
externalFocusManagement,
disableCellPadding = false,
navigation: navigationApi,
queryParams
} = reactExports.useContext(InstanceContext);
const [internalEmitter] = reactExports.useState(emitter || createEmitter);
const theme = useTheme$1();
const [cellRef, cellRect, cellNode] = useRect$1();
const [state, dispatch] = reactExports.useReducer(contentReducer, initialState(initialError));
const [model, setModel] = reactExports.useState(inputModel);
const [layout, {
validating,
canCancel,
canRetry
}, longrunning] = useLayout$1(model);
const [appLayout] = useAppLayout$1(app);
const [contentRef, contentRect, contentNode] = useRect$1();
const [snOptions, setSnOptions] = reactExports.useState(initialSnOptions);
const [snPlugins, setSnPlugins] = reactExports.useState(initialSnPlugins);
const cellElementId = "njs-cell-".concat(currentId);
const [selections] = useObjectSelections(app, model, ["#".concat(cellElementId), '.njs-action-toolbar-popover']); // elements which will not trigger the click out listener
const [hovering, setHover] = reactExports.useState(false);
const hoveringDebouncer = reactExports.useRef({
enter: null,
leave: null
});
const {
titleStyles,
bgColor,
bgImage,
border,
borderRadius,
boxShadow
} = useStyling({
layout,
theme: halo.public.theme,
app: halo.app,
themeName,
disableThemeBorder: snOptions === null || snOptions === void 0 ? void 0 : snOptions.disableThemeBorder,
queryParams
});
const isRtl = !!((snOptions === null || snOptions === void 0 ? void 0 : snOptions.direction) === 'rtl');
const focusHandler = reactExports.useRef({
focusToolbarButton(last) {
// eslint-disable-next-line react/no-this-in-sfc
this.emit(last ? 'focus_toolbar_last' : 'focus_toolbar_first');
}
});
reactExports.useEffect(() => {
eventmixin(focusHandler.current);
focusHandler.current.blurCallback = resetFocus => {
if (focusHandler.current.onBlurHandler) {
focusHandler.current.onBlurHandler(resetFocus);
return;
}
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);
}
};
reactExports.useEffect(() => {
if (initialError) {
// To resolve the Viz promise for missing types
onMount();
return undefined;
}
if (!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'
});
await loadType({
dispatch,
types,
visualization,
version,
model,
app,
selections,
nebbie,
focusHandler: focusHandler.current,
emitter: internalEmitter,
onMount,
navigation: navigation !== null && navigation !== void 0 ? navigation : navigationApi
});
};
// 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);
load(layout.visualization, withVersion);
return () => {};
}, [types, state.sn, model, selections, layout, appLayout, language]);
// Long running query
reactExports.useEffect(() => {
if (!validating) {
return undefined;
}
const handle = setTimeout(() => dispatch({
type: 'LONG_RUNNING_QUERY'
}), 2000);
return () => clearTimeout(handle);
}, [validating]);
// Expose cell ref api
reactExports.useImperativeHandle(ref, () => ({
getQae() {
return state.sn.generator.qae;
},
getExtensionDefinition() {
return state.sn.generator.definition.ext;
},
// allow input of supportObject ot override when flipped to table
support(type, supportObject, outerLayout) {
if (layout && state.loaded && !state.error) {
var _state$sn$generator$d;
const suppObj = supportObject || ((_state$sn$generator$d = state.sn.generator.definition.ext) === null || _state$sn$generator$d === void 0 ? void 0 : _state$sn$generator$d.support);
if (suppObj) {
return support(type, suppObj, outerLayout || layout);
}
}
return false;
},
toggleFocus(active) {
if (typeof state.sn.component.focus === 'function') {
if (active) {
state.sn.component.focus();
} else {
state.sn.component.blur();
}
}
},
setOnBlurHandler(cb) {
focusHandler.current.onBlurHandler = cb;
},
setSnOptions,
setSnPlugins,
setModel,
getImperativeHandle() {
var _state$sn;
if ((_state$sn = state.sn) !== null && _state$sn !== void 0 && _state$sn.component && typeof state.sn.component.getImperativeHandle === 'function') {
return state.sn.component.getImperativeHandle();
}
return {};
},
onContextMenu() {
var _state$sn2;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return (_state$sn2 = state.sn) === null || _state$sn2 === void 0 ? void 0 : _state$sn2.component.onContextMenu(...args);
},
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);
},
getHypercubePath() {
var _state$sn$generator$d2;
return (_state$sn$generator$d2 = state.sn.generator.definition.ext) === null || _state$sn$generator$d2 === void 0 || (_state$sn$generator$d2 = _state$sn$generator$d2.options) === null || _state$sn$generator$d2 === void 0 ? void 0 : _state$sn$generator$d2.hypercubePath;
}
}), [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) {
if (onError) {
const e = state.error.errorObject ? state.error.errorObject : new RenderError(state.error.title);
onError(e);
}
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,
cellId: currentId
});
}
const isCardTheme = !!((_halo$public$theme = halo.public.theme) !== null && _halo$public$theme !== void 0 && _halo$public$theme.getStyle('', '', '_cards'));
const flags = (_halo$public$galaxy = halo.public.galaxy) === null || _halo$public$galaxy === void 0 ? void 0 : _halo$public$galaxy.flags;
let useOldCellPadding;
let bodyPadding;
if (disableCellPadding) {
useOldCellPadding = false;
bodyPadding = undefined;
} else if (!(flags !== null && flags !== void 0 && flags.isEnabled('VNA-13_CELLPADDING_FROM_THEME'))) {
useOldCellPadding = true;
bodyPadding = undefined;
} else {
useOldCellPadding = false;
bodyPadding = getPadding({
layout,
isError: state.error,
isCardTheme,
titleStyles,
translator
});
}
const translationKey = translationKeys.get(layout === null || layout === void 0 ? void 0 : layout.visualization);
const translation = translator.get(translationKey);
return /*#__PURE__*/React.createElement(Paper, {
style: {
position: 'relative',
width: '100%',
height: '100%',
overflow: 'hidden',
backgroundColor: bgColor || 'unset',
backgroundImage: bgImage && bgImage.url ? "url(".concat(bgImage.url, ")") : undefined,
backgroundRepeat: 'no-repeat',
backgroundSize: bgImage && bgImage.size,
backgroundPosition: bgImage && bgImage.pos,
border,
borderRadius,
boxShadow,
boxSizing: 'border-box'
},
elevation: 0,
square: true,
className: CellElement.className,
ref: cellRef,
id: cellElementId,
onMouseEnter: handleOnMouseEnter,
onMouseLeave: handleOnMouseLeave
}, /*#__PURE__*/React.createElement(Grid, {
container: true,
direction: "column",
gap: 0,
style: _objectSpread2(_objectSpread2({
position: 'relative',
width: '100%',
height: '100%'
}, useOldCellPadding ? {
padding: theme.spacing(1)
} : {}), state.longRunningQuery ? {
opacity: '0.3'
} : {}),
"aria-labelledby": "".concat(currentId, "_title ").concat(currentId, "_type ").concat(currentId, "_content")
}, layout && /*#__PURE__*/React.createElement("div", {
id: "".concat(currentId, "_type"),
style: hiddenScreenReaderText,
"aria-label": translation !== null && translation !== void 0 ? translation : layout.visualization
}), cellNode && layout && state.sn && /*#__PURE__*/React.createElement(Header, {
layout: layout,
sn: state.sn,
anchorEl: cellNode,
hovering: hovering,
focusHandler: focusHandler.current,
titleStyles: titleStyles,
isRtl: isRtl,
id: currentId,
translator: translator
}, "\xA0"), /*#__PURE__*/React.createElement(Grid, {
tabIndex: keyboardNavigation && !externalFocusManagement ? 0 : -1,
onKeyDown: keyboardNavigation && !externalFocusManagement ? handleKeyDown : null,
item: true,
xs: true,
className: CellBody.className,
style: _objectSpread2({
height: '100%'
}, bodyPadding ? {
padding: bodyPadding
} : {}),
ref: contentRef
}, Content), cellNode && layout && state.sn && /*#__PURE__*/React.createElement(Footer, {
layout: layout,
titleStyles: titleStyles,
translator: translator,
flags: flags,
isCardTheme: isCardTheme,
isRtl: isRtl
})), state.longRunningQuery && /*#__PURE__*/React.createElement(LongRunningQuery, {
canCancel: canCancel,
canRetry: canRetry,
api: longrunning
}));
});
function glue$1(_ref) {
let {
halo,
element,
model,
initialSnOptions,
initialSnPlugins,
onMount,
emitter,
initialError,
navigation,
onError
} = _ref;
const {
root
} = halo;
const cellRef = React.createRef();
const currentId = uid$1();
const portal = ReactDOM.createPortal(/*#__PURE__*/React.createElement(Cell, {
ref: cellRef,
halo: halo,
model: model,
currentId: currentId,
initialSnOptions: initialSnOptions,
initialSnPlugins: initialSnPlugins,
initialError: initialError,
onMount: onMount,
emitter: emitter,
navigation: navigation,
onError: onError
}), element, currentId);
const unmount = () => {
root.remove(portal);
model.removeListener('closed', unmount);
};
model.on('closed', unmount);
// Cannot use model.id as it is not unique in a given mashup
root.addCell(currentId, cellRef);
(async () => {
try {
await root.add(portal, unmount);
} catch (e) {
unmount();
onMount();
onError(e);
}
})();
return [unmount, cellRef];
}
function isObject(v) {
return v != null && !Array.isArray(v) && typeof v === 'object';
}
function isEqual(a, b) {
if (isObject(a) && isObject(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 canSetProperties = layout => {
var _layout$qMeta;
return !!(layout && !layout.qHasSoftPatches && !layout.qExtendsId && (((_layout$qMeta = layout.qMeta) === null || _layout$qMeta === void 0 ? void 0 : _layout$qMeta.privileges) || []).indexOf('update') > -1);
};
/* eslint-disable no-underscore-dangle */
const setProperties = (model, newProperties) => {
if (model.__snInterceptor) {
return model.__snInterceptor.setProperties.call(model, newProperties);
}
return model.setProperties(newProperties);
};
/* eslint-disable no-underscore-dangle */
const saveSoftProperties = (model, prevEffectiveProperties, effectiveProperties) => {
if (!model) {
return Promise.resolve();
}
let patches = JSONPatch.generate(prevEffectiveProperties, effectiveProperties);
originalExtend(true, prevEffectiveProperties, effectiveProperties);
if (patches && patches.length) {
patches = patches.map(p => ({
qOp: p.op,
qValue: JSON.stringify(p.value),
qPath: p.path
}));
if (model.__snInterceptor) {
return model.__snInterceptor.applyPatches.call(model, patches, true);
}
return model.applyPatches(patches, true);
}
return Promise.resolve();
};
const noopi$1 = () => {};
function viz() {
var _halo$context;
let {
model,
halo,
navigation,
initialError,
onDestroy = async () => {},
onRender = () => {},
onError = () => {}
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let unmountCell = noopi$1;
let cellRef = null;
let mountedReference = null;
let onMount = null;
let onRenderResolve = null;
let viewDataObjectId;
let originalExtensionDef;
let originalLayout;
let successfulRender = false;
const mounted = new Promise(resolve => {
onMount = resolve;
});
const rendered = new Promise(resolve => {
onRenderResolve = resolve;
});
const createOnInitialRender = override => () => {
override === null || override === void 0 || override(); // from options.onInitialRender
onRenderResolve(); // internal promise in viz to wait for render
onRender(); // from RenderConfig
successfulRender = true;
};
let initialSnOptions = {};
let initialSnPlugins = [];
const emitter = new EventEmitter();
const setSnOptions = async opts => {
const override = opts.onInitialRender;
if (mountedReference) {
(async () => {
await mounted;
cellRef.current.setSnOptions(_objectSpread2(_objectSpread2(_objectSpread2({}, initialSnOptions), opts), {
onInitialRender: createOnInitialRender(override)
}));
})();
} else {
// Handle setting options before mount
initialSnOptions = _objectSpread2(_objectSpread2(_objectSpread2({}, initialSnOptions), opts), {
onInitialRender: createOnInitialRender(override)
});
}
};
const setSnPlugins = async plugins => {
validatePlugins(plugins);
if (mountedReference) {
(async () => {
await mounted;
cellRef.current.setSnPlugins(plugins);
})();
} else {
// Handle setting plugins before mount
initialSnPlugins = plugins;
}
};
let newExperimental = {};
if ((_halo$context = halo.context) !== null && _halo$context !== void 0 && _halo$context.enablePrivateExperimental) {
// ===== undocumented experimental API - use at own risk ======
newExperimental = {
/**
* @ignore
* valid types: viewData, cssScaling, snapshot, exportData, exploration
* questionable types: supportRefresh, quickMobile, fullscreen
* deprecated?: sharing
*
*/
support(type) {
if (mountedReference && successfulRender) {
var _originalExtensionDef;
return cellRef.current.support(type, (_originalExtensionDef = originalExtensionDef) === null || _originalExtensionDef === void 0 ? void 0 : _originalExtensionDef.support, originalLayout);
}
return false;
},
getPropertyPanelDefinition() {
if (mountedReference && successfulRender) {
return originalExtensionDef ? originalExtensionDef.definition : cellRef.current.getExtensionDefinition().definition;
}
return false;
},
/**
* Gets the generic hypercube handlers
* @private
* @returns {Promise<object|undefined>} methods to handle hypercube dimensions and measures definitions and properties.
*/
async getHypercubePropertyHandler() {
await rendered;
const extensionDefinition = cellRef.current.getExtensionDefinition();
const dataDefinition = extensionDefinition.data;
const properties = await model.getEffectiveProperties();
if (dataDefinition) {
var _properties$qHyperCub, _properties$qHyperCub2;
const options = {
app: model.app,
dimensionDefinition: dataDefinition.dimensions,
measureDefinition: dataDefinition.measures,
dimensionProperties: ((_properties$qHyperCub = properties.qHyperCubeDef) === null || _properties$qHyperCub === void 0 || (_properties$qHyperCub = _properties$qHyperCub.qDimensions) === null || _properties$qHyperCub === void 0 ? void 0 : _properties$qHyperCub[0]) || helpers.getDefaultDimension(),
measureProperties: ((_properties$qHyperCub2 = properties.qHyperCubeDef) === null || _properties$qHyperCub2 === void 0 || (_properties$qHyperCub2 = _properties$qHyperCub2.qMeasures) === null || _properties$qHyperCub2 === void 0 ? void 0 : _properties$qHyperCub2[0]) || helpers.getDefaultMeasure(),
globalChangeListeners: undefined,
path: cellRef.current.getHypercubePath()
};
if (typeof extensionDefinition.definition.dataHandler === 'function') {
return extensionDefinition.definition.dataHandler(options);
}
return new HyperCubeHandler(options);
}
return undefined;
},
toggleFocus(focus) {
cellRef.current.toggleFocus(focus);
},
setOnBlurHandler(cb) {
cellRef.current.setOnBlurHandler(cb);
},
onContextMenu() {
return cellRef.current.onContextMenu(...arguments);
}
};
}
/**
* @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# */_objectSpread2(_objectSpread2({
/**
* The id of this visualization's generic object.
* @type {string}
*/
id: model.id,
/**
* This visualizations Enigma model, a representation of the generic object.
* @type {qix.GenericObject}
*/
model,
/**
* Destroys the visualization and removes it from the the DOM.
* @returns {Promise<void>}
* @example
* const viz = await embed(app).render({
* element,
* id: 'abc'
* });
* viz.destroy();
*/
async destroy() {
await onDestroy();
unmountCell();
unmountCell = noopi$1;
},
/**
* Converts the visualization to a different registered type.
*
* Will update properties if permissions allow, else will patch (can be forced with forcePatch parameter)
*
* Not all chart types are compatible, similar structures are required.
*
* @since 1.1.0
* @param {string} newType - Which registered type to convert to.
* @param {boolean=} forceUpdate - Whether to apply the change or not, else simply returns the resulting properties, defaults to true.
* @param {boolean=} forcePatch - Whether to always patch the change instead of making a permanent change
* @throws {Error} Throws an error if the source or target chart does not support conversion
* @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'
* });
* await viz.convertTo('barChart');
* // Change the barchart to a linechart, only in the current session
* const newProperties = await viz.convertTo('lineChart', false, true);
* // Remove the conversion by clearing the patches
* await viz.model.clearSoftPatches();
*/
async convertTo(newType) {
let forceUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
let forcePatch = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (forceUpdate) {
const layout = await model.getLayout();
if (canSetProperties(layout) && !forcePatch) {
const propertyTree = await convertTo({
halo,
model,
cellRef,
newType
});
await setProperties(model, propertyTree.qProperty);
return propertyTree;
}
const oldProperties = await model.getEffectiveProperties();
const propertyTree = await convertTo({
halo,
model,
cellRef,
newType,
properties: oldProperties
});
const newProperties = propertyTree.qProperty;
await saveSoftProperties(model, oldProperties, newProperties);
return propertyTree;
}
const propertyTree = await convertTo({
halo,
model,
cellRef,
newType
});
return propertyTree;
},
/**
* Toggles the chart to a data view of the chart.
*
* The chart will be toggled to the type defined in the nebula context (dataViewType).
*
* The default dataViewType for nebula is sn-table. The specified chart type needs to be registered as well, in order to make it possible to render the data view.
*
* @experimental
* @since 4.9.0
* @param {boolean=} showDataView - If included, forces the chart into a specific state. True will show data view, and false will show the original chart. If not included it will always toggle between the two views.
*/
async toggleDataView(showDataView) {
let newModel;
if (!viewDataObjectId && showDataView !== false) {
let newType = halo.context.dataViewType;
const oldProperties = await model.getEffectiveProperties();
// Check if dataViewType is registered. Otherwise potentially fallback to table
if (!halo.types.getSupportedVersion(newType)) {
if (halo.types.getSupportedVersion('table')) {
newType = 'table';
} else {
throw new Error('No data view type registered');
}
}
const propertyTree = await convertTo({
halo,
model,
cellRef,
newType,
properties: oldProperties,
viewDataMode: true
});
newModel = await halo.app.createSessionObject(propertyTree.qProperty);
viewDataObjectId = newModel.id;
originalExtensionDef = cellRef.current.getExtensionDefinition();
originalLayout = await model.getLayout();
} else if (viewDataObjectId && showDataView !== true) {
newModel = model;
await halo.app.destroySessionObject(viewDataObjectId);
viewDataObjectId = undefined;
originalExtensionDef = undefined;
originalLayout = undefined;
}
if (newModel) {
cellRef.current.setModel(newModel);
}
},
/**
* Whether or not the chart has the data view toggled on.
* @type {boolean}
*/
get viewDataToggled() {
return viewDataObjectId !== undefined;
},
/**
* Listens to custom events from inside the visualization. See useEmitter
* @param {string} eventName Event name to listen to
* @param {Function} listener Callback function to invoke
*/
addListener(eventName, listener) {
emitter.addListener(eventName, listener);
},
/**
* Removes a listener
* @param {string} eventName Event name to remove from
* @param {Function} listener Callback function to remove
*/
removeListener(eventName, listener) {
emitter.removeListener(eventName, listener);
},
/**
* Gets the specific api that a Viz exposes.
* @returns {Promise<object>} object that contains the internal Viz api.
*/
async getImperativeHandle() {
await rendered;
return cellRef.current.getImperativeHandle();
},
/**
* Takes a snapshot of the Viz layout and state
* @experimental
* @private
* @returns {Promise<object>} viz layout object with snapshot settings
*/
async takeSnapshot() {
await rendered;
return cellRef.current.takeSnapshot();
}
}, newExperimental), {}, {
// ===== unexposed experimental API - use at own risk ======
__DO_NOT_USE__: {
mount(element) {
if (mountedReference) {
throw new Error('Already mounted');
}
if (!(element instanceof HTMLElement)) {
throw new Error('Provided element is not a proper HTMLElement');
}
mountedReference = element;
[unmountCell, cellRef] = glue$1({
halo,
element,
model,
initialSnOptions,
initialSnPlugins,
initialError,
onMount,
emitter,
navigation,
onError
});
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;
},
/**
* Contains functionality related to conversions between types in the current session
* @memberof Viz#
* @ignore
* @since 4.5.0
*/
convert: {
/**
* Converts the visualization to a different registered type using a patch. Only persists in session
* @since 4.5.0
* @ignore
* @memberof Viz.convert
* @param {string} newType - Which registered type to convert to.
* @throws {Error} Throws an error if the source or target chart does not support conversion
* @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.convert.toType('barChart');
*/
async toType(newType) {
const oldProperties = await model.getEffectiveProperties();
const propertyTree = await convertTo({
halo,
model,
cellRef,
newType,
properties: oldProperties
});
const newProperties = propertyTree.qProperty;
await saveSoftProperties(model, oldProperties, newProperties);
return propertyTree;
},
/**
* Reverts any conversion done on the visualization
* @since 4.5.0
* @ignore
* @memberof Viz.convert
* @returns {Promise<object>} Promise object that resolves when the conversion is undone, returns result.
* @example
* const viz = await embed(app).render({
* element,
* id: 'abc'
* });
* viz.convert.toType('barChart');
* viz.convert.revert();
*/
async revert() {
await model.clearSoftPatches();
}
}
}
// old QVisualization API
// close() {},
// exportData() {},
// exportImg() {},
// exportPdf() {},
// setOptions() {}, // applied soft patch
// resize() {},
// show() {},
});
return api;
}
/* eslint no-underscore-dangle:0 */
async function init(model, optional, halo, navigation, initialError) {
let onDestroy = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : async () => {};
const {
onRender,
onError
} = optional;
const api = viz({
model,
halo,
navigation,
initialError,
onDestroy,
onRender,
onError
});
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 | qix.NxDimension | qix.NxMeasure | LibraryField} Field
*/
/**
* @interface RenderConfig
* @description Configuration for rendering a visualisation, either creating or fetching an existing object.
* @property {HTMLElement} element Target html element to render in to
* @property {object=} options Options passed into the visualisation
* @property {function=} onRender Callback function called after rendering successfully
* @property {function(RenderError)=} onError Callback function called if an error occurs
* @property {Plugin[]} [plugins] plugins passed into the visualisation
* @property {string=} id For existing objects: Engine identifier of object to render
* @property {string=} type For creating objects: Type of visualisation to render
* @property {string=} version For creating objects: Version of visualization to render
* @property {(Field[])=} fields For creating objects: Data fields to use
* @property {boolean=} [extendProperties=false] For creating objects: Whether to deeply extend properties or not. If false then subtrees will be overwritten.
* @property {qix.GenericObjectProperties=} properties For creating objects: Explicit properties to set
* @example
* // A config for Creating objects:
* const createConfig = {
* type: 'bar',
* element: document.querySelector('.bar'),
* extendProperties: true,
* fields: ['[Country names]', '=Sum(Sales)'],
* properties: {
* legend: {
* show: false,
* },
* }
* };
* nebbie.render(createConfig);
* // A config for rendering an existing object:
* const createConfig = {
* id: 'jG5LP',
* element: document.querySelector('.line'),
* };
* nebbie.render(createConfig);
*/
async function createSessionObject(_ref, halo, store) {
let {
type,
version,
fields,
properties,
options,
plugins,
element,
extendProperties,
navigation,
onRender,
onError
} = _ref;
let mergedProps = {};
const children = [];
const {
modelStore,
subscribe
} = store;
let error;
try {
const t = halo.types.get({
name: type,
version
});
mergedProps = await t.initialProperties(properties, extendProperties);
const sn = await t.supernova();
if (fields) {
await populateData({
sn,
properties: mergedProps,
fields,
children
}, 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);
if (children.length > 0) {
await model.setFullPropertyTree({
qProperty: mergedProps,
qChildren: children
});
}
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,
onRender,
onError
}, halo, navigation, error, onDestroy);
}
/**
* @typedef {string | qix.NxDimension | qix.NxMeasure | LibraryField} Field
*/
/**
* @interface CreateConfig
* @description Rendering configuration for creating and rendering a new object
* @property {string} type
* @property {string=} version
* @property {(Field[])=} fields
* @property {qix.GenericObjectProperties=} properties
*/
async function createObject(_ref, halo, generateOnly, store) {
let {
type,
version,
fields,
properties,
extendProperties /* , options, plugins, element */
} = _ref;
let mergedProps = {};
const children = [];
const {
modelStore
} = store;
// let error;
try {
const t = halo.types.get({
name: type,
version
});
mergedProps = await t.initialProperties(properties, extendProperties);
const sn = await t.supernova();
if (fields) {
await populateData({
sn,
properties: mergedProps,
fields,
children
}, 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
if (!generateOnly) {
mergedProps = {
qInfo: {
qType: type
},
visualization: type
};
} else {
mergedProps = null;
}
// console.error(e); // eslint-disable-line
}
if (!generateOnly) {
const model = await halo.app.createObject(mergedProps);
if (children.length > 0) {
await model.setFullPropertyTree({
qProperty: mergedProps,
qChildren: children
});
}
modelStore.set(model.id, model);
return model;
}
return mergedProps;
}
async function getObject$1(_ref, halo, store) {
let {
id,
options,
plugins,
element
} = _ref;
const {
modelStore,
rpcRequestModelStore
} = store;
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);
}
/**
* @interface
* @extends HTMLElement
* @experimental
* @since 3.1.0
*/
const SheetElement = {
/** @type {'njs-sheet'} */
className: 'njs-sheet'
};
function getCellRenderer(cell, halo, initialSnOptions, initialSnPlugins, initialError, onMount, navigation, onError) {
var _halo$public$galaxy;
const {
x,
y,
width,
height
} = cell.bounds;
const style = {
left: "".concat(x, "%"),
top: "".concat(y, "%"),
width: "".concat(width, "%"),
height: "".concat(height, "%"),
position: 'absolute'
};
const flags = (_halo$public$galaxy = halo.public.galaxy) === null || _halo$public$galaxy === void 0 ? void 0 : _halo$public$galaxy.flags;
if (flags !== null && flags !== void 0 && flags.isEnabled('VNA-13_CELLPADDING_FROM_THEME')) {
style.boxSizing = 'border-box';
style.padding = '4px';
}
return /*#__PURE__*/React.createElement("div", {
style: style,
key: cell.model.id
}, /*#__PURE__*/React.createElement(Cell, {
ref: cell.cellRef,
halo: halo,
model: cell.model,
currentId: cell.currentId,
initialSnOptions: initialSnOptions,
initialSnPlugins: initialSnPlugins,
initialError: initialError,
onMount: onMount,
navigation: navigation,
onError: onError
}));
}
function getBounds(pos, columns, rows) {
if (pos.bounds) {
return pos.bounds;
}
return {
y: pos.row / rows * 100,
x: pos.col / columns * 100,
width: pos.colspan / columns * 100,
height: pos.rowspan / rows * 100
};
}
const Sheet = reactExports.forwardRef((_ref, ref) => {
var _navigation$setCurren;
let {
model: inputModel,
halo,
initialSnOptions,
initialSnPlugins,
initialError,
onMount,
unmount,
navigation,
onError
} = _ref;
const {
root
} = halo;
const [model, setModel] = reactExports.useState(inputModel);
const [layout] = useLayout$1(model);
const {
theme: themeName,
modelStore
} = reactExports.useContext(InstanceContext);
const [cells, setCells] = reactExports.useState([]);
const [bgColor, setBgColor] = reactExports.useState(undefined);
const [bgImage, setBgImage] = reactExports.useState(undefined);
const [deepHash, setDeepHash] = reactExports.useState('');
const renderState = reactExports.useRef({
cellCount: 0,
cellsRendered: 0,
initialRender: false
});
navigation === null || navigation === void 0 || (_navigation$setCurren = navigation.setCurrentSheetId) === null || _navigation$setCurren === void 0 || _navigation$setCurren.call(navigation, model.id);
/// For each object
reactExports.useEffect(() => {
if (layout) {
const hash = JSON.stringify(layout.cells);
if (hash === deepHash) {
return;
}
setDeepHash(hash);
const fetchObjects = async () => {
/*
Need to always fetch and evaluate everything as the sheet need to support multiple instances of the same object?
No, there is no way to add the same chart twice, so the optimization should be worth it.
*/
// Clear the cell list
cells.forEach(c => {
root.removeCell(c.currentId);
});
const lCells = layout.cells;
renderState.cellCount = lCells.length;
renderState.cellsRendered = 0;
const renderCallback = () => {
renderState.cellsRendered++;
if (renderState.cellsRendered === renderState.cellCount && !renderState.initialRender) {
renderState.initialRender = true;
initialSnOptions.onInitialRender();
}
};
const {
columns,
rows
} = layout;
// TODO - should try reuse existing objects on subsequent renders
// Non-id updates should only change the "css"
const cs = await Promise.all(lCells.map(async c => {
let mounted;
const mountedPromise = new Promise(resolve => {
mounted = resolve;
});
const cell = cells.find(ce => ce.id === c.name);
if (cell) {
cell.bounds = getBounds(c, columns, rows);
delete cell.mountedPromise;
return cell;
}
const vs = await getObject$1({
id: c.name
}, halo, modelStore);
return {
model: vs.model,
id: c.name,
bounds: getBounds(c, columns, rows),
cellRef: React.createRef(),
currentId: uid$1(),
mounted,
mountedPromise,
options: _objectSpread2(_objectSpread2({}, initialSnOptions), {
onInitialRender: renderCallback
})
};
}));
cs.forEach(c => root.addCell(c.currentId, c.cellRef));
setCells(cs);
};
fetchObjects();
}
}, [layout]);
reactExports.useEffect(() => {
const onModelClose = () => {
model.removeListener('closed', onModelClose);
unmount();
};
model.on('closed', onModelClose);
return () => model.removeListener('closed', onModelClose);
}, [model]);
const cellRenderers = reactExports.useMemo(() => cells ? cells.map(c => getCellRenderer(c, halo, c.options, initialSnPlugins, initialError, c.mounted, navigation, onError)) : [], [cells]);
reactExports.useEffect(() => {
const bgComp = layout !== null && layout !== void 0 && layout.components ? layout.components.find(comp => comp.key === 'general') : null;
setBgColor(resolveBgColor(bgComp, halo.public.theme));
setBgImage(resolveBgImage(bgComp, halo.app));
}, [layout, halo.public.theme, halo.app, themeName]);
// Expose sheet ref api
reactExports.useImperativeHandle(ref, () => ({
setModel
}), []);
/* TODO
- sheet title + bg + logo etc + as option
- sheet exposed classnames for theming
*/
const height = !layout || layout.height === undefined || Number.isNaN(layout.height) ? '100%' : "".concat(Number(layout.height), "%");
const promises = cells.map(c => c.mountedPromise);
const ps = promises.filter(p => !!p);
if (ps.length) {
Promise.all(promises).then(() => {
// TODO - correct? Currently called each time a new cell is mounted?
onMount();
});
}
return /*#__PURE__*/React.createElement("div", {
className: SheetElement.className,
style: {
width: "100%",
height,
position: 'relative',
backgroundColor: bgColor,
backgroundImage: bgImage && bgImage.url ? "url(".concat(bgImage.url, ")") : undefined,
backgroundRepeat: 'no-repeat',
backgroundSize: bgImage && bgImage.size,
backgroundPosition: bgImage && bgImage.pos
}
}, cellRenderers);
});
function glue(_ref) {
let {
halo,
element,
model,
initialSnOptions,
initialSnPlugins,
onMount,
initialError,
navigation,
onError
} = _ref;
const {
root
} = halo;
const sheetRef = React.createRef();
let portal;
const unmount = () => {
root.remove(portal);
};
portal = ReactDOM.createPortal(/*#__PURE__*/React.createElement(Sheet, {
ref: sheetRef,
halo: halo,
model: model,
initialSnOptions: initialSnOptions,
initialSnPlugins: initialSnPlugins,
initialError: initialError,
onMount: onMount,
unmount: unmount,
navigation: navigation,
onError: onError
}), element, model.id);
navigation.setSheetRef(sheetRef);
root.add(portal, unmount);
return [unmount, sheetRef];
}
const noopi = () => {};
function sheet() {
let {
model,
halo,
navigation,
initialError,
onDestroy = async () => {},
onRender = () => {},
onError = () => {}
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let unmountSheet = noopi;
let sheetRef = null;
let mountedReference = null;
let onMount = null;
let onRenderResolve = null;
const mounted = new Promise(resolve => {
onMount = resolve;
});
const rendered = new Promise(resolve => {
onRenderResolve = resolve;
});
const createOnInitialRender = override => () => {
override === null || override === void 0 || override(); // from options.onInitialRender
onRenderResolve(); // internal promise in viz to wait for render
onRender(); // from RenderConfig
};
let initialSnOptions = {};
let initialSnPlugins = [];
const setSnOptions = async opts => {
const override = opts.onInitialRender;
if (mountedReference) {
(async () => {
await mounted;
sheetRef.current.setSnOptions(_objectSpread2(_objectSpread2(_objectSpread2({}, initialSnOptions), opts), {
onInitialRender: createOnInitialRender(override)
}));
})();
} else {
// Handle setting options before mount
initialSnOptions = _objectSpread2(_objectSpread2(_objectSpread2({}, initialSnOptions), opts), {
onInitialRender: createOnInitialRender(override)
});
}
};
const setSnPlugins = async plugins => {
validatePlugins(plugins);
if (mountedReference) {
(async () => {
await mounted;
sheetRef.current.setSnPlugins(plugins);
})();
} else {
// Handle setting plugins before mount
initialSnPlugins = plugins;
}
};
/**
* @class
* @alias Sheet
* @classdesc A controller to further modify a visualization after it has been rendered.
* @experimental
* @since 3.1.0
* @example
* const sheet = await embed(app).render({
* element,
* id: "jD5Gd"
* });
* sheet.destroy();
*/
const api = /** @lends Sheet# */{
/**
* The id of this sheets's generic object.
* @type {string}
*/
id: model.id,
/**
* This sheets Enigma model, a representation of the generic object.
* @type {string}
*/
model,
/**
* The navigation api to control sheet navigation.
* @experimental
* @since 5.4.0
* @type {Navigation}
*/
navigation,
/**
* Gets the specific api that a Viz exposes.
* @private currently empty and private
* @returns {Promise<object>} object that contains the internal Viz api.
*/
async getImperativeHandle() {
await rendered;
return sheetRef.current.getImperativeHandle();
},
/**
* Destroys the sheet and removes it from the the DOM.
* @example
* const sheet = await embed(app).render({
* element,
* id: "jD5Gd"
* });
* sheet.destroy();
*/
async destroy() {
await onDestroy();
unmountSheet();
unmountSheet = noopi;
},
// ===== unexposed experimental API - use at own risk ======
__DO_NOT_USE__: {
mount(element) {
if (mountedReference) {
throw new Error('Already mounted');
}
if (!(element instanceof HTMLElement)) {
throw new Error('Provided element is not a proper HTMLElement');
}
mountedReference = element;
[unmountSheet, sheetRef] = glue({
halo,
element,
model,
initialSnOptions,
initialSnPlugins,
initialError,
onMount,
navigation,
onError
});
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() {
throw new Error('Not implemented');
},
takeSnapshot() {
throw new Error('Not implemented');
},
getModel() {
return model;
}
}
};
return api;
}
/* eslint no-underscore-dangle:0 */
async function initSheet(model, optional, halo, navigation, initialError) {
let onDestroy = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : async () => {};
const {
onRender,
onError
} = optional;
const api = sheet({
model,
halo,
navigation,
initialError,
onDestroy,
onRender,
onError
});
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;
}
function createNavigationApi(halo, store, model) {
var _galaxy$anything;
const {
galaxy
} = halo.public;
if ((_galaxy$anything = galaxy.anything) !== null && _galaxy$anything !== void 0 && (_galaxy$anything = _galaxy$anything.sense) !== null && _galaxy$anything !== void 0 && _galaxy$anything.navigation) {
var _galaxy$anything2;
return (_galaxy$anything2 = galaxy.anything) === null || _galaxy$anything2 === void 0 || (_galaxy$anything2 = _galaxy$anything2.sense) === null || _galaxy$anything2 === void 0 ? void 0 : _galaxy$anything2.navigation;
}
const State = {
model
};
/**
* @class Navigation
* @description The navigation api instance.
* @implements Emitter
* @experimental
* @since 5.4.0
* @example
* const navigation = useNavigation();
* //...
* useEffect(() => {
* const onSheetChanged = () => {
* // do something
* };
* if (navigation?.addListener) {
* navigation.addListener("sheetChanged", onSheetChanged);
* }
* return () => {
* if (navigation?.removeListener) {
* navigation.removeListener("sheetChanged", onSheetChanged);
* }
* };
* }, [navigation]);
*
* const onSheetClick = (sheetId: string) => {
* navigation?.goToSheet(sheetId);
* };
*/
const navigationAPI = /** @lends Navigation# */{
/**
* Navigate to the supplied sheet and emit 'sheetChanged' event if the target sheet Id is valid.
* This allows a navigation object to synchronize its current sheet item with the active sheet.
* @experimental
* @since 5.4.0
* @param {string} sheetId Id of the sheet to navigate to
*/
goToSheet: async sheetId => {
var _State$sheetRef, _State$sheetRef$setMo;
if (!State.sheetRef) {
return;
}
const {
modelStore,
rpcRequestModelStore
} = store;
const key = "".concat(sheetId);
let rpc = rpcRequestModelStore.get(key);
if (!rpc) {
rpc = halo.app.getObject(sheetId);
rpcRequestModelStore.set(key, rpc);
}
let newModel;
try {
newModel = await rpc;
if (newModel.genericType !== 'sheet') {
return;
}
} catch (e) {
return;
}
modelStore.set(key, newModel);
(_State$sheetRef = State.sheetRef) === null || _State$sheetRef === void 0 || (_State$sheetRef = _State$sheetRef.current) === null || _State$sheetRef === void 0 || (_State$sheetRef$setMo = _State$sheetRef.setModel) === null || _State$sheetRef$setMo === void 0 || _State$sheetRef$setMo.call(_State$sheetRef, newModel);
State.model = newModel;
navigationAPI.emit('sheetChanged');
},
/**
* @private
* Set the sheet ref
* @param {object} sheetRef sheet ref object
*/
setSheetRef: sheetRef => {
State.sheetRef = sheetRef;
},
/**
* Return the current sheet id
* @experimental
* @since 5.4.0
* @returns {string|false} The current sheet Id. false means there is no current sheet.
*/
getCurrentSheetId: () => {
if (State.model) {
return State.model.id;
}
return false;
}
};
eventmixin(navigationAPI);
return navigationAPI;
}
async function getObject(_ref, halo, store) {
let {
id,
options,
plugins,
element,
onRender,
onError,
navigation: inputNavigation
} = _ref;
const {
modelStore,
rpcRequestModelStore
} = store;
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);
const navigation = inputNavigation || (model.genericType === 'sheet' ? createNavigationApi(halo, store, model) : undefined);
if (model.genericType === 'sheet') {
return initSheet(model, {
options,
plugins,
element,
onRender,
onError
}, halo, navigation);
}
return init(model, {
options,
plugins,
element,
onRender,
onError
}, halo, navigation);
}
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
};
}
var lrucache;
var hasRequiredLrucache;
function requireLrucache() {
if (hasRequiredLrucache) return lrucache;
hasRequiredLrucache = 1;
class LRUCache {
constructor() {
this.max = 1000;
this.map = new Map();
}
get(key) {
const value = this.map.get(key);
if (value === undefined) {
return undefined;
} else {
// Remove the key from the map and add it to the end
this.map.delete(key);
this.map.set(key, value);
return value;
}
}
delete(key) {
return this.map.delete(key);
}
set(key, value) {
const deleted = this.delete(key);
if (!deleted && value !== undefined) {
// If cache is full, delete the least recently used item
if (this.map.size >= this.max) {
const firstKey = this.map.keys().next().value;
this.delete(firstKey);
}
this.map.set(key, value);
}
return this;
}
}
lrucache = LRUCache;
return lrucache;
}
var parseOptions_1;
var hasRequiredParseOptions;
function requireParseOptions() {
if (hasRequiredParseOptions) return parseOptions_1;
hasRequiredParseOptions = 1;
// parse out just the options we care about
const looseOption = Object.freeze({
loose: true
});
const emptyOpts = Object.freeze({});
const parseOptions = options => {
if (!options) {
return emptyOpts;
}
if (typeof options !== 'object') {
return looseOption;
}
return options;
};
parseOptions_1 = parseOptions;
return parseOptions_1;
}
var re = {exports: {}};
var constants;
var hasRequiredConstants;
function requireConstants() {
if (hasRequiredConstants) return constants;
hasRequiredConstants = 1;
// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
const SEMVER_SPEC_VERSION = '2.0.0';
const MAX_LENGTH = 256;
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */9007199254740991;
// Max safe segment length for coercion.
const MAX_SAFE_COMPONENT_LENGTH = 16;
// Max safe length for a build identifier. The max length minus 6 characters for
// the shortest version with a build 0.0.0+BUILD.
const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
const RELEASE_TYPES = ['major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease'];
constants = {
MAX_LENGTH,
MAX_SAFE_COMPONENT_LENGTH,
MAX_SAFE_BUILD_LENGTH,
MAX_SAFE_INTEGER,
RELEASE_TYPES,
SEMVER_SPEC_VERSION,
FLAG_INCLUDE_PRERELEASE: 0b001,
FLAG_LOOSE: 0b010
};
return constants;
}
var debug_1;
var hasRequiredDebug;
function requireDebug() {
if (hasRequiredDebug) return debug_1;
hasRequiredDebug = 1;
const debug = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return console.error('SEMVER', ...args);
} : () => {};
debug_1 = debug;
return debug_1;
}
var hasRequiredRe;
function requireRe() {
if (hasRequiredRe) return re.exports;
hasRequiredRe = 1;
(function (module, exports$1) {
const {
MAX_SAFE_COMPONENT_LENGTH,
MAX_SAFE_BUILD_LENGTH,
MAX_LENGTH
} = requireConstants();
const debug = requireDebug();
exports$1 = module.exports = {};
// The actual regexps go on exports.re
const re = exports$1.re = [];
const safeRe = exports$1.safeRe = [];
const src = exports$1.src = [];
const safeSrc = exports$1.safeSrc = [];
const t = exports$1.t = {};
let R = 0;
const LETTERDASHNUMBER = '[a-zA-Z0-9-]';
// Replace some greedy regex tokens to prevent regex dos issues. These regex are
// used internally via the safeRe object since all inputs in this library get
// normalized first to trim and collapse all extra whitespace. The original
// regexes are exported for userland consumption and lower level usage. A
// future breaking change could export the safer regex only with a note that
// all input should have extra whitespace removed.
const safeRegexReplacements = [['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]];
const makeSafeRegex = value => {
for (const [token, max] of safeRegexReplacements) {
value = value.split("".concat(token, "*")).join("".concat(token, "{0,").concat(max, "}")).split("".concat(token, "+")).join("".concat(token, "{1,").concat(max, "}"));
}
return value;
};
const createToken = (name, value, isGlobal) => {
const safe = makeSafeRegex(value);
const index = R++;
debug(name, index, value);
t[name] = index;
src[index] = value;
safeSrc[index] = safe;
re[index] = new RegExp(value, isGlobal ? 'g' : undefined);
safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined);
};
// 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.
createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*');
createToken('NUMERICIDENTIFIERLOOSE', '\\d+');
// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.
createToken('NONNUMERICIDENTIFIER', "\\d*[a-zA-Z-]".concat(LETTERDASHNUMBER, "*"));
// ## Main Version
// Three dot-separated numeric identifiers.
createToken('MAINVERSION', "(".concat(src[t.NUMERICIDENTIFIER], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIER], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIER], ")"));
createToken('MAINVERSIONLOOSE', "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")"));
// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
// Non-numberic identifiers include numberic identifiers but can be longer.
// Therefore non-numberic identifiers must go first.
createToken('PRERELEASEIDENTIFIER', "(?:".concat(src[t.NONNUMERICIDENTIFIER], "|").concat(src[t.NUMERICIDENTIFIER], ")"));
createToken('PRERELEASEIDENTIFIERLOOSE', "(?:".concat(src[t.NONNUMERICIDENTIFIER], "|").concat(src[t.NUMERICIDENTIFIERLOOSE], ")"));
// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.
createToken('PRERELEASE', "(?:-(".concat(src[t.PRERELEASEIDENTIFIER], "(?:\\.").concat(src[t.PRERELEASEIDENTIFIER], ")*))"));
createToken('PRERELEASELOOSE', "(?:-?(".concat(src[t.PRERELEASEIDENTIFIERLOOSE], "(?:\\.").concat(src[t.PRERELEASEIDENTIFIERLOOSE], ")*))"));
// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.
createToken('BUILDIDENTIFIER', "".concat(LETTERDASHNUMBER, "+"));
// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.
createToken('BUILD', "(?:\\+(".concat(src[t.BUILDIDENTIFIER], "(?:\\.").concat(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.
createToken('FULLPLAIN', "v?".concat(src[t.MAINVERSION]).concat(src[t.PRERELEASE], "?").concat(src[t.BUILD], "?"));
createToken('FULL', "^".concat(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.
createToken('LOOSEPLAIN', "[v=\\s]*".concat(src[t.MAINVERSIONLOOSE]).concat(src[t.PRERELEASELOOSE], "?").concat(src[t.BUILD], "?"));
createToken('LOOSE', "^".concat(src[t.LOOSEPLAIN], "$"));
createToken('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.
createToken('XRANGEIDENTIFIERLOOSE', "".concat(src[t.NUMERICIDENTIFIERLOOSE], "|x|X|\\*"));
createToken('XRANGEIDENTIFIER', "".concat(src[t.NUMERICIDENTIFIER], "|x|X|\\*"));
createToken('XRANGEPLAIN', "[v=\\s]*(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:".concat(src[t.PRERELEASE], ")?").concat(src[t.BUILD], "?") + ")?)?");
createToken('XRANGEPLAINLOOSE', "[v=\\s]*(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:".concat(src[t.PRERELEASELOOSE], ")?").concat(src[t.BUILD], "?") + ")?)?");
createToken('XRANGE', "^".concat(src[t.GTLT], "\\s*").concat(src[t.XRANGEPLAIN], "$"));
createToken('XRANGELOOSE', "^".concat(src[t.GTLT], "\\s*").concat(src[t.XRANGEPLAINLOOSE], "$"));
// Coercion.
// Extract anything that could conceivably be a part of a valid semver
createToken('COERCEPLAIN', "".concat('(^|[^\\d])' + '(\\d{1,').concat(MAX_SAFE_COMPONENT_LENGTH, "})") + "(?:\\.(\\d{1,".concat(MAX_SAFE_COMPONENT_LENGTH, "}))?") + "(?:\\.(\\d{1,".concat(MAX_SAFE_COMPONENT_LENGTH, "}))?"));
createToken('COERCE', "".concat(src[t.COERCEPLAIN], "(?:$|[^\\d])"));
createToken('COERCEFULL', src[t.COERCEPLAIN] + "(?:".concat(src[t.PRERELEASE], ")?") + "(?:".concat(src[t.BUILD], ")?") + "(?:$|[^\\d])");
createToken('COERCERTL', src[t.COERCE], true);
createToken('COERCERTLFULL', src[t.COERCEFULL], true);
// Tilde ranges.
// Meaning is "reasonably at or greater than"
createToken('LONETILDE', '(?:~>?)');
createToken('TILDETRIM', "(\\s*)".concat(src[t.LONETILDE], "\\s+"), true);
exports$1.tildeTrimReplace = '$1~';
createToken('TILDE', "^".concat(src[t.LONETILDE]).concat(src[t.XRANGEPLAIN], "$"));
createToken('TILDELOOSE', "^".concat(src[t.LONETILDE]).concat(src[t.XRANGEPLAINLOOSE], "$"));
// Caret ranges.
// Meaning is "at least and backwards compatible with"
createToken('LONECARET', '(?:\\^)');
createToken('CARETTRIM', "(\\s*)".concat(src[t.LONECARET], "\\s+"), true);
exports$1.caretTrimReplace = '$1^';
createToken('CARET', "^".concat(src[t.LONECARET]).concat(src[t.XRANGEPLAIN], "$"));
createToken('CARETLOOSE', "^".concat(src[t.LONECARET]).concat(src[t.XRANGEPLAINLOOSE], "$"));
// A simple gt/lt/eq thing, or just "" to indicate "any version"
createToken('COMPARATORLOOSE', "^".concat(src[t.GTLT], "\\s*(").concat(src[t.LOOSEPLAIN], ")$|^$"));
createToken('COMPARATOR', "^".concat(src[t.GTLT], "\\s*(").concat(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`
createToken('COMPARATORTRIM', "(\\s*)".concat(src[t.GTLT], "\\s*(").concat(src[t.LOOSEPLAIN], "|").concat(src[t.XRANGEPLAIN], ")"), true);
exports$1.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.
createToken('HYPHENRANGE', "^\\s*(".concat(src[t.XRANGEPLAIN], ")") + "\\s+-\\s+" + "(".concat(src[t.XRANGEPLAIN], ")") + "\\s*$");
createToken('HYPHENRANGELOOSE', "^\\s*(".concat(src[t.XRANGEPLAINLOOSE], ")") + "\\s+-\\s+" + "(".concat(src[t.XRANGEPLAINLOOSE], ")") + "\\s*$");
// Star ranges basically just allow anything at all.
createToken('STAR', '(<|>)?=?\\s*\\*');
// >=0.0.0 is like a star
createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$');
createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$');
})(re, re.exports);
return re.exports;
}
var identifiers;
var hasRequiredIdentifiers;
function requireIdentifiers() {
if (hasRequiredIdentifiers) return identifiers;
hasRequiredIdentifiers = 1;
const numeric = /^[0-9]+$/;
const compareIdentifiers = (a, b) => {
const anum = numeric.test(a);
const 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;
};
const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
identifiers = {
compareIdentifiers,
rcompareIdentifiers
};
return identifiers;
}
var semver;
var hasRequiredSemver;
function requireSemver() {
if (hasRequiredSemver) return semver;
hasRequiredSemver = 1;
const debug = requireDebug();
const {
MAX_LENGTH,
MAX_SAFE_INTEGER
} = requireConstants();
const {
safeRe: re,
t
} = requireRe();
const parseOptions = requireParseOptions();
const {
compareIdentifiers
} = requireIdentifiers();
class SemVer {
constructor(version, options) {
options = parseOptions(options);
if (version instanceof SemVer) {
if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
return version;
} else {
version = version.version;
}
} else if (typeof version !== 'string') {
throw new TypeError("Invalid version. Must be a string. Got type \"".concat(typeof version, "\"."));
}
if (version.length > MAX_LENGTH) {
throw new TypeError("version is longer than ".concat(MAX_LENGTH, " characters"));
}
debug('SemVer', version, options);
this.options = options;
this.loose = !!options.loose;
// this isn't actually relevant for versions, but keep it so that we
// don't run into trouble passing this.options around.
this.includePrerelease = !!options.includePrerelease;
const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
if (!m) {
throw new TypeError("Invalid Version: ".concat(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(id => {
if (/^[0-9]+$/.test(id)) {
const num = +id;
if (num >= 0 && num < MAX_SAFE_INTEGER) {
return num;
}
}
return id;
});
}
this.build = m[5] ? m[5].split('.') : [];
this.format();
}
format() {
this.version = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch);
if (this.prerelease.length) {
this.version += "-".concat(this.prerelease.join('.'));
}
return this.version;
}
toString() {
return this.version;
}
compare(other) {
debug('SemVer.compare', this.version, this.options, other);
if (!(other instanceof SemVer)) {
if (typeof other === 'string' && other === this.version) {
return 0;
}
other = new SemVer(other, this.options);
}
if (other.version === this.version) {
return 0;
}
return this.compareMain(other) || this.comparePre(other);
}
compareMain(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);
}
comparePre(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;
}
let i = 0;
do {
const a = this.prerelease[i];
const 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);
}
compareBuild(other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options);
}
let i = 0;
do {
const a = this.build[i];
const b = other.build[i];
debug('build 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.
inc(release, identifier, identifierBase) {
if (release.startsWith('pre')) {
if (!identifier && identifierBase === false) {
throw new Error('invalid increment argument: identifier is empty');
}
// Avoid an invalid semver results
if (identifier) {
const match = "-".concat(identifier).match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]);
if (!match || match[1] !== identifier) {
throw new Error("invalid identifier: ".concat(identifier));
}
}
}
switch (release) {
case 'premajor':
this.prerelease.length = 0;
this.patch = 0;
this.minor = 0;
this.major++;
this.inc('pre', identifier, identifierBase);
break;
case 'preminor':
this.prerelease.length = 0;
this.patch = 0;
this.minor++;
this.inc('pre', identifier, identifierBase);
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, identifierBase);
this.inc('pre', identifier, identifierBase);
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, identifierBase);
}
this.inc('pre', identifier, identifierBase);
break;
case 'release':
if (this.prerelease.length === 0) {
throw new Error("version ".concat(this.raw, " is not a prerelease"));
}
this.prerelease.length = 0;
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':
{
const base = Number(identifierBase) ? 1 : 0;
if (this.prerelease.length === 0) {
this.prerelease = [base];
} else {
let 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
if (identifier === this.prerelease.join('.') && identifierBase === false) {
throw new Error('invalid increment argument: identifier already exists');
}
this.prerelease.push(base);
}
}
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
let prerelease = [identifier, base];
if (identifierBase === false) {
prerelease = [identifier];
}
if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
if (isNaN(this.prerelease[1])) {
this.prerelease = prerelease;
}
} else {
this.prerelease = prerelease;
}
}
break;
}
default:
throw new Error("invalid increment argument: ".concat(release));
}
this.raw = this.format();
if (this.build.length) {
this.raw += "+".concat(this.build.join('.'));
}
return this;
}
}
semver = SemVer;
return semver;
}
var compare_1;
var hasRequiredCompare;
function requireCompare() {
if (hasRequiredCompare) return compare_1;
hasRequiredCompare = 1;
const SemVer = requireSemver();
const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose));
compare_1 = compare;
return compare_1;
}
var eq_1;
var hasRequiredEq;
function requireEq() {
if (hasRequiredEq) return eq_1;
hasRequiredEq = 1;
const compare = requireCompare();
const eq = (a, b, loose) => compare(a, b, loose) === 0;
eq_1 = eq;
return eq_1;
}
var neq_1;
var hasRequiredNeq;
function requireNeq() {
if (hasRequiredNeq) return neq_1;
hasRequiredNeq = 1;
const compare = requireCompare();
const neq = (a, b, loose) => compare(a, b, loose) !== 0;
neq_1 = neq;
return neq_1;
}
var gt_1;
var hasRequiredGt;
function requireGt() {
if (hasRequiredGt) return gt_1;
hasRequiredGt = 1;
const compare = requireCompare();
const gt = (a, b, loose) => compare(a, b, loose) > 0;
gt_1 = gt;
return gt_1;
}
var gte_1;
var hasRequiredGte;
function requireGte() {
if (hasRequiredGte) return gte_1;
hasRequiredGte = 1;
const compare = requireCompare();
const gte = (a, b, loose) => compare(a, b, loose) >= 0;
gte_1 = gte;
return gte_1;
}
var lt_1;
var hasRequiredLt;
function requireLt() {
if (hasRequiredLt) return lt_1;
hasRequiredLt = 1;
const compare = requireCompare();
const lt = (a, b, loose) => compare(a, b, loose) < 0;
lt_1 = lt;
return lt_1;
}
var lte_1;
var hasRequiredLte;
function requireLte() {
if (hasRequiredLte) return lte_1;
hasRequiredLte = 1;
const compare = requireCompare();
const lte = (a, b, loose) => compare(a, b, loose) <= 0;
lte_1 = lte;
return lte_1;
}
var cmp_1;
var hasRequiredCmp;
function requireCmp() {
if (hasRequiredCmp) return cmp_1;
hasRequiredCmp = 1;
const eq = requireEq();
const neq = requireNeq();
const gt = requireGt();
const gte = requireGte();
const lt = requireLt();
const lte = requireLte();
const 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: ".concat(op));
}
};
cmp_1 = cmp;
return cmp_1;
}
var comparator;
var hasRequiredComparator;
function requireComparator() {
if (hasRequiredComparator) return comparator;
hasRequiredComparator = 1;
const ANY = Symbol('SemVer ANY');
// hoisted class for cyclic dependency
class Comparator {
static get ANY() {
return ANY;
}
constructor(comp, options) {
options = parseOptions(options);
if (comp instanceof Comparator) {
if (comp.loose === !!options.loose) {
return comp;
} else {
comp = comp.value;
}
}
comp = comp.trim().split(/\s+/).join(' ');
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);
}
parse(comp) {
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
const m = comp.match(r);
if (!m) {
throw new TypeError("Invalid comparator: ".concat(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);
}
}
toString() {
return this.value;
}
test(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);
}
intersects(comp, options) {
if (!(comp instanceof Comparator)) {
throw new TypeError('a Comparator is required');
}
if (this.operator === '') {
if (this.value === '') {
return true;
}
return new Range(comp.value, options).test(this.value);
} else if (comp.operator === '') {
if (comp.value === '') {
return true;
}
return new Range(this.value, options).test(comp.semver);
}
options = parseOptions(options);
// Special cases where nothing can possibly be lower
if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
return false;
}
if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
return false;
}
// Same direction increasing (> or >=)
if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
return true;
}
// Same direction decreasing (< or <=)
if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
return true;
}
// same SemVer and both sides are inclusive (<= or >=)
if (this.semver.version === comp.semver.version && this.operator.includes('=') && comp.operator.includes('=')) {
return true;
}
// opposite directions less than
if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) {
return true;
}
// opposite directions greater than
if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) {
return true;
}
return false;
}
}
comparator = Comparator;
const parseOptions = requireParseOptions();
const {
safeRe: re,
t
} = requireRe();
const cmp = requireCmp();
const debug = requireDebug();
const SemVer = requireSemver();
const Range = requireRange();
return comparator;
}
var range;
var hasRequiredRange;
function requireRange() {
if (hasRequiredRange) return range;
hasRequiredRange = 1;
const SPACE_CHARACTERS = /\s+/g;
// hoisted class for cyclic dependency
class Range {
constructor(range, options) {
options = parseOptions(options);
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) {
// just put it in the set and return
this.raw = range.value;
this.set = [[range]];
this.formatted = undefined;
return this;
}
this.options = options;
this.loose = !!options.loose;
this.includePrerelease = !!options.includePrerelease;
// First reduce all whitespace as much as possible so we do not have to rely
// on potentially slow regexes like \s*. This is then stored and used for
// future error messages as well.
this.raw = range.trim().replace(SPACE_CHARACTERS, ' ');
// First, split on ||
this.set = this.raw.split('||')
// map the range to a 2d array of comparators
.map(r => this.parseRange(r.trim()))
// throw out any comparator lists that are empty
// this generally means that it was not a valid range, which is allowed
// in loose mode, but will still throw if the WHOLE range is invalid.
.filter(c => c.length);
if (!this.set.length) {
throw new TypeError("Invalid SemVer Range: ".concat(this.raw));
}
// if we have any that are not the null set, throw out null sets.
if (this.set.length > 1) {
// keep the first one, in case they're all null sets
const first = this.set[0];
this.set = this.set.filter(c => !isNullSet(c[0]));
if (this.set.length === 0) {
this.set = [first];
} else if (this.set.length > 1) {
// if we have any that are *, then the range is just *
for (const c of this.set) {
if (c.length === 1 && isAny(c[0])) {
this.set = [c];
break;
}
}
}
}
this.formatted = undefined;
}
get range() {
if (this.formatted === undefined) {
this.formatted = '';
for (let i = 0; i < this.set.length; i++) {
if (i > 0) {
this.formatted += '||';
}
const comps = this.set[i];
for (let k = 0; k < comps.length; k++) {
if (k > 0) {
this.formatted += ' ';
}
this.formatted += comps[k].toString().trim();
}
}
}
return this.formatted;
}
format() {
return this.range;
}
toString() {
return this.range;
}
parseRange(range) {
// memoize range parsing for performance.
// this is a very hot path, and fully deterministic.
const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
const memoKey = memoOpts + ':' + range;
const cached = cache.get(memoKey);
if (cached) {
return cached;
}
const loose = this.options.loose;
// `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
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);
// `~ 1.2.3` => `~1.2.3`
range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
debug('tilde trim', range);
// `^ 1.2.3` => `^1.2.3`
range = range.replace(re[t.CARETTRIM], caretTrimReplace);
debug('caret trim', range);
// At this point, the range is completely trimmed and
// ready to be split into comparators.
let rangeList = range.split(' ').map(comp => parseComparator(comp, this.options)).join(' ').split(/\s+/)
// >=0.0.0 is equivalent to *
.map(comp => replaceGTE0(comp, this.options));
if (loose) {
// in loose mode, throw out any that are not valid comparators
rangeList = rangeList.filter(comp => {
debug('loose invalid filter', comp, this.options);
return !!comp.match(re[t.COMPARATORLOOSE]);
});
}
debug('range list', rangeList);
// if any comparators are the null set, then replace with JUST null set
// if more than one comparator, remove any * comparators
// also, don't include the same comparator more than once
const rangeMap = new Map();
const comparators = rangeList.map(comp => new Comparator(comp, this.options));
for (const comp of comparators) {
if (isNullSet(comp)) {
return [comp];
}
rangeMap.set(comp.value, comp);
}
if (rangeMap.size > 1 && rangeMap.has('')) {
rangeMap.delete('');
}
const result = [...rangeMap.values()];
cache.set(memoKey, result);
return result;
}
intersects(range, options) {
if (!(range instanceof Range)) {
throw new TypeError('a Range is required');
}
return this.set.some(thisComparators => {
return isSatisfiable(thisComparators, options) && range.set.some(rangeComparators => {
return isSatisfiable(rangeComparators, options) && thisComparators.every(thisComparator => {
return rangeComparators.every(rangeComparator => {
return thisComparator.intersects(rangeComparator, options);
});
});
});
});
}
// if ANY of the sets match ALL of its comparators, then pass
test(version) {
if (!version) {
return false;
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options);
} catch (er) {
return false;
}
}
for (let i = 0; i < this.set.length; i++) {
if (testSet(this.set[i], version, this.options)) {
return true;
}
}
return false;
}
}
range = Range;
const LRU = requireLrucache();
const cache = new LRU();
const parseOptions = requireParseOptions();
const Comparator = requireComparator();
const debug = requireDebug();
const SemVer = requireSemver();
const {
safeRe: re,
t,
comparatorTrimReplace,
tildeTrimReplace,
caretTrimReplace
} = requireRe();
const {
FLAG_INCLUDE_PRERELEASE,
FLAG_LOOSE
} = requireConstants();
const isNullSet = c => c.value === '<0.0.0-0';
const isAny = c => c.value === '';
// take a set of comparators and determine whether there
// exists a version which can satisfy it
const isSatisfiable = (comparators, options) => {
let result = true;
const remainingComparators = comparators.slice();
let testComparator = remainingComparators.pop();
while (result && remainingComparators.length) {
result = remainingComparators.every(otherComparator => {
return testComparator.intersects(otherComparator, options);
});
testComparator = remainingComparators.pop();
}
return result;
};
// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
const 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;
};
const isX = id => !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-0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
// ~0.0.1 --> >=0.0.1 <0.1.0-0
const replaceTildes = (comp, options) => {
return comp.trim().split(/\s+/).map(c => replaceTilde(c, options)).join(' ');
};
const replaceTilde = (comp, options) => {
const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
return comp.replace(r, (_, M, m, p, pr) => {
debug('tilde', comp, _, M, m, p, pr);
let ret;
if (isX(M)) {
ret = '';
} else if (isX(m)) {
ret = ">=".concat(M, ".0.0 <").concat(+M + 1, ".0.0-0");
} else if (isX(p)) {
// ~1.2 == >=1.2.0 <1.3.0-0
ret = ">=".concat(M, ".").concat(m, ".0 <").concat(M, ".").concat(+m + 1, ".0-0");
} else if (pr) {
debug('replaceTilde pr', pr);
ret = ">=".concat(M, ".").concat(m, ".").concat(p, "-").concat(pr, " <").concat(M, ".").concat(+m + 1, ".0-0");
} else {
// ~1.2.3 == >=1.2.3 <1.3.0-0
ret = ">=".concat(M, ".").concat(m, ".").concat(p, " <").concat(M, ".").concat(+m + 1, ".0-0");
}
debug('tilde return', ret);
return ret;
});
};
// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
// ^1.2.3 --> >=1.2.3 <2.0.0-0
// ^1.2.0 --> >=1.2.0 <2.0.0-0
// ^0.0.1 --> >=0.0.1 <0.0.2-0
// ^0.1.0 --> >=0.1.0 <0.2.0-0
const replaceCarets = (comp, options) => {
return comp.trim().split(/\s+/).map(c => replaceCaret(c, options)).join(' ');
};
const replaceCaret = (comp, options) => {
debug('caret', comp, options);
const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
const z = options.includePrerelease ? '-0' : '';
return comp.replace(r, (_, M, m, p, pr) => {
debug('caret', comp, _, M, m, p, pr);
let ret;
if (isX(M)) {
ret = '';
} else if (isX(m)) {
ret = ">=".concat(M, ".0.0").concat(z, " <").concat(+M + 1, ".0.0-0");
} else if (isX(p)) {
if (M === '0') {
ret = ">=".concat(M, ".").concat(m, ".0").concat(z, " <").concat(M, ".").concat(+m + 1, ".0-0");
} else {
ret = ">=".concat(M, ".").concat(m, ".0").concat(z, " <").concat(+M + 1, ".0.0-0");
}
} else if (pr) {
debug('replaceCaret pr', pr);
if (M === '0') {
if (m === '0') {
ret = ">=".concat(M, ".").concat(m, ".").concat(p, "-").concat(pr, " <").concat(M, ".").concat(m, ".").concat(+p + 1, "-0");
} else {
ret = ">=".concat(M, ".").concat(m, ".").concat(p, "-").concat(pr, " <").concat(M, ".").concat(+m + 1, ".0-0");
}
} else {
ret = ">=".concat(M, ".").concat(m, ".").concat(p, "-").concat(pr, " <").concat(+M + 1, ".0.0-0");
}
} else {
debug('no pr');
if (M === '0') {
if (m === '0') {
ret = ">=".concat(M, ".").concat(m, ".").concat(p).concat(z, " <").concat(M, ".").concat(m, ".").concat(+p + 1, "-0");
} else {
ret = ">=".concat(M, ".").concat(m, ".").concat(p).concat(z, " <").concat(M, ".").concat(+m + 1, ".0-0");
}
} else {
ret = ">=".concat(M, ".").concat(m, ".").concat(p, " <").concat(+M + 1, ".0.0-0");
}
}
debug('caret return', ret);
return ret;
});
};
const replaceXRanges = (comp, options) => {
debug('replaceXRanges', comp, options);
return comp.split(/\s+/).map(c => replaceXRange(c, options)).join(' ');
};
const replaceXRange = (comp, options) => {
comp = comp.trim();
const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
debug('xRange', comp, ret, gtlt, M, m, p, pr);
const xM = isX(M);
const xm = xM || isX(m);
const xp = xm || isX(p);
const 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
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;
}
}
if (gtlt === '<') {
pr = '-0';
}
ret = "".concat(gtlt + M, ".").concat(m, ".").concat(p).concat(pr);
} else if (xm) {
ret = ">=".concat(M, ".0.0").concat(pr, " <").concat(+M + 1, ".0.0-0");
} else if (xp) {
ret = ">=".concat(M, ".").concat(m, ".0").concat(pr, " <").concat(M, ".").concat(+m + 1, ".0-0");
}
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.
const 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], '');
};
const replaceGTE0 = (comp, options) => {
debug('replaceGTE0', comp, options);
return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '');
};
// 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-0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
// TODO build?
const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
if (isX(fM)) {
from = '';
} else if (isX(fm)) {
from = ">=".concat(fM, ".0.0").concat(incPr ? '-0' : '');
} else if (isX(fp)) {
from = ">=".concat(fM, ".").concat(fm, ".0").concat(incPr ? '-0' : '');
} else if (fpr) {
from = ">=".concat(from);
} else {
from = ">=".concat(from).concat(incPr ? '-0' : '');
}
if (isX(tM)) {
to = '';
} else if (isX(tm)) {
to = "<".concat(+tM + 1, ".0.0-0");
} else if (isX(tp)) {
to = "<".concat(tM, ".").concat(+tm + 1, ".0-0");
} else if (tpr) {
to = "<=".concat(tM, ".").concat(tm, ".").concat(tp, "-").concat(tpr);
} else if (incPr) {
to = "<".concat(tM, ".").concat(tm, ".").concat(+tp + 1, "-0");
} else {
to = "<=".concat(to);
}
return "".concat(from, " ").concat(to).trim();
};
const testSet = (set, version, options) => {
for (let 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 (let i = 0; i < set.length; i++) {
debug(set[i].semver);
if (set[i].semver === Comparator.ANY) {
continue;
}
if (set[i].semver.prerelease.length > 0) {
const 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;
};
return range;
}
var satisfies_1;
var hasRequiredSatisfies;
function requireSatisfies() {
if (hasRequiredSatisfies) return satisfies_1;
hasRequiredSatisfies = 1;
const Range = requireRange();
const satisfies = (version, range, options) => {
try {
range = new Range(range, options);
} catch (er) {
return false;
}
return range.test(version);
};
satisfies_1 = satisfies;
return satisfies_1;
}
var satisfiesExports = requireSatisfies();
var satisfies = /*@__PURE__*/getDefaultExportFromCjs(satisfiesExports);
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 RenderError("Failed to load visualization: '".concat(sKey, "'"), e);
});
}
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 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) {
let extendProperties = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
return this.supernova().then(() => {
const props = _objectSpread2({
qInfo: {
qType: type.name
},
visualization: type.name,
version: type.version,
showTitles: true
}, JSON.parse(stringified));
if (extendProperties) {
originalExtend(true, props, initial);
return props;
}
return _objectSpread2(_objectSpread2({}, props), initial);
});
}
};
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 undefined;
}
return tc[name].getMatchingVersionFromProperties(propertyVersion);
},
get(typeInfo) {
const {
name
} = typeInfo;
let {
version
} = typeInfo;
if (!tc[name]) {
// Chart not registered, so we'll do that now.
{
console.warn("Visualization ".concat(name, " is not registered. Adding it now.")); // 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);
}
};
}
/**
* @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 Component
* @property {string} key The key of the component. Currently supporting components "theme" and "selections".
* @example
* const n = embed(app);
* const inst = await n.field('field_name');
* inst.mount(document.querySelector('.listbox'), {
* components: [{
* key: 'theme',
* header: {
* fontColor: { color: '#f00' },
* fontSize: 23,
* },
* content: {
* fontSize: 16,
* useContrastColor: false,
* }
* },{
* key: 'selections',
* colors: {
* selected: { color: '#0f0' },
* alternative: { color: '#ededed' },
* excluded: { color: '#ccc' },
* selectedExcluded: { color: '#bbb' },
* possible: { color: '#fefefe' },
* possible: { color: '#fefefe' },
* }
* }]
* });
*/
/**
* Fallback load function for missing types
* @typedef {Function(LoadType):Promise<Visualization>} LoadFallback
*/
/**
* @interface Configuration
* @property {LoadFallback=} load Fallback load function for missing types
* @property {Context=} context Settings for the rendering instance
* @property {Array<TypeInfo>=} types Visualization types to register
* @property {Array<ThemeInfo>=} themes Themes to register
* @property {object=} hostConfig Qlik api compatible host config, see https://github.com/qlik-oss/qlik-api-ts/blob/main/docs/authentication.md#the-host-config
* @property {object=} anything
* @example
* import { embed } from '@nebula.js/stardust'
* n = embed(app, {
* context: {
* keyboardNavigation: true,
* theme: 'purple',
* },
* load: ({ name, version }) => {
* if (name === 'linechart') {
* return Promise.resolve(line);
* }
* },
* types: [
* {
* name: 'bar',
* load: () => Promise.resolve(bar),
* },
* ],
* themes: [
* {
* id: 'purple',
* load: () => Promise.resolve(purpleThemeJson),
* },
* ],
* });
*/
const DEFAULT_CONFIG = {
context: {},
load: () => undefined,
types: [],
themes: [],
anything: {},
flags: {
KPI_REACTCOLORPICKER: true,
CLIENT_IM_3365: true
},
snapshot: DEFAULT_SNAPSHOT_CONFIG
};
/**
* @interface Context
*/
const DEFAULT_CONTEXT = /** @lends Context */{
/** @type {string=} */
theme: 'light',
/** @type {string=} */
language: 'en-US',
/** @type {string=} */
deviceType: 'auto',
/**
* @type {Constraints=}
* @deprecated
* */
constraints: {},
/** @type {Interactions=} */
interactions: {},
/** @type {boolean=} */
keyboardNavigation: false,
/** @type {boolean=} */
disableCellPadding: false,
/**
* Type used for toggling to the data view (toggleDataView)
* This type need to be registered as well
* @type {string=}
* */
dataViewType: 'sn-table',
/** @type {Navigation=} */
navigation: undefined
};
DEFAULT_CONFIG.context = DEFAULT_CONTEXT;
/**
* @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,
loadTheme: c.loadTheme || base.loadTheme,
snapshot: _objectSpread2({}, c.snapshot || base.snapshot),
types: mergeArray(base.types, c.types),
themes: mergeArray(base.themes, c.themes),
flags: mergeObj(base.flags, c.flags),
hostConfig: c.hostConfig || base.hostConfig,
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.
*/
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 {qix.Doc} 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,
hostConfig: configuration.hostConfig
});
const [root, modelStore] = boot({
app,
context: currentContext
});
const appTheme$1 = appTheme({
themes: configuration.themes,
loadTheme: configuration.loadTheme,
root
});
currentContext.themeApi = appTheme$1.externalAPI;
const publicAPIs = {
galaxy: /** @lends Galaxy */{
/** @type {Translator} */
translator: locale.translator,
/** @type {Theme} */
theme: appTheme$1.externalAPI,
// TODO - validate flags input
/** @type {Flags} */
flags: flagsFn(configuration.flags),
/** @type {string} */
deviceType: deviceTypeFn(configuration.context.deviceType),
/** @type {object} */
hostConfig: configuration.hostConfig,
/** @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 currentSetupPromise = new Promise(resolve => {
const p = async () => {
await appTheme$1.setTheme(configuration.context.theme);
if (configuration.hostConfig && auth_default && auth_default.getWebResourceAuthParams) {
const {
queryParams
} = await auth_default.getWebResourceAuthParams({
hostConfig: configuration.hostConfig
});
currentContext.queryParams = queryParams;
root.context(currentContext);
}
};
p().then(resolve);
});
let selectionsApi = null;
let selectionsComponentReference = null;
/**
* @ignore
* @typedef { 'fieldPopoverClose' } EmbedEventTypes
*/
/**
* Event listener function on instance
*
* @ignore
* @method
* @name Embed#on
* @param {EmbedEventTypes} eventType event type that function needs to listen
* @param {Function} callback a callback function to run when event emits
* @example
* api.on('someEvent', () => {...});
*/
/**
* @class
* @alias Embed
*/
const api = /** @lends Embed# */{
/**
* Renders a visualization or sheet into an HTMLElement.
* Visualizations can either be existing objects or created on the fly.
* Support for sense sheets is experimental.
* @param {RenderConfig} cfg The render configuration.
* @returns {Promise<Viz|Sheet>} A controller to the rendered visualization or sheet.
* @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 currentSetupPromise;
if (cfg.id) {
return getObject(cfg, halo, modelStore);
}
return createSessionObject(cfg, halo, modelStore);
},
// TODO - document
destroy: async () => {
root.destroy();
},
/**
* Creates a visualization model
* @param {CreateConfig} cfg The create configuration.
* @returns {Promise<qix.GenericObject>} An engima model
* @example
* // create a barchart in the app and return the model
* const model = await n.create({
* type: 'barchart',
* fields: ['Product', { qLibraryId: 'u378hn', type: 'measure' }],
* properties: { showTitle: true }
* }
* );
*/
create: async cfg => createObject(cfg, halo, false, modelStore),
/**
* Generates properties for a visualization object
* @param {CreateConfig} cfg The create configuration.
* @returns {Promise<object>} The objects properties
* @example
* // generate properties for a barchart
* const properties = await n.generateProperties({
* type: 'barchart',
* fields: ['Product', { qLibraryId: 'u378hn', type: 'measure' }],
* properties: { showTitle: true }
* },
* );
*/
generateProperties: async cfg => createObject(cfg, halo, true, modelStore),
/**
* 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
* // change interactions
* n.context({ interactions: { select: false } });
*/
context: async ctx => {
// filter valid values to avoid triggering unnecessary rerender
let changes;
['theme', 'language', 'constraints', 'interactions', '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
});
if (changes.theme) {
await currentSetupPromise;
currentSetupPromise = appTheme$1.setTheme(changes.theme);
await currentSetupPromise;
}
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) {
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|QInfo} fieldIdentifier Fieldname as a string, a Library dimension or an object id
* @returns {Promise<FieldInstance>}
* @since 1.1.0
* @example
* const fieldInstance = await n.field("MyField");
* fieldInstance.mount(element, { title: "Hello Field"});
*/
field: async fieldIdentifier => {
let qId;
const fieldName = typeof fieldIdentifier === 'string' ? fieldIdentifier : fieldIdentifier.qLibraryId;
if (fieldIdentifier.qId) {
qId = fieldIdentifier.qId;
} else if (!fieldName) {
throw new Error("Field identifier or object id must be provided");
}
/**
* @typedef { 'ltr' | 'rtl' } Direction
*/
/**
* @typedef { 'vertical' | 'horizontal' } ListLayout
*/
/**
* @typedef { 'none' | 'value' | 'percent' | 'relative' } FrequencyMode
*/
/**
* @typedef { boolean | 'toggle' } SearchMode
*/
/**
* @typedef { 'selectionActivated' | 'selectionDeactivated' } FieldEventTypes
*/
/**
* Event listener function on instance
*
* @method
* @name FieldInstance#on
* @param {FieldEventTypes} eventType event type that function needs to listen
* @param {Function} callback a callback function to run when event emits
* @example
* const handleSomeEvent () => {...};
* fieldInstance.on('someEvent', handleSomeEvent);
* ...
* fieldInstance.removeListener('someEvent', handleSomeEvent);
*/
/**
* Remove listener on instance
*
* @method
* @name FieldInstance#removeListener
* @param {FieldEventTypes} eventType event type
* @param {Function} callback handler
*/
/**
* @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 (not applicable for existing objects)
* @param {Direction=} [options.direction=ltr] Direction setting ltr|rtl.
* @param {ListLayout=} [options.listLayout=vertical] Layout direction vertical|horizontal (not applicable for existing objects)
* @param {FrequencyMode=} [options.frequencyMode=none] Show frequency none|value|percent|relative
* @param {boolean=} [options.histogram=false] Show histogram bar (not applicable for existing objects)
* @param {SearchMode=} [options.search=true] Show the search bar permanently, using the toggle button or when in selection: false|true|toggle
* @param {boolean=} [options.showLock=false] Show the button for toggling locked state.
* @param {boolean=} [options.toolbar=true] Show the toolbar
* @param {boolean=} [options.checkboxes=false] Show values as checkboxes instead of as fields (not applicable for existing objects)
* @param {boolean=} [options.dense=false] Reduces padding and text size (not applicable for existing objects)
* @param {string=} [options.stateName="$"] Sets the state to make selections in (not applicable for existing objects)
* @param {Component[]} [options.components] Override individual components' styling, otherwise set by the theme or the default style.
* @param {object=} [options.properties={}] Properties object to extend default properties with
* @returns {Promise<void>} A promise that resolves when the data is fetched.
*
* @since 1.1.0
* @instance
* @example
* fieldInstance.mount(element);
*/
async mount(element) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!element) {
throw new Error("Element for ".concat(fieldName || qId, " not provided"));
}
if (this._instance) {
throw new Error("Field or object ".concat(fieldName || qId, " already mounted"));
}
const onSelectionActivated = () => fieldSels.emit('selectionActivated');
const onSelectionDeactivated = () => fieldSels.emit('selectionDeactivated');
return new Promise(resolve => {
[this._instance, this._ref] = ListBoxPortal({
element,
app,
fieldIdentifier,
qId,
options: getOptions$1(_objectSpread2({
onSelectionActivated,
onSelectionDeactivated
}, options)),
stateName: options.stateName || '$',
renderedCallback: resolve
});
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;
this._ref = null;
}
},
// ===== unexposed experimental API - use at own risk ======
__DO_NOT_USE__: {
options(opts) {
var _fieldSels$_ref;
const onSelectionActivated = () => fieldSels.emit('selectionActivated');
const onSelectionDeactivated = () => fieldSels.emit('selectionDeactivated');
if ((_fieldSels$_ref = fieldSels._ref) !== null && _fieldSels$_ref !== void 0 && _fieldSels$_ref.current) {
const options = getOptions$1(_objectSpread2({
onSelectionActivated,
onSelectionDeactivated
}, opts));
fieldSels._ref.current.setOptions(options);
}
}
}
};
eventmixin(fieldSels);
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,
popover(anchorElement, fieldIdentifier, options) {
if (api._popoverInstance) {
root.remove(api._popoverInstance);
api._popoverInstance = null;
}
const onPopoverClose = () => api.emit('fieldPopoverClose');
const opts = getOptions(_objectSpread2({
onPopoverClose
}, options));
api._popoverInstance = React.createElement(ListBoxPopoverWrapper, {
element: anchorElement,
key: uid$1(),
app,
fieldIdentifier,
options: opts,
stateName: options.stateName || '$'
});
root.add(api._popoverInstance);
}
}
};
halo.public.nebbie = api;
halo.types = types;
eventmixin(api);
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.
*/
/**
* @interface QInfo
* @property {string} qId Generic object id
*/
var index = exports("b", nuked(DEFAULT_CONFIG));
function SessionMock() {
return {
getObjectApi() {
return Promise.resolve({
id: "sessapi - ".concat(+Date.now())
});
}
};
}
/* eslint-disable no-underscore-dangle */
// To cover test
// 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(session) {
return props => {
const properties = originalExtend({}, 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 = originalExtend({}, properties, mockedInclusions);
}
return Promise.resolve({
on: () => {},
once: () => {},
getLayout: () => Promise.resolve(layout),
getProperties: () => Promise.resolve(properties),
getEffectiveProperties: () => Promise.resolve(properties),
removeListener: () => {},
id: properties.qInfo.qId,
properties,
session
});
};
}
/**
* 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()}'}),
* }
* ```
* @type function
* @ignore
* @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 {any} 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 })
* };
* ```
* @type function
* @ignore
* @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 {function} 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.
* @ignore
* @type Array
*/
const PROPS_SYNC = ['addListener', 'emit', 'listeners', 'on', 'once', 'removeAllListeners', 'removeListener', 'setMaxListerners'];
/**
* Is property operating asynchrously.
* @param {string} name Property name.
* @ignore
* @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
* @ignore
* @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.
* @ignore
* @returns The mocked object
*/
function createMock(genericObject, options) {
let qId = getQId(genericObject);
const {
delay
} = options;
const {
id,
session
} = genericObject,
props = _objectWithoutProperties(genericObject, _excluded);
if (id && qId && id !== qId) {
throw new Error("Generic object has multiple IDs, qInfo.qId: ".concat(qId, ", id: ").concat(id));
}
qId = qId || id || "object - ".concat(+Date.now());
const mock = _objectSpread2(_objectSpread2({
id: qId,
session: getPropValue(session, {
defaultValue: true
}),
on: () => {},
once: () => {},
removeListener: () => {}
}, Object.entries(props).reduce((fns, _ref) => {
let [name, value] = _ref;
return _objectSpread2(_objectSpread2({}, fns), {}, {
[name]: getPropFn(value, {
async: isPropAsync(name),
delay
})
});
}, {})), {}, {
genericType: genericObject.type
});
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
* @ignore
* @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
* @ignore
* @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.
* @ignore
* @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(options) {
return () => Promise.resolve({
id: 'app-layout',
qLocaleInfo: options === null || options === void 0 ? void 0 : options.appLocaleInfo
});
}
function fromGenericObjects(genericObjects) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const session = new SessionMock();
const createSessionObject = new CreateSessionObjectMock(session);
const getObject = new GetObjectMock(genericObjects, options);
const getAppLayout = new GetAppLayoutMock(options);
const app = {
id: "app - ".concat(+Date.now()),
session,
createSessionObject,
destroySessionObject: async () => {},
getObject,
getAppLayout,
getListObject: async props => {
var _props$qInfo;
return getObject((_props$qInfo = props.qInfo) === null || _props$qInfo === void 0 ? void 0 : _props$qInfo.qId);
}
};
return Promise.resolve(app);
}
/**
* @interface EnigmaMockerOptions
* @property {number} delay Simulate delay (in ms) for calls in enigma-mocker.
* @description Options for Enigma Mocker
* @experimental
* @since 3.0.0
*/
/**
* @entry
* @namespace
* @alias EnigmaMocker
* @description Mocks Engima app functionality for demo and testing purposes.
*/
const mocker = exports("m", /** @lends EnigmaMocker# */{
/**
* Mocks Engima app functionality. It accepts one / many generic objects as input argument and returns the mocked Enigma app. Each generic object represents one visualisation 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.
* @type function
* @experimental
* @since 3.0.0
* @param {Array<object>} genericObjects Generic objects controlling behaviour of visualizations.
* @param {EnigmaMockerOptions=} options Options
* @returns {Promise<qix.Doc>}
* @example
* const genericObject = {
* getLayout() {
* return {
* qInfo: {
* qId: 'qqj4zx',
* qType: 'sn-grid-chart'
* },
* ...
* }
* },
* getHyperCubeData(path, page) {
* return [ ... ];
* }
* };
* const app = await EnigmaMocker.fromGenericObjects([genericObject]);
*/
fromGenericObjects(genericObjects) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return fromGenericObjects(genericObjects, options);
}
});
/* eslint no-underscore-dangle: 0 */
// component internals
const __DO_NOT_USE__ = exports("_", {
generator: generatorFn,
hook,
theme,
locale
});
})
};
}));
//# sourceMappingURL=index-DC5bJ1TW.js.map