@shopify/polaris
Version:
Shopify’s product component library
1,614 lines (1,380 loc) • 732 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var React = require('react');
var React__default = _interopDefault(React);
var tslib = require('tslib');
var polarisIcons = require('@shopify/polaris-icons');
var focus = require('@shopify/javascript-utilities/focus');
var reactDom = require('react-dom');
var other = require('@shopify/javascript-utilities/other');
var tokens = require('@shopify/polaris-tokens');
var tokens__default = _interopDefault(tokens);
var distModern = require('@shopify/polaris-tokens/dist-modern');
var utils = require('@shopify/polaris-tokens/dist-modern/utils');
var base = require('@shopify/polaris-tokens/dist-modern/configs/base');
var math = require('@shopify/javascript-utilities/math');
var debounce = _interopDefault(require('lodash/debounce'));
var events = require('@shopify/javascript-utilities/events');
var dom = require('@shopify/javascript-utilities/dom');
var geometry = require('@shopify/javascript-utilities/geometry');
var fastdom = require('@shopify/javascript-utilities/fastdom');
var DefaultThemeColors = _interopDefault(require('@shopify/polaris-tokens/dist-modern/theme/base.json'));
var createApp = require('@shopify/app-bridge');
var createApp__default = _interopDefault(createApp);
var isEqual = _interopDefault(require('lodash/isEqual'));
var hoistStatics = _interopDefault(require('hoist-non-react-statics'));
var dates = require('@shopify/javascript-utilities/dates');
var reactTransitionGroup = require('@material-ui/react-transition-group');
var actions = require('@shopify/app-bridge/actions');
if (typeof window !== 'undefined') {
window.Polaris = window.Polaris || {};
window.Polaris.VERSION = '4.20.0';
}
var polarisVersion = '4.20.0';
var NEW_DESIGN_LANGUAGE_COLORS = ['base', 'subdued', 'critical', 'warning', 'highlight', 'success', 'primary'];
function isNewDesignLanguageColor(color) {
return NEW_DESIGN_LANGUAGE_COLORS.includes(color);
}
(function (Key) {
Key[Key["Backspace"] = 8] = "Backspace";
Key[Key["Tab"] = 9] = "Tab";
Key[Key["Enter"] = 13] = "Enter";
Key[Key["Shift"] = 16] = "Shift";
Key[Key["Ctrl"] = 17] = "Ctrl";
Key[Key["Alt"] = 18] = "Alt";
Key[Key["Pause"] = 19] = "Pause";
Key[Key["CapsLock"] = 20] = "CapsLock";
Key[Key["Escape"] = 27] = "Escape";
Key[Key["Space"] = 32] = "Space";
Key[Key["PageUp"] = 33] = "PageUp";
Key[Key["PageDown"] = 34] = "PageDown";
Key[Key["End"] = 35] = "End";
Key[Key["Home"] = 36] = "Home";
Key[Key["LeftArrow"] = 37] = "LeftArrow";
Key[Key["UpArrow"] = 38] = "UpArrow";
Key[Key["RightArrow"] = 39] = "RightArrow";
Key[Key["DownArrow"] = 40] = "DownArrow";
Key[Key["Insert"] = 45] = "Insert";
Key[Key["Delete"] = 46] = "Delete";
Key[Key["Key0"] = 48] = "Key0";
Key[Key["Key1"] = 49] = "Key1";
Key[Key["Key2"] = 50] = "Key2";
Key[Key["Key3"] = 51] = "Key3";
Key[Key["Key4"] = 52] = "Key4";
Key[Key["Key5"] = 53] = "Key5";
Key[Key["Key6"] = 54] = "Key6";
Key[Key["Key7"] = 55] = "Key7";
Key[Key["Key8"] = 56] = "Key8";
Key[Key["Key9"] = 57] = "Key9";
Key[Key["KeyA"] = 65] = "KeyA";
Key[Key["KeyB"] = 66] = "KeyB";
Key[Key["KeyC"] = 67] = "KeyC";
Key[Key["KeyD"] = 68] = "KeyD";
Key[Key["KeyE"] = 69] = "KeyE";
Key[Key["KeyF"] = 70] = "KeyF";
Key[Key["KeyG"] = 71] = "KeyG";
Key[Key["KeyH"] = 72] = "KeyH";
Key[Key["KeyI"] = 73] = "KeyI";
Key[Key["KeyJ"] = 74] = "KeyJ";
Key[Key["KeyK"] = 75] = "KeyK";
Key[Key["KeyL"] = 76] = "KeyL";
Key[Key["KeyM"] = 77] = "KeyM";
Key[Key["KeyN"] = 78] = "KeyN";
Key[Key["KeyO"] = 79] = "KeyO";
Key[Key["KeyP"] = 80] = "KeyP";
Key[Key["KeyQ"] = 81] = "KeyQ";
Key[Key["KeyR"] = 82] = "KeyR";
Key[Key["KeyS"] = 83] = "KeyS";
Key[Key["KeyT"] = 84] = "KeyT";
Key[Key["KeyU"] = 85] = "KeyU";
Key[Key["KeyV"] = 86] = "KeyV";
Key[Key["KeyW"] = 87] = "KeyW";
Key[Key["KeyX"] = 88] = "KeyX";
Key[Key["KeyY"] = 89] = "KeyY";
Key[Key["KeyZ"] = 90] = "KeyZ";
Key[Key["LeftMeta"] = 91] = "LeftMeta";
Key[Key["RightMeta"] = 92] = "RightMeta";
Key[Key["Select"] = 93] = "Select";
Key[Key["Numpad0"] = 96] = "Numpad0";
Key[Key["Numpad1"] = 97] = "Numpad1";
Key[Key["Numpad2"] = 98] = "Numpad2";
Key[Key["Numpad3"] = 99] = "Numpad3";
Key[Key["Numpad4"] = 100] = "Numpad4";
Key[Key["Numpad5"] = 101] = "Numpad5";
Key[Key["Numpad6"] = 102] = "Numpad6";
Key[Key["Numpad7"] = 103] = "Numpad7";
Key[Key["Numpad8"] = 104] = "Numpad8";
Key[Key["Numpad9"] = 105] = "Numpad9";
Key[Key["Multiply"] = 106] = "Multiply";
Key[Key["Add"] = 107] = "Add";
Key[Key["Subtract"] = 109] = "Subtract";
Key[Key["Decimal"] = 110] = "Decimal";
Key[Key["Divide"] = 111] = "Divide";
Key[Key["F1"] = 112] = "F1";
Key[Key["F2"] = 113] = "F2";
Key[Key["F3"] = 114] = "F3";
Key[Key["F4"] = 115] = "F4";
Key[Key["F5"] = 116] = "F5";
Key[Key["F6"] = 117] = "F6";
Key[Key["F7"] = 118] = "F7";
Key[Key["F8"] = 119] = "F8";
Key[Key["F9"] = 120] = "F9";
Key[Key["F10"] = 121] = "F10";
Key[Key["F11"] = 122] = "F11";
Key[Key["F12"] = 123] = "F12";
Key[Key["NumLock"] = 144] = "NumLock";
Key[Key["ScrollLock"] = 145] = "ScrollLock";
Key[Key["Semicolon"] = 186] = "Semicolon";
Key[Key["Equals"] = 187] = "Equals";
Key[Key["Comma"] = 188] = "Comma";
Key[Key["Dash"] = 189] = "Dash";
Key[Key["Period"] = 190] = "Period";
Key[Key["ForwardSlash"] = 191] = "ForwardSlash";
Key[Key["GraveAccent"] = 192] = "GraveAccent";
Key[Key["OpenBracket"] = 219] = "OpenBracket";
Key[Key["BackSlash"] = 220] = "BackSlash";
Key[Key["CloseBracket"] = 221] = "CloseBracket";
Key[Key["SingleQuote"] = 222] = "SingleQuote";
})(exports.Key || (exports.Key = {}));
(function (TypeOf) {
TypeOf["Undefined"] = "undefined";
TypeOf["Object"] = "object";
TypeOf["Boolean"] = "boolean";
TypeOf["Number"] = "number";
TypeOf["String"] = "string";
TypeOf["Symbol"] = "symbol";
TypeOf["Function"] = "function";
})(exports.TypeOf || (exports.TypeOf = {}));
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _construct(Parent, args, Class) {
if (_isNativeReflectConstruct()) {
_construct = Reflect.construct;
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) _setPrototypeOf(instance, Class.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
function _isNativeFunction(fn) {
return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function _wrapNativeSuper(Class) {
var _cache = typeof Map === "function" ? new Map() : undefined;
_wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !_isNativeFunction(Class)) return Class;
if (typeof Class !== "function") {
throw new TypeError("Super expression must either be null or a function");
}
if (typeof _cache !== "undefined") {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return _construct(Class, arguments, _getPrototypeOf(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
});
return _setPrototypeOf(Wrapper, Class);
};
return _wrapNativeSuper(Class);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
return function () {
var Super = _getPrototypeOf(Derived),
result;
if (_isNativeReflectConstruct()) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _createForOfIteratorHelper(o) {
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var it,
normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = o[Symbol.iterator]();
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
function classNames() {
for (var _len = arguments.length, classes = new Array(_len), _key = 0; _key < _len; _key++) {
classes[_key] = arguments[_key];
}
return classes.filter(Boolean).join(' ');
}
function variationName(name, value) {
return "".concat(name).concat(value.charAt(0).toUpperCase()).concat(value.slice(1));
}
var FeaturesContext = React__default.createContext(undefined);
function useFeatures() {
var features = React.useContext(FeaturesContext);
if (!features) {
throw new Error('No Features were provided.');
}
return features;
}
var I18nContext = React__default.createContext(undefined);
var MissingAppProviderError = /*#__PURE__*/function (_Error) {
_inherits(MissingAppProviderError, _Error);
var _super = _createSuper(MissingAppProviderError);
function MissingAppProviderError() {
var _this;
var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
_classCallCheck(this, MissingAppProviderError);
_this = _super.call(this, "".concat(message ? "".concat(message, " ") : message, "Your application must be wrapped in an <AppProvider> component. See https://polaris.shopify.com/components/structure/app-provider for implementation instructions."));
_this.name = 'MissingAppProviderError';
return _this;
}
return MissingAppProviderError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
function useI18n() {
var i18n = React.useContext(I18nContext);
if (!i18n) {
throw new MissingAppProviderError('No i18n was provided.');
}
return i18n;
}
var OBJECT_NOTATION_MATCHER = /\[(.*?)\]|(\w+)/g;
function get(obj, keypath, defaultValue) {
if (obj == null) return undefined;
var keys = Array.isArray(keypath) ? keypath : getKeypath(keypath);
var acc = obj; // eslint-disable-next-line @typescript-eslint/prefer-for-of
for (var i = 0; i < keys.length; i++) {
var val = acc[keys[i]];
if (val === undefined) return defaultValue;
acc = val;
}
return acc;
}
function getKeypath(str) {
var path = [];
var result;
while (result = OBJECT_NOTATION_MATCHER.exec(str)) {
var _result = result,
_result2 = _slicedToArray(_result, 3),
first = _result2[1],
second = _result2[2];
path.push(first || second);
}
return path;
}
function merge() {
var final = {};
for (var _len = arguments.length, objs = new Array(_len), _key = 0; _key < _len; _key++) {
objs[_key] = arguments[_key];
}
for (var _i = 0, _objs = objs; _i < _objs.length; _i++) {
var obj = _objs[_i];
final = mergeRecursively(final, obj);
}
return final;
}
function mergeRecursively(inputObjA, objB) {
var objA = Array.isArray(inputObjA) ? _toConsumableArray(inputObjA) : Object.assign({}, inputObjA);
for (var key in objB) {
if (!Object.prototype.hasOwnProperty.call(objB, key)) {
continue;
} else if (isMergeableValue(objB[key]) && isMergeableValue(objA[key])) {
objA[key] = mergeRecursively(objA[key], objB[key]);
} else {
objA[key] = objB[key];
}
}
return objA;
}
function isMergeableValue(value) {
return value !== null && typeof value === 'object';
}
var REPLACE_REGEX = /{([^}]*)}/g;
var I18n = /*#__PURE__*/function () {
/**
* @param translation A locale object or array of locale objects that overrides default translations. If specifying an array then your fallback language dictionaries should come first, followed by your primary language dictionary
*/
function I18n(translation) {
_classCallCheck(this, I18n);
this.translation = {};
this.translation = Array.isArray(translation) ? merge.apply(void 0, _toConsumableArray(translation)) : translation;
}
_createClass(I18n, [{
key: "translate",
value: function translate(id, replacements) {
var text = get(this.translation, id, '');
if (!text) {
return '';
}
if (replacements) {
return text.replace(REPLACE_REGEX, function (match) {
var replacement = match.substring(1, match.length - 1);
if (replacements[replacement] === undefined) {
var replacementData = JSON.stringify(replacements);
throw new Error("Error in translation for key '".concat(id, "'. No replacement found for key '").concat(replacement, "'. The following replacements were passed: '").concat(replacementData, "'"));
} // This could be a string or a number, but JS doesn't mind which it gets
// and can handle that cast internally. So let it, to save us calling
// toString() on what's already a string in 90% of cases.
return replacements[replacement];
});
}
return text;
}
}, {
key: "translationKeyExists",
value: function translationKeyExists(path) {
return Boolean(get(this.translation, path));
}
}]);
return I18n;
}();
/**
* useIsAfterInitialMount will trigger a re-render to provide
* you with an updated value. Using this you enhance server-side
* code that can only run on the client.
* @returns MutableRefObject<T> - Returns a ref object with the
* results from invoking initial value
* @example
* function ComponentExample({children}) {
* const isMounted = useIsAfterInitialMount();
* const content = isMounted ? children : null;
*
* return <React.Fragment>{content}</React.Fragment>;
* }
*/
function useIsAfterInitialMount() {
var _useState = React.useState(false),
_useState2 = _slicedToArray(_useState, 2),
isAfterInitialMount = _useState2[0],
setIsAfterInitialMount = _useState2[1];
React.useEffect(function () {
setIsAfterInitialMount(true);
}, []);
return isAfterInitialMount;
}
function Image(_a) {
var sourceSet = _a.sourceSet,
source = _a.source,
crossOrigin = _a.crossOrigin,
rest = tslib.__rest(_a, ["sourceSet", "source", "crossOrigin"]);
var finalSourceSet = sourceSet ? sourceSet.map(function (_ref) {
var subSource = _ref.source,
descriptor = _ref.descriptor;
return "".concat(subSource, " ").concat(descriptor);
}).join(',') : null;
return finalSourceSet ?
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/alt-text
React__default.createElement("img", Object.assign({
src: source,
srcSet: finalSourceSet,
crossOrigin: crossOrigin
}, rest)) :
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/alt-text
React__default.createElement("img", Object.assign({
src: source
}, rest, {
crossOrigin: crossOrigin
}));
}
var styles = {
"Avatar": "Polaris-Avatar",
"hidden": "Polaris-Avatar--hidden",
"sizeSmall": "Polaris-Avatar--sizeSmall",
"sizeMedium": "Polaris-Avatar--sizeMedium",
"sizeLarge": "Polaris-Avatar--sizeLarge",
"styleOne": "Polaris-Avatar--styleOne",
"styleTwo": "Polaris-Avatar--styleTwo",
"styleThree": "Polaris-Avatar--styleThree",
"styleFour": "Polaris-Avatar--styleFour",
"styleFive": "Polaris-Avatar--styleFive",
"styleSix": "Polaris-Avatar--styleSix",
"hasImage": "Polaris-Avatar--hasImage",
"Image": "Polaris-Avatar__Image",
"Initials": "Polaris-Avatar__Initials",
"Svg": "Polaris-Avatar__Svg"
};
var Status;
(function (Status) {
Status["Pending"] = "PENDING";
Status["Loaded"] = "LOADED";
Status["Errored"] = "ERRORED";
})(Status || (Status = {}));
var STYLE_CLASSES = ['one', 'two', 'three', 'four', 'five'];
function Avatar(_ref) {
var name = _ref.name,
source = _ref.source,
initials = _ref.initials,
customer = _ref.customer,
_ref$size = _ref.size,
size = _ref$size === void 0 ? 'medium' : _ref$size,
accessibilityLabel = _ref.accessibilityLabel;
var i18n = useI18n();
var _useFeatures = useFeatures(),
newDesignLanguage = _useFeatures.newDesignLanguage;
var isAfterInitialMount = useIsAfterInitialMount();
function styleClass(name) {
var finalStyleClasses = newDesignLanguage ? STYLE_CLASSES : [].concat(STYLE_CLASSES, ['six']);
return name ? finalStyleClasses[name.charCodeAt(0) % finalStyleClasses.length] : finalStyleClasses[0];
}
var _useState = React.useState(Status.Pending),
_useState2 = _slicedToArray(_useState, 2),
status = _useState2[0],
setStatus = _useState2[1]; // If the source changes, set the status back to pending
React.useEffect(function () {
setStatus(Status.Pending);
}, [source]);
var handleError = React.useCallback(function () {
setStatus(Status.Errored);
}, []);
var handleLoad = React.useCallback(function () {
setStatus(Status.Loaded);
}, []);
var hasImage = source && status !== Status.Errored;
var nameString = name || initials;
var label;
if (accessibilityLabel) {
label = accessibilityLabel;
} else if (name) {
label = name;
} else if (initials) {
var splitInitials = initials.split('').join(' ');
label = i18n.translate('Polaris.Avatar.labelWithInitials', {
initials: splitInitials
});
} else {
label = i18n.translate('Polaris.Avatar.label');
}
var className = classNames(styles.Avatar, size && styles[variationName('size', size)], !customer && styles[variationName('style', styleClass(nameString))], (hasImage || initials && initials.length === 0) && status !== Status.Loaded && styles.hidden, hasImage && styles.hasImage);
var imageMarkUp = source && isAfterInitialMount && status !== Status.Errored ? /*#__PURE__*/React__default.createElement(Image, {
className: styles.Image,
source: source,
alt: "",
role: "presentation",
onLoad: handleLoad,
onError: handleError
}) : null; // Use `dominant-baseline: central` instead of `dy` when Edge supports it.
var verticalOffset = '0.35em';
var avatarBody = customer || !initials ? /*#__PURE__*/React__default.createElement("path", {
fill: "currentColor",
d: "M8.28 27.5A14.95 14.95 0 0120 21.8c4.76 0 8.97 2.24 11.72 5.7a14.02 14.02 0 01-8.25 5.91 14.82 14.82 0 01-6.94 0 14.02 14.02 0 01-8.25-5.9zM13.99 12.78a6.02 6.02 0 1112.03 0 6.02 6.02 0 01-12.03 0z"
}) : /*#__PURE__*/React__default.createElement("text", {
x: "50%",
y: "50%",
dy: verticalOffset,
fill: "currentColor",
fontSize: "20",
textAnchor: "middle"
}, initials);
var svgMarkup = !hasImage ? /*#__PURE__*/React__default.createElement("span", {
className: styles.Initials
}, /*#__PURE__*/React__default.createElement("svg", {
className: styles.Svg,
viewBox: "0 0 40 40"
}, avatarBody)) : null;
return /*#__PURE__*/React__default.createElement("span", {
"aria-label": label,
role: "img",
className: className
}, svgMarkup, imageMarkUp);
}
function isElementInViewport(element) {
var _element$getBoundingC = element.getBoundingClientRect(),
top = _element$getBoundingC.top,
left = _element$getBoundingC.left,
bottom = _element$getBoundingC.bottom,
right = _element$getBoundingC.right;
return top >= 0 && right <= window.innerWidth && bottom <= window.innerHeight && left >= 0;
}
var KEYBOARD_FOCUSABLE_SELECTORS = 'a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]:not([tabindex="-1"])';
function handleMouseUpByBlurring(_ref) {
var currentTarget = _ref.currentTarget;
currentTarget.blur();
}
function nextFocusableNode(node, filter) {
var allFocusableElements = _toConsumableArray(document.querySelectorAll(focus.FOCUSABLE_SELECTOR));
var sliceLocation = allFocusableElements.indexOf(node) + 1;
var focusableElementsAfterNode = allFocusableElements.slice(sliceLocation);
var _iterator = _createForOfIteratorHelper(focusableElementsAfterNode),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var focusableElement = _step.value;
if (isElementInViewport(focusableElement) && (!filter || filter && filter(focusableElement))) {
return focusableElement;
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return null;
} // Popover needs to be able to find its activator even if it is disabled, which FOCUSABLE_SELECTOR doesn't support.
function findFirstFocusableNode(element) {
var focusableSelector = "a,button,frame,iframe,input:not([type=hidden]),select,textarea,*[tabindex]";
if (matches(element, focusableSelector)) {
return element;
}
return element.querySelector(focusableSelector);
}
function focusNextFocusableNode(node, filter) {
var nextFocusable = nextFocusableNode(node, filter);
if (nextFocusable && nextFocusable instanceof HTMLElement) {
nextFocusable.focus();
return true;
}
return false;
} // https://github.com/Shopify/javascript-utilities/blob/1e705564643d6fe7ffea5ebfbbf3e6b759a66c9b/src/focus.ts
function findFirstKeyboardFocusableNode(element) {
var onlyDescendants = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (!onlyDescendants && matches(element, KEYBOARD_FOCUSABLE_SELECTORS)) {
return element;
}
return element.querySelector(KEYBOARD_FOCUSABLE_SELECTORS);
}
function focusFirstKeyboardFocusableNode(element) {
var onlyDescendants = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var firstFocusable = findFirstKeyboardFocusableNode(element, onlyDescendants);
if (firstFocusable) {
firstFocusable.focus();
return true;
}
return false;
}
function findLastKeyboardFocusableNode(element) {
var onlyDescendants = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (!onlyDescendants && matches(element, KEYBOARD_FOCUSABLE_SELECTORS)) {
return element;
}
var allFocusable = element.querySelectorAll(KEYBOARD_FOCUSABLE_SELECTORS);
return allFocusable[allFocusable.length - 1];
}
function focusLastKeyboardFocusableNode(element) {
var onlyDescendants = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var lastFocusable = findLastKeyboardFocusableNode(element, onlyDescendants);
if (lastFocusable) {
lastFocusable.focus();
return true;
}
return false;
}
function matches(node, selector) {
if (node.matches) {
return node.matches(selector);
}
var matches = (node.ownerDocument || document).querySelectorAll(selector);
var i = matches.length;
while (--i >= 0 && matches.item(i) !== node) {
return i > -1;
}
}
var scrollable = {
props: {
'data-polaris-scrollable': true
},
selector: '[data-polaris-scrollable]'
};
var overlay = {
props: {
'data-polaris-overlay': true
},
selector: '[data-polaris-overlay]'
};
var layer = {
props: {
'data-polaris-layer': true
},
selector: '[data-polaris-layer]'
};
var unstyled = {
props: {
'data-polaris-unstyled': true
},
selector: '[data-polaris-unstyled]'
};
var dataPolarisTopBar = {
props: {
'data-polaris-top-bar': true
},
selector: '[data-polaris-top-bar]'
};
var headerCell = {
props: {
'data-polaris-header-cell': true
},
selector: '[data-polaris-header-cell]'
};
var portal = {
props: ['data-portal-id'],
selector: '[data-portal-id]'
};
var DATA_ATTRIBUTE = {
overlay,
layer
};
var LinkContext = React__default.createContext(undefined);
function useLink() {
return React__default.useContext(LinkContext);
}
// https://github.com/facebook/react/issues/16722
// but eslint-plugin-react doesn't know that just yet
// eslint-disable-next-line react/display-name
var UnstyledLink = React__default.memo(React__default.forwardRef(function UnstyledLink(props, _ref) {
var LinkComponent = useLink();
if (LinkComponent) {
return /*#__PURE__*/React__default.createElement(LinkComponent, Object.assign({}, unstyled.props, props));
}
var external = props.external,
url = props.url,
rest = tslib.__rest(props, ["external", "url"]);
var target = external ? '_blank' : undefined;
var rel = external ? 'noopener noreferrer' : undefined;
return /*#__PURE__*/React__default.createElement("a", Object.assign({
target: target
}, rest, {
href: url,
rel: rel
}, unstyled.props));
}));
var styles$1 = {
"Icon": "Polaris-Icon",
"hasBackdrop": "Polaris-Icon--hasBackdrop",
"isColored": "Polaris-Icon--isColored",
"colorWhite": "Polaris-Icon--colorWhite",
"newDesignLanguage": "Polaris-Icon--newDesignLanguage",
"colorBlack": "Polaris-Icon--colorBlack",
"colorSkyLighter": "Polaris-Icon--colorSkyLighter",
"colorSkyLight": "Polaris-Icon--colorSkyLight",
"colorSky": "Polaris-Icon--colorSky",
"colorSkyDark": "Polaris-Icon--colorSkyDark",
"colorInkLightest": "Polaris-Icon--colorInkLightest",
"colorInkLighter": "Polaris-Icon--colorInkLighter",
"colorInkLight": "Polaris-Icon--colorInkLight",
"colorInk": "Polaris-Icon--colorInk",
"colorBlueLighter": "Polaris-Icon--colorBlueLighter",
"colorBlueLight": "Polaris-Icon--colorBlueLight",
"colorBlue": "Polaris-Icon--colorBlue",
"colorBlueDark": "Polaris-Icon--colorBlueDark",
"colorBlueDarker": "Polaris-Icon--colorBlueDarker",
"colorIndigoLighter": "Polaris-Icon--colorIndigoLighter",
"colorIndigoLight": "Polaris-Icon--colorIndigoLight",
"colorIndigo": "Polaris-Icon--colorIndigo",
"colorIndigoDark": "Polaris-Icon--colorIndigoDark",
"colorIndigoDarker": "Polaris-Icon--colorIndigoDarker",
"colorTealLighter": "Polaris-Icon--colorTealLighter",
"colorTealLight": "Polaris-Icon--colorTealLight",
"colorTeal": "Polaris-Icon--colorTeal",
"colorTealDark": "Polaris-Icon--colorTealDark",
"colorTealDarker": "Polaris-Icon--colorTealDarker",
"colorGreenLighter": "Polaris-Icon--colorGreenLighter",
"colorGreen": "Polaris-Icon--colorGreen",
"colorGreenDark": "Polaris-Icon--colorGreenDark",
"colorYellowLighter": "Polaris-Icon--colorYellowLighter",
"colorYellow": "Polaris-Icon--colorYellow",
"colorYellowDark": "Polaris-Icon--colorYellowDark",
"colorOrange": "Polaris-Icon--colorOrange",
"colorOrangeDark": "Polaris-Icon--colorOrangeDark",
"colorRedLighter": "Polaris-Icon--colorRedLighter",
"colorRed": "Polaris-Icon--colorRed",
"colorRedDark": "Polaris-Icon--colorRedDark",
"colorPurple": "Polaris-Icon--colorPurple",
"colorBase": "Polaris-Icon--colorBase",
"colorSubdued": "Polaris-Icon--colorSubdued",
"colorCritical": "Polaris-Icon--colorCritical",
"colorWarning": "Polaris-Icon--colorWarning",
"colorHighlight": "Polaris-Icon--colorHighlight",
"colorSuccess": "Polaris-Icon--colorSuccess",
"colorPrimary": "Polaris-Icon--colorPrimary",
"Svg": "Polaris-Icon__Svg",
"Img": "Polaris-Icon__Img",
"Placeholder": "Polaris-Icon__Placeholder"
};
var COLORS_WITH_BACKDROPS = ['teal', 'tealDark', 'greenDark', 'redDark', 'yellowDark', 'ink', 'inkLighter'];
function Icon(_ref) {
var source = _ref.source,
color = _ref.color,
backdrop = _ref.backdrop,
accessibilityLabel = _ref.accessibilityLabel;
var i18n = useI18n();
var _useFeatures = useFeatures(),
newDesignLanguage = _useFeatures.newDesignLanguage;
var sourceType;
if (typeof source === 'function') {
sourceType = 'function';
} else if (source === 'placeholder') {
sourceType = 'placeholder';
} else {
sourceType = 'external';
}
if (color && backdrop && !COLORS_WITH_BACKDROPS.includes(color)) {
// eslint-disable-next-line no-console
console.warn(i18n.translate('Polaris.Icon.backdropWarning', {
color,
colorsWithBackDrops: COLORS_WITH_BACKDROPS.join(', ')
}));
}
if (color && sourceType === 'external' && newDesignLanguage === true && isNewDesignLanguageColor(color)) {
// eslint-disable-next-line no-console
console.warn('Recoloring external SVGs is not supported with colors in the new design language. Set the intended color on your SVG instead.');
}
var className = classNames(styles$1.Icon, color && styles$1[variationName('color', color)], color && color !== 'white' && styles$1.isColored, backdrop && styles$1.hasBackdrop, newDesignLanguage && styles$1.newDesignLanguage);
var SourceComponent = source;
var contentMarkup = {
function: /*#__PURE__*/React__default.createElement(SourceComponent, {
className: styles$1.Svg,
focusable: "false",
"aria-hidden": "true"
}),
placeholder: /*#__PURE__*/React__default.createElement("div", {
className: styles$1.Placeholder
}),
external: /*#__PURE__*/React__default.createElement("img", {
className: styles$1.Img,
src: "data:image/svg+xml;utf8,".concat(source),
alt: "",
"aria-hidden": "true"
})
};
return /*#__PURE__*/React__default.createElement("span", {
className: className,
"aria-label": accessibilityLabel
}, contentMarkup[sourceType]);
}
var styles$2 = {
"VisuallyHidden": "Polaris-VisuallyHidden"
};
function VisuallyHidden(_ref) {
var children = _ref.children;
return /*#__PURE__*/React__default.createElement("span", {
className: styles$2.VisuallyHidden
}, children);
}
var styles$3 = {
"Spinner": "Polaris-Spinner",
"sizeSmall": "Polaris-Spinner--sizeSmall",
"sizeLarge": "Polaris-Spinner--sizeLarge",
"colorWhite": "Polaris-Spinner--colorWhite",
"loading": "Polaris-Spinner--loading",
"colorTeal": "Polaris-Spinner--colorTeal",
"colorHighlight": "Polaris-Spinner--colorHighlight",
"colorInkLightest": "Polaris-Spinner--colorInkLightest"
};
var COLORS_FOR_LARGE_SPINNER = ['teal', 'inkLightest', 'highlight'];
function Spinner(_ref) {
var _ref$size = _ref.size,
size = _ref$size === void 0 ? 'large' : _ref$size,
_ref$color = _ref.color,
color = _ref$color === void 0 ? 'teal' : _ref$color,
accessibilityLabel = _ref.accessibilityLabel,
hasFocusableParent = _ref.hasFocusableParent;
var _useFeatures = useFeatures(),
newDesignLanguage = _useFeatures.newDesignLanguage;
var i18n = useI18n();
var isAfterInitialMount = useIsAfterInitialMount();
if (size === 'large' && !COLORS_FOR_LARGE_SPINNER.includes(color)) {
if (process.env.NODE_ENV === 'development') {
// eslint-disable-next-line no-console
console.warn(i18n.translate('Polaris.Spinner.warningMessage', {
color,
size,
colors: COLORS_FOR_LARGE_SPINNER.join(', ')
}));
} // eslint-disable-next-line no-param-reassign
size = 'small';
}
var className = classNames(styles$3.Spinner, color && styles$3[variationName('color', color)], size && styles$3[variationName('size', size)], newDesignLanguage && styles$3.newDesignLanguage);
var spinnerSVGMarkup = size === 'large' ? /*#__PURE__*/React__default.createElement("svg", {
viewBox: "0 0 44 44",
xmlns: "http://www.w3.org/2000/svg"
}, /*#__PURE__*/React__default.createElement("path", {
d: "M15.542 1.487A21.507 21.507 0 00.5 22c0 11.874 9.626 21.5 21.5 21.5 9.847 0 18.364-6.675 20.809-16.072a1.5 1.5 0 00-2.904-.756C37.803 34.755 30.473 40.5 22 40.5 11.783 40.5 3.5 32.217 3.5 22c0-8.137 5.3-15.247 12.942-17.65a1.5 1.5 0 10-.9-2.863z"
})) : /*#__PURE__*/React__default.createElement("svg", {
viewBox: "0 0 20 20",
xmlns: "http://www.w3.org/2000/svg"
}, /*#__PURE__*/React__default.createElement("path", {
d: "M7.229 1.173a9.25 9.25 0 1011.655 11.412 1.25 1.25 0 10-2.4-.698 6.75 6.75 0 11-8.506-8.329 1.25 1.25 0 10-.75-2.385z"
}));
var spanAttributes = Object.assign({}, !hasFocusableParent && {
role: 'status'
});
var accessibilityLabelMarkup = (isAfterInitialMount || !hasFocusableParent) && /*#__PURE__*/React__default.createElement(VisuallyHidden, null, accessibilityLabel);
return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement("span", {
className: className
}, spinnerSVGMarkup), /*#__PURE__*/React__default.createElement("span", spanAttributes, accessibilityLabelMarkup));
}
var ThemeContext = React__default.createContext(undefined);
function useTheme() {
var theme = React.useContext(ThemeContext);
if (!theme) {
throw new MissingAppProviderError('No Theme was provided.');
}
return theme;
}
function compose() {
for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
fns[_key] = arguments[_key];
}
return fns.reduce(function (func, group) {
return function () {
return func(group.apply(void 0, arguments));
};
});
}
function rgbString(color) {
var red = color.red,
green = color.green,
blue = color.blue;
if ('alpha' in color) {
return "rgba(".concat(red, ", ").concat(green, ", ").concat(blue, ", ").concat(color.alpha, ")");
} else {
return "rgb(".concat(red, ", ").concat(green, ", ").concat(blue, ")");
}
}
var rgbaString = rgbString;
function rgbToHex(_ref) {
var red = _ref.red,
green = _ref.green,
blue = _ref.blue;
return "#".concat(componentToHex(red)).concat(componentToHex(green)).concat(componentToHex(blue));
}
function componentToHex(component) {
var hex = component.toString(16);
return hex.length === 1 ? "0".concat(hex) : hex;
}
function hsbToHex(color) {
return rgbToHex(hsbToRgb(color));
}
function rgbFromHueAndChroma(hue, chroma) {
var huePrime = hue / 60;
var hueDelta = 1 - Math.abs(huePrime % 2 - 1);
var intermediateValue = chroma * hueDelta;
var red = 0;
var green = 0;
var blue = 0;
if (huePrime >= 0 && huePrime <= 1) {
red = chroma;
green = intermediateValue;
blue = 0;
}
if (huePrime >= 1 && huePrime <= 2) {
red = intermediateValue;
green = chroma;
blue = 0;
}
if (huePrime >= 2 && huePrime <= 3) {
red = 0;
green = chroma;
blue = intermediateValue;
}
if (huePrime >= 3 && huePrime <= 4) {
red = 0;
green = intermediateValue;
blue = chroma;
}
if (huePrime >= 4 && huePrime <= 5) {
red = intermediateValue;
green = 0;
blue = chroma;
}
if (huePrime >= 5 && huePrime <= 6) {
red = chroma;
green = 0;
blue = intermediateValue;
}
return {
red,
green,
blue
};
}
function hsbToRgb(color) {
var hue = color.hue,
saturation = color.saturation,
brightness = color.brightness,
_color$alpha = color.alpha,
alpha = _color$alpha === void 0 ? 1 : _color$alpha;
var chroma = brightness * saturation;
var _rgbFromHueAndChroma = rgbFromHueAndChroma(hue, chroma),
red = _rgbFromHueAndChroma.red,
green = _rgbFromHueAndChroma.green,
blue = _rgbFromHueAndChroma.blue;
var chromaBrightnessDelta = brightness - chroma;
red += chromaBrightnessDelta;
green += chromaBrightnessDelta;
blue += chromaBrightnessDelta;
return {
red: Math.round(red * 255),
green: Math.round(green * 255),
blue: Math.round(blue * 255),
alpha
};
}
function hslToRgb(color) {
var hue = color.hue,
saturation = color.saturation,
lightness = color.lightness,
_color$alpha2 = color.alpha,
alpha = _color$alpha2 === void 0 ? 1 : _color$alpha2;
var chroma = (1 - Math.abs(2 * (lightness / 100) - 1)) * (saturation / 100);
var _rgbFromHueAndChroma2 = rgbFromHueAndChroma(hue, chroma),
red = _rgbFromHueAndChroma2.red,
green = _rgbFromHueAndChroma2.green,
blue = _rgbFromHueAndChroma2.blue;
var lightnessVal = lightness / 100 - chroma / 2;
red += lightnessVal;
green += lightnessVal;
blue += lightnessVal;
return {
red: Math.round(red * 255),
green: Math.round(green * 255),
blue: Math.round(blue * 255),
alpha
};
} // ref https://en.wikipedia.org/wiki/HSL_and_HSV
function rgbToHsbl(color) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'b';
var r = color.red,
g = color.green,
b = color.blue,
_color$alpha3 = color.alpha,
alpha = _color$alpha3 === void 0 ? 1 : _color$alpha3;
var red = r / 255;
var green = g / 255;
var blue = b / 255;
var largestComponent = Math.max(red, green, blue);
var smallestComponent = Math.min(red, green, blue);
var delta = largestComponent - smallestComponent;
var lightness = (largestComponent + smallestComponent) / 2;
var saturation = 0;
if (largestComponent === 0) {
saturation = 0;
} else if (type === 'b') {
saturation = delta / largestComponent;
} else if (type === 'l') {
var baseSaturation = lightness > 0.5 ? delta / (2 - largestComponent - smallestComponent) : delta / (largestComponent + smallestComponent);
saturation = isNaN(baseSaturation) ? 0 : baseSaturation;
}
var huePercentage = 0;
switch (largestComponent) {
case red:
huePercentage = (green - blue) / delta + (green < blue ? 6 : 0);
break;
case green:
huePercentage = (blue - red) / delta + 2;
break;
case blue:
huePercentage = (red - green) / delta + 4;
}
var hue = Math.round(huePercentage / 6 * 360);
return {
hue: math.clamp(hue, 0, 360) || 0,
saturation: parseFloat(math.clamp(saturation, 0, 1).toFixed(2)),
brightness: parseFloat(math.clamp(largestComponent, 0, 1).toFixed(2)),
lightness: parseFloat(lightness.toFixed(2)),
alpha: parseFloat(alpha.toFixed(2))
};
}
function rgbToHsb(color) {
var _rgbToHsbl = rgbToHsbl(color, 'b'),
hue = _rgbToHsbl.hue,
saturation = _rgbToHsbl.saturation,
brightness = _rgbToHsbl.brightness,
_rgbToHsbl$alpha = _rgbToHsbl.alpha,
alpha = _rgbToHsbl$alpha === void 0 ? 1 : _rgbToHsbl$alpha;
return {
hue,
saturation,
brightness,
alpha
};
}
function rgbToHsl(color) {
var _rgbToHsbl2 = rgbToHsbl(color, 'l'),
hue = _rgbToHsbl2.hue,
rawSaturation = _rgbToHsbl2.saturation,
rawLightness = _rgbToHsbl2.lightness,
_rgbToHsbl2$alpha = _rgbToHsbl2.alpha,
alpha = _rgbToHsbl2$alpha === void 0 ? 1 : _rgbToHsbl2$alpha;
var saturation = rawSaturation * 100;
var lightness = rawLightness * 100;
return {
hue,
saturation,
lightness,
alpha
};
}
function hexToRgb(color) {
if (color.length === 4) {
var repeatHex = function repeatHex(hex1, hex2) {
return color.slice(hex1, hex2).repeat(2);
};
var _red = parseInt(repeatHex(1, 2), 16);
var _green = parseInt(repeatHex(2, 3), 16);
var _blue = parseInt(repeatHex(3, 4), 16);
return {
red: _red,
green: _green,
blue: _blue
};
}
var red = parseInt(color.slice(1, 3), 16);
var green = parseInt(color.slice(3, 5), 16);
var blue = parseInt(color.slice(5, 7), 16);
return {
red,
green,
blue
};
}
var ColorType;
(function (ColorType) {
ColorType["Hex"] = "hex";
ColorType["Rgb"] = "rgb";
ColorType["Rgba"] = "rgba";
ColorType["Hsl"] = "hsl";
ColorType["Hsla"] = "hsla";
ColorType["Default"] = "default";
})(ColorType || (ColorType = {}));
function getColorType(color) {
if (color.includes('#')) {
return ColorType.Hex;
} else if (color.includes('rgb')) {
return ColorType.Rgb;
} else if (color.includes('rgba')) {
return ColorType.Rgba;
} else if (color.includes('hsl')) {
return ColorType.Hsl;
} else if (color.includes('hsla')) {
return ColorType.Hsla;
} else {
if (process.env.NODE_ENV === 'development') {
/* eslint-disable-next-line no-console */
console.warn('Accepted colors formats are: hex, rgb, rgba, hsl and hsla');
}
return ColorType.Default;
}
}
function hslToString(hslColor) {
if (typeof hslColor === 'string') {
return hslColor;
}
var _hslColor$alpha = hslColor.alpha,
alpha = _hslColor$alpha === void 0 ? 1 : _hslColor$alpha,
hue = hslColor.hue,
lightness = hslColor.lightness,
saturation = hslColor.saturation;
return "hsla(".concat(hue, ", ").concat(saturation, "%, ").concat(lightness, "%, ").concat(alpha, ")");
}
function rgbToObject(color) {
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
var colorMatch = color.match(/\(([^)]+)\)/);
if (!colorMatch) {
return {
red: 0,
green: 0,
blue: 0,
alpha: 0
};
}
var _colorMatch$1$split = colorMatch[1].split(','),
_colorMatch$1$split2 = _slicedToArray(_colorMatch$1$split, 4),
red = _colorMatch$1$split2[0],
green = _colorMatch$1$split2[1],
blue = _colorMatch$1$split2[2],
alpha = _colorMatch$1$split2[3];
var objColor = {
red: parseInt(red, 10),
green: parseInt(green, 10),
blue: parseInt(blue, 10),
alpha: parseInt(alpha, 10) || 1
};
return objColor;
}
var hexToHsla = compose(rgbToHsl, hexToRgb);
var rbgStringToHsla = compose(rgbToHsl, rgbToObject);
function hslToObject(color) {
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
var colorMatch = color.match(/\(([^)]+)\)/);
if (!colorMatch) {
return {
hue: 0,
saturation: 0,
lightness: 0,
alpha: 0
};
}
var _colorMatch$1$split3 = colorMatch[1].split(','),
_colorMatch$1$split4 = _slicedToArray(_colorMatch$1$split3, 4),
hue = _colorMatch$1$split4[0],
saturation = _colorMatch$1$split4[1],
lightness = _colorMatch$1$split4[2],
alpha = _colorMatch$1$split4[3];
var objColor = {
hue: parseInt(hue, 10),
saturation: parseInt(saturation, 10),
lightness: parseInt(lightness, 10),
alpha: parseFloat(alpha) || 1
};
return objColor;
}
function colorToHsla(color) {
var type = getColorType(color);
switch (type) {
case ColorType.Hex:
return hexToHsla(color);
case ColorType.Rgb:
case ColorType.Rgba:
return rbgStringToHsla(color);
case ColorType.Hsla:
case ColorType.Hsl:
return hslToObject(color);
case ColorType.Default:
default:
throw new Error('Accepted color formats are: hex, rgb, rgba, hsl and hsla');
}
}
// implements: https://www.w3.org/WAI/ER/WD-AERT/#color-contrast
function isLight(_ref) {
var red = _ref.red,
green = _ref.green,
blue = _ref.blue;
var contrast = (red * 299 + green * 587 + blue * 114) / 1000;
return contrast > 125;
}
function normalizeName(name) {
return name.split(/(?=[A-Z])/).join('-').toLowerCase();
}
function constructColorName(baseName, property, suffix) {
var name = normalizeName(baseName);
var propertyName = property ? "-".concat(normalizeName(property)) : '';
var constructedSuffix = suffix ? "-".concat(suffix) : '';
return "--".concat(name).concat(propertyName).concat(constructedSuffix);
}
function lightenColor(color) {
var lighten = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
if (typeof color === 'string') {
return color;
}
var lightness = color.lightness;
var nextLightness = lightness + lighten;
return Object.assign(Object.assign({}, color), {
lightness: math.clamp(nextLightness, 0, 100)
});
}
function saturateColor(color) {
var saturate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
if (typeof color === 'string') {
return color;
}
var saturation = color.saturation;
var nextSaturation = saturation + saturate;
return Object.assign(Object.assign({}, color), {
saturation: nextSaturation
});
}
function createLightColor(color, lightness, saturation) {
var lightenedColor = lightenColor(color, lightness);
var saturatedColor = saturateColor(lightenedColor, -saturation);
return saturatedColor;
}
var needsVariantList = ['topBar'];
function buildCustomProperties(themeConfig, newDesignLanguage, tokens) {
var _themeConfig$colors = themeConfig.colors,
colors = _themeConfig$colors === void 0 ? {} : _themeConfig$colors,
colorScheme = themeConfig.colorScheme,
config = themeConfig.config,
_themeConfig$frameOff = themeConfig.frameOffset,
frameOffset = _themeConfig$frameOff === void 0 ? 0 : _themeConfig$frameOff;
var mergedConfig = utils.mergeConfigs(base.config, config || {});
return newDesignLanguage ? customPropertyTransformer(Object.assign(Object.assign(Object.assign({}, distModern.colorFactory(colors, colorScheme, mergedConfig)), tokens), {
frameOffset: "".concat(frameOffset, "px")
})) : Object.assign(Object.assign({}, buildLegacyColors(themeConfig)), customPropertyTransformer({
frameOffset: "".concat(frameOffset, "px")
}));
}
function buildThemeContext(themeConfig, cssCustomProperties) {
var logo = themeConfig.logo,
_themeConfig$colors2 = themeConfig.colors,
colors = _themeConfig$colors2 === void 0 ? {} : _themeConfig$colors2,
colorSche