Preview: app-bundle.development.js
Size: 4.39 MB
/home/byroehnu/easepaybiz.easetack.com/node_modules/adminjs/bundle/app-bundle.development.js
var AdminJS = (function (styledComponents, React$1, require$$3, reactRouterDom, reactRouter, DesignSystem, require$$1, require$$0$1) {
'use strict';
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
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);
}
var React__default$1 = /*#__PURE__*/_interopDefault(React$1);
var require$$3__default = /*#__PURE__*/_interopDefault(require$$3);
var DesignSystem__namespace = /*#__PURE__*/_interopNamespace(DesignSystem);
var require$$1__default = /*#__PURE__*/_interopDefault(require$$1);
var require$$0__default = /*#__PURE__*/_interopDefault(require$$0$1);
function _typeof$3(obj) {
"@babel/helpers - typeof";
return _typeof$3 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof$3(obj);
}
function _toPrimitive$1(input, hint) {
if (_typeof$3(input) !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (_typeof$3(res) !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
function _toPropertyKey$1(arg) {
var key = _toPrimitive$1(arg, "string");
return _typeof$3(key) === "symbol" ? key : String(key);
}
function _defineProperty$2(obj, key, value) {
key = _toPropertyKey$1(key);
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function getAugmentedNamespace(n) {
if (n.__esModule) return n;
var f = n.default;
if (typeof f == "function") {
var a = function a () {
if (this instanceof a) {
return Reflect.construct(f, arguments, this.constructor);
}
return f.apply(this, arguments);
};
a.prototype = f.prototype;
} else a = {};
Object.defineProperty(a, '__esModule', {value: true});
Object.keys(n).forEach(function (k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function () {
return n[k];
}
});
});
return a;
}
/**
* This file automatically generated from `pre-publish.js`.
* Do not manually edit.
*/
var voidElements = {
"area": true,
"base": true,
"br": true,
"col": true,
"embed": true,
"hr": true,
"img": true,
"input": true,
"link": true,
"meta": true,
"param": true,
"source": true,
"track": true,
"wbr": true
};
var e,t=(e=voidElements)&&"object"==typeof e&&"default"in e?e.default:e,n=/\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;function r(e){var r={type:"tag",name:"",voidElement:!1,attrs:{},children:[]},i=e.match(/<\/?([^\s]+?)[/\s>]/);if(i&&(r.name=i[1],(t[i[1]]||"/"===e.charAt(e.length-2))&&(r.voidElement=!0),r.name.startsWith("!--"))){var s=e.indexOf("--\x3e");return {type:"comment",comment:-1!==s?e.slice(4,s):""}}for(var c=new RegExp(n),a=null;null!==(a=c.exec(e));)if(a[0].trim())if(a[1]){var o=a[1].trim(),u=[o,""];o.indexOf("=")>-1&&(u=o.split("=")),r.attrs[u[0]]=u[1],c.lastIndex--;}else a[2]&&(r.attrs[a[2]]=a[3].trim().substring(1,a[3].length-1));return r}var i$1=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g,s=/^\s*$/,c=Object.create(null);function a(e,t){switch(t.type){case"text":return e+t.content;case"tag":return e+="<"+t.name+(t.attrs?function(e){var t=[];for(var n in e)t.push(n+'="'+e[n]+'"');return t.length?" "+t.join(" "):""}(t.attrs):"")+(t.voidElement?"/>":">"),t.voidElement?e:e+t.children.reduce(a,"")+"</"+t.name+">";case"comment":return e+"\x3c!--"+t.comment+"--\x3e"}}var htmlParseStringify={parse:function(e,t){t||(t={}),t.components||(t.components=c);var n,a=[],o=[],u=-1,l=!1;if(0!==e.indexOf("<")){var m=e.indexOf("<");a.push({type:"text",content:-1===m?e:e.substring(0,m)});}return e.replace(i$1,function(i,c){if(l){if(i!=="</"+n.name+">")return;l=!1;}var m,d="/"!==i.charAt(1),f=i.startsWith("\x3c!--"),h=c+i.length,p=e.charAt(h);if(f){var v=r(i);return u<0?(a.push(v),a):((m=o[u]).children.push(v),a)}if(d&&(u++,"tag"===(n=r(i)).type&&t.components[n.name]&&(n.type="component",l=!0),n.voidElement||l||!p||"<"===p||n.children.push({type:"text",content:e.slice(h,e.indexOf("<",h))}),0===u&&a.push(n),(m=o[u-1])&&m.children.push(n),o[u]=n),(!d||n.voidElement)&&(u>-1&&(n.voidElement||n.name===i.slice(2,-1))&&(u--,n=-1===u?a:o[u]),!l&&"<"!==p&&p)){m=-1===u?a:o[u].children;var x=e.indexOf("<",h),g=e.slice(h,-1===x?void 0:x);s.test(g)&&(g=" "),(x>-1&&u+m.length>=0||" "!==g)&&m.push({type:"text",content:g});}}),a},stringify:function(e){return e.reduce(function(e,t){return e+a("",t)},"")}};
var HTML = /*@__PURE__*/getDefaultExportFromCjs(htmlParseStringify);
function warn() {
if (console && console.warn) {
var _console;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (typeof args[0] === 'string') args[0] = "react-i18next:: ".concat(args[0]);
(_console = console).warn.apply(_console, args);
}
}
var alreadyWarned = {};
function warnOnce() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
if (typeof args[0] === 'string' && alreadyWarned[args[0]]) return;
if (typeof args[0] === 'string') alreadyWarned[args[0]] = new Date();
warn.apply(void 0, args);
}
function loadNamespaces(i18n, ns, cb) {
i18n.loadNamespaces(ns, function () {
if (i18n.isInitialized) {
cb();
} else {
var initialized = function initialized() {
setTimeout(function () {
i18n.off('initialized', initialized);
}, 0);
cb();
};
i18n.on('initialized', initialized);
}
});
}
function oldI18nextHasLoadedNamespace(ns, i18n) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var lng = i18n.languages[0];
var fallbackLng = i18n.options ? i18n.options.fallbackLng : false;
var lastLng = i18n.languages[i18n.languages.length - 1];
if (lng.toLowerCase() === 'cimode') return true;
var loadNotPending = function loadNotPending(l, n) {
var loadState = i18n.services.backendConnector.state["".concat(l, "|").concat(n)];
return loadState === -1 || loadState === 2;
};
if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns)) return false;
if (i18n.hasResourceBundle(lng, ns)) return true;
if (!i18n.services.backendConnector.backend || i18n.options.resources && !i18n.options.partialBundledLanguages) return true;
if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
return false;
}
function hasLoadedNamespace(ns, i18n) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (!i18n.languages || !i18n.languages.length) {
warnOnce('i18n.languages were undefined or empty', i18n.languages);
return true;
}
var isNewerI18next = i18n.options.ignoreJSONStructure !== undefined;
if (!isNewerI18next) {
return oldI18nextHasLoadedNamespace(ns, i18n, options);
}
return i18n.hasLoadedNamespace(ns, {
precheck: function precheck(i18nInstance, loadNotPending) {
if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false;
}
});
}
var matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
var htmlEntities = {
'&': '&',
'&': '&',
'<': '<',
'<': '<',
'>': '>',
'>': '>',
''': "'",
''': "'",
'"': '"',
'"': '"',
' ': ' ',
' ': ' ',
'©': '©',
'©': '©',
'®': '®',
'®': '®',
'…': '…',
'…': '…',
'/': '/',
'/': '/'
};
var unescapeHtmlEntity = function unescapeHtmlEntity(m) {
return htmlEntities[m];
};
var unescape$1 = function unescape(text) {
return text.replace(matchHtmlEntity, unescapeHtmlEntity);
};
function ownKeys$a(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$a(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$a(Object(source), true).forEach(function (key) { _defineProperty$2(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$a(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var defaultOptions = {
bindI18n: 'languageChanged',
bindI18nStore: '',
transEmptyNodeValue: '',
transSupportBasicHtmlNodes: true,
transWrapTextNodes: '',
transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],
useSuspense: true,
unescape: unescape$1
};
function setDefaults() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
defaultOptions = _objectSpread$a(_objectSpread$a({}, defaultOptions), options);
}
function getDefaults$2() {
return defaultOptions;
}
var i18nInstance;
function setI18n(instance) {
i18nInstance = instance;
}
function getI18n() {
return i18nInstance;
}
var _excluded$1 = ["format"],
_excluded2 = ["children", "count", "parent", "i18nKey", "context", "tOptions", "values", "defaults", "components", "ns", "i18n", "t", "shouldUnescape"];
function ownKeys$9(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$9(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$9(Object(source), true).forEach(function (key) { _defineProperty$2(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$9(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function hasChildren(node, checkLength) {
if (!node) return false;
var base = node.props ? node.props.children : node.children;
if (checkLength) return base.length > 0;
return !!base;
}
function getChildren(node) {
if (!node) return [];
return node.props ? node.props.children : node.children;
}
function hasValidReactChildren(children) {
if (Object.prototype.toString.call(children) !== '[object Array]') return false;
return children.every(function (child) {
return React$1.isValidElement(child);
});
}
function getAsArray(data) {
return Array.isArray(data) ? data : [data];
}
function mergeProps(source, target) {
var newTarget = _objectSpread$9({}, target);
newTarget.props = Object.assign(source.props, target.props);
return newTarget;
}
function nodesToString(children, i18nOptions) {
if (!children) return '';
var stringNode = '';
var childrenArray = getAsArray(children);
var keepArray = i18nOptions.transSupportBasicHtmlNodes && i18nOptions.transKeepBasicHtmlNodesFor ? i18nOptions.transKeepBasicHtmlNodesFor : [];
childrenArray.forEach(function (child, childIndex) {
if (typeof child === 'string') {
stringNode += "".concat(child);
} else if (React$1.isValidElement(child)) {
var childPropsCount = Object.keys(child.props).length;
var shouldKeepChild = keepArray.indexOf(child.type) > -1;
var childChildren = child.props.children;
if (!childChildren && shouldKeepChild && childPropsCount === 0) {
stringNode += "<".concat(child.type, "/>");
} else if (!childChildren && (!shouldKeepChild || childPropsCount !== 0)) {
stringNode += "<".concat(childIndex, "></").concat(childIndex, ">");
} else if (child.props.i18nIsDynamicList) {
stringNode += "<".concat(childIndex, "></").concat(childIndex, ">");
} else if (shouldKeepChild && childPropsCount === 1 && typeof childChildren === 'string') {
stringNode += "<".concat(child.type, ">").concat(childChildren, "</").concat(child.type, ">");
} else {
var content = nodesToString(childChildren, i18nOptions);
stringNode += "<".concat(childIndex, ">").concat(content, "</").concat(childIndex, ">");
}
} else if (child === null) {
warn("Trans: the passed in value is invalid - seems you passed in a null child.");
} else if (_typeof$3(child) === 'object') {
var format = child.format,
clone = _objectWithoutProperties(child, _excluded$1);
var keys = Object.keys(clone);
if (keys.length === 1) {
var value = format ? "".concat(keys[0], ", ").concat(format) : keys[0];
stringNode += "{{".concat(value, "}}");
} else {
warn("react-i18next: the passed in object contained more than one variable - the object should look like {{ value, format }} where format is optional.", child);
}
} else {
warn("Trans: the passed in value is invalid - seems you passed in a variable like {number} - please pass in variables for interpolation as full objects like {{number}}.", child);
}
});
return stringNode;
}
function renderNodes(children, targetString, i18n, i18nOptions, combinedTOpts, shouldUnescape) {
if (targetString === '') return [];
var keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];
var emptyChildrenButNeedsHandling = targetString && new RegExp(keepArray.join('|')).test(targetString);
if (!children && !emptyChildrenButNeedsHandling) return [targetString];
var data = {};
function getData(childs) {
var childrenArray = getAsArray(childs);
childrenArray.forEach(function (child) {
if (typeof child === 'string') return;
if (hasChildren(child)) getData(getChildren(child));else if (_typeof$3(child) === 'object' && !React$1.isValidElement(child)) Object.assign(data, child);
});
}
getData(children);
var ast = HTML.parse("<0>".concat(targetString, "</0>"));
var opts = _objectSpread$9(_objectSpread$9({}, data), combinedTOpts);
function renderInner(child, node, rootReactNode) {
var childs = getChildren(child);
var mappedChildren = mapAST(childs, node.children, rootReactNode);
return hasValidReactChildren(childs) && mappedChildren.length === 0 ? childs : mappedChildren;
}
function pushTranslatedJSX(child, inner, mem, i, isVoid) {
if (child.dummy) child.children = inner;
mem.push(React$1.cloneElement(child, _objectSpread$9(_objectSpread$9({}, child.props), {}, {
key: i
}), isVoid ? undefined : inner));
}
function mapAST(reactNode, astNode, rootReactNode) {
var reactNodes = getAsArray(reactNode);
var astNodes = getAsArray(astNode);
return astNodes.reduce(function (mem, node, i) {
var translationContent = node.children && node.children[0] && node.children[0].content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language);
if (node.type === 'tag') {
var tmp = reactNodes[parseInt(node.name, 10)];
if (!tmp && rootReactNode.length === 1 && rootReactNode[0][node.name]) tmp = rootReactNode[0][node.name];
if (!tmp) tmp = {};
var child = Object.keys(node.attrs).length !== 0 ? mergeProps({
props: node.attrs
}, tmp) : tmp;
var isElement = React$1.isValidElement(child);
var isValidTranslationWithChildren = isElement && hasChildren(node, true) && !node.voidElement;
var isEmptyTransWithHTML = emptyChildrenButNeedsHandling && _typeof$3(child) === 'object' && child.dummy && !isElement;
var isKnownComponent = _typeof$3(children) === 'object' && children !== null && Object.hasOwnProperty.call(children, node.name);
if (typeof child === 'string') {
var value = i18n.services.interpolator.interpolate(child, opts, i18n.language);
mem.push(value);
} else if (hasChildren(child) || isValidTranslationWithChildren) {
var inner = renderInner(child, node, rootReactNode);
pushTranslatedJSX(child, inner, mem, i);
} else if (isEmptyTransWithHTML) {
var _inner = mapAST(reactNodes, node.children, rootReactNode);
mem.push(React$1.cloneElement(child, _objectSpread$9(_objectSpread$9({}, child.props), {}, {
key: i
}), _inner));
} else if (Number.isNaN(parseFloat(node.name))) {
if (isKnownComponent) {
var _inner2 = renderInner(child, node, rootReactNode);
pushTranslatedJSX(child, _inner2, mem, i, node.voidElement);
} else if (i18nOptions.transSupportBasicHtmlNodes && keepArray.indexOf(node.name) > -1) {
if (node.voidElement) {
mem.push(React$1.createElement(node.name, {
key: "".concat(node.name, "-").concat(i)
}));
} else {
var _inner3 = mapAST(reactNodes, node.children, rootReactNode);
mem.push(React$1.createElement(node.name, {
key: "".concat(node.name, "-").concat(i)
}, _inner3));
}
} else if (node.voidElement) {
mem.push("<".concat(node.name, " />"));
} else {
var _inner4 = mapAST(reactNodes, node.children, rootReactNode);
mem.push("<".concat(node.name, ">").concat(_inner4, "</").concat(node.name, ">"));
}
} else if (_typeof$3(child) === 'object' && !isElement) {
var content = node.children[0] ? translationContent : null;
if (content) mem.push(content);
} else if (node.children.length === 1 && translationContent) {
mem.push(React$1.cloneElement(child, _objectSpread$9(_objectSpread$9({}, child.props), {}, {
key: i
}), translationContent));
} else {
mem.push(React$1.cloneElement(child, _objectSpread$9(_objectSpread$9({}, child.props), {}, {
key: i
})));
}
} else if (node.type === 'text') {
var wrapTextNodes = i18nOptions.transWrapTextNodes;
var _content = shouldUnescape ? i18nOptions.unescape(i18n.services.interpolator.interpolate(node.content, opts, i18n.language)) : i18n.services.interpolator.interpolate(node.content, opts, i18n.language);
if (wrapTextNodes) {
mem.push(React$1.createElement(wrapTextNodes, {
key: "".concat(node.name, "-").concat(i)
}, _content));
} else {
mem.push(_content);
}
}
return mem;
}, []);
}
var result = mapAST([{
dummy: true,
children: children || []
}], ast, getAsArray(children || []));
return getChildren(result[0]);
}
function Trans$1(_ref) {
var children = _ref.children,
count = _ref.count,
parent = _ref.parent,
i18nKey = _ref.i18nKey,
context = _ref.context,
_ref$tOptions = _ref.tOptions,
tOptions = _ref$tOptions === void 0 ? {} : _ref$tOptions,
values = _ref.values,
defaults = _ref.defaults,
components = _ref.components,
ns = _ref.ns,
i18nFromProps = _ref.i18n,
tFromProps = _ref.t,
shouldUnescape = _ref.shouldUnescape,
additionalProps = _objectWithoutProperties(_ref, _excluded2);
var i18n = i18nFromProps || getI18n();
if (!i18n) {
warnOnce('You will need to pass in an i18next instance by using i18nextReactModule');
return children;
}
var t = tFromProps || i18n.t.bind(i18n) || function (k) {
return k;
};
if (context) tOptions.context = context;
var reactI18nextOptions = _objectSpread$9(_objectSpread$9({}, getDefaults$2()), i18n.options && i18n.options.react);
var namespaces = ns || t.ns || i18n.options && i18n.options.defaultNS;
namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation'];
var defaultValue = defaults || nodesToString(children, reactI18nextOptions) || reactI18nextOptions.transEmptyNodeValue || i18nKey;
var hashTransKey = reactI18nextOptions.hashTransKey;
var key = i18nKey || (hashTransKey ? hashTransKey(defaultValue) : defaultValue);
var interpolationOverride = values ? tOptions.interpolation : {
interpolation: _objectSpread$9(_objectSpread$9({}, tOptions.interpolation), {}, {
prefix: '#$?',
suffix: '?$#'
})
};
var combinedTOpts = _objectSpread$9(_objectSpread$9(_objectSpread$9(_objectSpread$9({}, tOptions), {}, {
count: count
}, values), interpolationOverride), {}, {
defaultValue: defaultValue,
ns: namespaces
});
var translation = key ? t(key, combinedTOpts) : defaultValue;
var content = renderNodes(components || children, translation, i18n, reactI18nextOptions, combinedTOpts, shouldUnescape);
var useAsParent = parent !== undefined ? parent : reactI18nextOptions.defaultTransParent;
return useAsParent ? React$1.createElement(useAsParent, additionalProps, content) : content;
}
function _classCallCheck$1(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties$1(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, _toPropertyKey$1(descriptor.key), descriptor);
}
}
function _createClass$1(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
if (staticProps) _defineProperties$1(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
var initReactI18next = {
type: '3rdParty',
init: function init(instance) {
setDefaults(instance.options.react);
setI18n(instance);
}
};
var I18nContext = React$1.createContext();
var ReportNamespaces = function () {
function ReportNamespaces() {
_classCallCheck$1(this, ReportNamespaces);
this.usedNamespaces = {};
}
_createClass$1(ReportNamespaces, [{
key: "addUsedNamespaces",
value: function addUsedNamespaces(namespaces) {
var _this = this;
namespaces.forEach(function (ns) {
if (!_this.usedNamespaces[ns]) _this.usedNamespaces[ns] = true;
});
}
}, {
key: "getUsedNamespaces",
value: function getUsedNamespaces() {
return Object.keys(this.usedNamespaces);
}
}]);
return ReportNamespaces;
}();
var _excluded = ["children", "count", "parent", "i18nKey", "context", "tOptions", "values", "defaults", "components", "ns", "i18n", "t", "shouldUnescape"];
function ownKeys$8(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$8(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$8(Object(source), true).forEach(function (key) { _defineProperty$2(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$8(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function Trans(_ref) {
var children = _ref.children,
count = _ref.count,
parent = _ref.parent,
i18nKey = _ref.i18nKey,
context = _ref.context,
_ref$tOptions = _ref.tOptions,
tOptions = _ref$tOptions === void 0 ? {} : _ref$tOptions,
values = _ref.values,
defaults = _ref.defaults,
components = _ref.components,
ns = _ref.ns,
i18nFromProps = _ref.i18n,
tFromProps = _ref.t,
shouldUnescape = _ref.shouldUnescape,
additionalProps = _objectWithoutProperties(_ref, _excluded);
var _ref2 = React$1.useContext(I18nContext) || {},
i18nFromContext = _ref2.i18n,
defaultNSFromContext = _ref2.defaultNS;
var i18n = i18nFromProps || i18nFromContext || getI18n();
var t = tFromProps || i18n && i18n.t.bind(i18n);
return Trans$1(_objectSpread$8({
children: children,
count: count,
parent: parent,
i18nKey: i18nKey,
context: context,
tOptions: tOptions,
values: values,
defaults: defaults,
components: components,
ns: ns || t && t.ns || defaultNSFromContext || i18n && i18n.options && i18n.options.defaultNS,
i18n: i18n,
t: tFromProps,
shouldUnescape: shouldUnescape
}, additionalProps));
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
if (null != _i) {
var _s,
_e,
_x,
_r,
_arr = [],
_n = !0,
_d = !1;
try {
if (_x = (_i = _i.call(arr)).next, 0 === i) {
if (Object(_i) !== _i) return;
_n = !1;
} else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
} catch (err) {
_d = !0, _e = err;
} finally {
try {
if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return;
} finally {
if (_d) throw _e;
}
}
return _arr;
}
}
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 _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(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
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 _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function ownKeys$7(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$7(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$7(Object(source), true).forEach(function (key) { _defineProperty$2(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$7(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var usePrevious$1 = function usePrevious(value, ignore) {
var ref = React$1.useRef();
React$1.useEffect(function () {
ref.current = ignore ? ref.current : value;
}, [value, ignore]);
return ref.current;
};
function useTranslation$1(ns) {
var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var i18nFromProps = props.i18n;
var _ref = React$1.useContext(I18nContext) || {},
i18nFromContext = _ref.i18n,
defaultNSFromContext = _ref.defaultNS;
var i18n = i18nFromProps || i18nFromContext || getI18n();
if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();
if (!i18n) {
warnOnce('You will need to pass in an i18next instance by using initReactI18next');
var notReadyT = function notReadyT(k, optsOrDefaultValue) {
if (typeof optsOrDefaultValue === 'string') return optsOrDefaultValue;
if (optsOrDefaultValue && _typeof$3(optsOrDefaultValue) === 'object' && typeof optsOrDefaultValue.defaultValue === 'string') return optsOrDefaultValue.defaultValue;
return Array.isArray(k) ? k[k.length - 1] : k;
};
var retNotReady = [notReadyT, {}, false];
retNotReady.t = notReadyT;
retNotReady.i18n = {};
retNotReady.ready = false;
return retNotReady;
}
if (i18n.options.react && i18n.options.react.wait !== undefined) warnOnce('It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.');
var i18nOptions = _objectSpread$7(_objectSpread$7(_objectSpread$7({}, getDefaults$2()), i18n.options.react), props);
var useSuspense = i18nOptions.useSuspense,
keyPrefix = i18nOptions.keyPrefix;
var namespaces = ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;
namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation'];
if (i18n.reportNamespaces.addUsedNamespaces) i18n.reportNamespaces.addUsedNamespaces(namespaces);
var ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(function (n) {
return hasLoadedNamespace(n, i18n, i18nOptions);
});
function getT() {
return i18n.getFixedT(null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
}
var _useState = React$1.useState(getT),
_useState2 = _slicedToArray(_useState, 2),
t = _useState2[0],
setT = _useState2[1];
var joinedNS = namespaces.join();
var previousJoinedNS = usePrevious$1(joinedNS);
var isMounted = React$1.useRef(true);
React$1.useEffect(function () {
var bindI18n = i18nOptions.bindI18n,
bindI18nStore = i18nOptions.bindI18nStore;
isMounted.current = true;
if (!ready && !useSuspense) {
loadNamespaces(i18n, namespaces, function () {
if (isMounted.current) setT(getT);
});
}
if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) {
setT(getT);
}
function boundReset() {
if (isMounted.current) setT(getT);
}
if (bindI18n && i18n) i18n.on(bindI18n, boundReset);
if (bindI18nStore && i18n) i18n.store.on(bindI18nStore, boundReset);
return function () {
isMounted.current = false;
if (bindI18n && i18n) bindI18n.split(' ').forEach(function (e) {
return i18n.off(e, boundReset);
});
if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(function (e) {
return i18n.store.off(e, boundReset);
});
};
}, [i18n, joinedNS]);
var isInitial = React$1.useRef(true);
React$1.useEffect(function () {
if (isMounted.current && !isInitial.current) {
setT(getT);
}
isInitial.current = false;
}, [i18n, keyPrefix]);
var ret = [t, i18n, ready];
ret.t = t;
ret.i18n = i18n;
ret.ready = ready;
if (ready) return ret;
if (!ready && !useSuspense) return ret;
throw new Promise(function (resolve) {
loadNamespaces(i18n, namespaces, function () {
resolve();
});
});
}
function I18nextProvider(_ref) {
var i18n = _ref.i18n,
defaultNS = _ref.defaultNS,
children = _ref.children;
var value = React$1.useMemo(function () {
return {
i18n: i18n,
defaultNS: defaultNS
};
}, [i18n, defaultNS]);
return React$1.createElement(I18nContext.Provider, {
value: value
}, children);
}
let globalAny$2 = {};
try {
globalAny$2 = window;
} catch (error) {
if (!(error instanceof ReferenceError)) {
throw error;
}
} finally {
if (!globalAny$2) {
globalAny$2 = {};
}
}
/**
* Base Params for a any function
* @alias ActionParams
* @memberof ViewHelpers
*/
/**
* Params for a record action
* @alias RecordActionParams
* @extends ActionParams
* @memberof ViewHelpers
*/
/**
* Params for a bulk action
* @alias BulkActionParams
* @extends ActionParams
* @memberof ViewHelpers
*/
/**
* Params for a resource action
* @alias ResourceActionParams
* @extends ActionParams
* @memberof ViewHelpers
*/
const runDate = new Date();
/**
* Collection of helper methods available in the views
*/
class ViewHelpers {
constructor({
options
} = {}) {
let opts = ViewHelpers.getPaths(options);
opts = opts || {
rootPath: '/admin'
};
// when ViewHelpers are used on the frontend, paths are taken from global Redux State
this.options = opts;
}
static getPaths(options) {
return options || globalAny$2.REDUX_STATE?.paths;
}
/**
* To each related path adds rootPath passed by the user, as well as a query string
* @private
* @param {Array<string>} [paths] list of parts of the url
* @return {string} path
* @return {query} [search=''] query string which can be fetch
* from `location.search`
*/
urlBuilder(paths = [], search = '') {
const separator = '/';
const replace = new RegExp(`${separator}{1,}`, 'g');
let {
rootPath
} = this.options;
if (!rootPath.startsWith(separator)) {
rootPath = `${separator}${rootPath}`;
}
const parts = [rootPath, ...paths];
return `${parts.join(separator).replace(replace, separator)}${search}`;
}
/**
* Returns login URL
* @return {string}
*/
loginUrl() {
return this.options.loginPath;
}
/**
* Returns logout URL
* @return {string}
*/
logoutUrl() {
return this.options.logoutPath;
}
/**
* Returns URL for the dashboard
* @return {string}
*/
dashboardUrl() {
return this.options.rootPath;
}
/**
* Returns URL for given page name
* @param {string} pageName page name which is a unique key specified in
* {@link AdminJSOptions}
* @return {string}
*/
pageUrl(pageName) {
return this.urlBuilder(['pages', pageName]);
}
/**
* Returns url for a `edit` action in given Resource. Uses {@link recordActionUrl}
*
* @param {string} resourceId id to the resource
* @param {string} recordId id to the record
* @param {string} [search] optional query string
*/
editUrl(resourceId, recordId, search) {
return this.recordActionUrl({
resourceId,
recordId,
actionName: 'edit',
search
});
}
/**
* Returns url for a `show` action in given Resource. Uses {@link recordActionUrl}
*
* @param {string} resourceId id to the resource
* @param {string} recordId id to the record
* @param {string} [search] optional query string
*/
showUrl(resourceId, recordId, search) {
return this.recordActionUrl({
resourceId,
recordId,
actionName: 'show',
search
});
}
/**
* Returns url for a `delete` action in given Resource. Uses {@link recordActionUrl}
*
* @param {string} resourceId id to the resource
* @param {string} recordId id to the record
* @param {string} [search] optional query string
*/
deleteUrl(resourceId, recordId, search) {
return this.recordActionUrl({
resourceId,
recordId,
actionName: 'delete',
search
});
}
/**
* Returns url for a `new` action in given Resource. Uses {@link resourceActionUrl}
*
* @param {string} resourceId id to the resource
* @param {string} [search] optional query string
*/
newUrl(resourceId, search) {
return this.resourceActionUrl({
resourceId,
actionName: 'new',
search
});
}
/**
* Returns url for a `list` action in given Resource. Uses {@link resourceActionUrl}
*
* @param {string} resourceId id to the resource
* @param {string} [search] optional query string
*/
listUrl(resourceId, search) {
return this.resourceActionUrl({
resourceId,
actionName: 'list',
search
});
}
/**
* Returns url for a `bulkDelete` action in given Resource. Uses {@link bulkActionUrl}
*
* @param {string} resourceId id to the resource
* @param {Array<string>} recordIds separated by comma records
* @param {string} [search] optional query string
*/
bulkDeleteUrl(resourceId, recordIds, search) {
return this.bulkActionUrl({
resourceId,
recordIds,
actionName: 'bulkDelete',
search
});
}
/**
* Returns resourceAction url
*
* @param {ResourceActionParams} options
* @param {string} options.resourceId
* @param {string} options.actionName
* @param {string} [options.search] optional query string
*
* @return {string}
*/
resourceActionUrl({
resourceId,
actionName,
search
}) {
return this.urlBuilder(['resources', resourceId, 'actions', actionName], search);
}
resourceUrl({
resourceId,
search
}) {
return this.urlBuilder(['resources', resourceId], search);
}
/**
* Returns recordAction url
*
* @param {RecordActionParams} options
* @param {string} options.resourceId
* @param {string} options.recordId
* @param {string} options.actionName
*
* @return {string}
*/
recordActionUrl({
resourceId,
recordId,
actionName,
search
}) {
return this.urlBuilder(['resources', resourceId, 'records', recordId, actionName], search);
}
/**
* Returns bulkAction url
*
* @param {BulkActionParams} options
* @param {string} options.resourceId
* @param {Array<string>} [options.recordIds]
* @param {string} options.actionName
*
* @return {string}
*/
bulkActionUrl({
resourceId,
recordIds,
actionName,
search
}) {
const url = this.urlBuilder(['resources', resourceId, 'bulk', actionName]);
if (recordIds && recordIds.length) {
const query = new URLSearchParams(search);
query.set('recordIds', recordIds.join(','));
return `${url}?${query.toString()}`;
}
return `${url}${search || ''}`;
}
/**
* Returns absolute path to a given asset.
* @private
*
* @param {string} asset
* @param {Assets | undefined} assetsConfig
* @return {string}
*/
assetPath(asset, assetsConfig) {
if (this.options.assetsCDN) {
const pathname = assetsConfig?.coreScripts?.[asset] ?? asset;
const url = new URL(pathname, this.options.assetsCDN).href;
// adding timestamp to the href invalidates the CDN cache
return `${url}?date=${runDate.getTime()}`;
}
return this.urlBuilder(['frontend', 'assets', asset]);
}
}
var flat$1 = flatten$2;
flatten$2.flatten = flatten$2;
flatten$2.unflatten = unflatten;
function isBuffer$6 (obj) {
return obj &&
obj.constructor &&
(typeof obj.constructor.isBuffer === 'function') &&
obj.constructor.isBuffer(obj)
}
function keyIdentity (key) {
return key
}
function flatten$2 (target, opts) {
opts = opts || {};
const delimiter = opts.delimiter || '.';
const maxDepth = opts.maxDepth;
const transformKey = opts.transformKey || keyIdentity;
const output = {};
function step (object, prev, currentDepth) {
currentDepth = currentDepth || 1;
Object.keys(object).forEach(function (key) {
const value = object[key];
const isarray = opts.safe && Array.isArray(value);
const type = Object.prototype.toString.call(value);
const isbuffer = isBuffer$6(value);
const isobject = (
type === '[object Object]' ||
type === '[object Array]'
);
const newKey = prev
? prev + delimiter + transformKey(key)
: transformKey(key);
if (!isarray && !isbuffer && isobject && Object.keys(value).length &&
(!opts.maxDepth || currentDepth < maxDepth)) {
return step(value, newKey, currentDepth + 1)
}
output[newKey] = value;
});
}
step(target);
return output
}
function unflatten (target, opts) {
opts = opts || {};
const delimiter = opts.delimiter || '.';
const overwrite = opts.overwrite || false;
const transformKey = opts.transformKey || keyIdentity;
const result = {};
const isbuffer = isBuffer$6(target);
if (isbuffer || Object.prototype.toString.call(target) !== '[object Object]') {
return target
}
// safely ensure that the key is
// an integer.
function getkey (key) {
const parsedKey = Number(key);
return (
isNaN(parsedKey) ||
key.indexOf('.') !== -1 ||
opts.object
) ? key
: parsedKey
}
function addKeys (keyPrefix, recipient, target) {
return Object.keys(target).reduce(function (result, key) {
result[keyPrefix + delimiter + key] = target[key];
return result
}, recipient)
}
function isEmpty (val) {
const type = Object.prototype.toString.call(val);
const isArray = type === '[object Array]';
const isObject = type === '[object Object]';
if (!val) {
return true
} else if (isArray) {
return !val.length
} else if (isObject) {
return !Object.keys(val).length
}
}
target = Object.keys(target).reduce(function (result, key) {
const type = Object.prototype.toString.call(target[key]);
const isObject = (type === '[object Object]' || type === '[object Array]');
if (!isObject || isEmpty(target[key])) {
result[key] = target[key];
return result
} else {
return addKeys(
key,
result,
flatten$2(target[key], opts)
)
}
}, {});
Object.keys(target).forEach(function (key) {
const split = key.split(delimiter).map(transformKey);
let key1 = getkey(split.shift());
let key2 = getkey(split[0]);
let recipient = result;
while (key2 !== undefined) {
if (key1 === '__proto__') {
return
}
const type = Object.prototype.toString.call(recipient[key1]);
const isobject = (
type === '[object Object]' ||
type === '[object Array]'
);
// do not write over falsey, non-undefined values if overwrite is false
if (!overwrite && !isobject && typeof recipient[key1] !== 'undefined') {
return
}
if ((overwrite && !isobject) || (!overwrite && recipient[key1] == null)) {
recipient[key1] = (
typeof key2 === 'number' &&
!opts.object ? [] : {}
);
}
recipient = recipient[key1];
if (split.length > 0) {
key1 = getkey(split.shift());
key2 = getkey(split[0]);
}
}
// unflatten again for 'messy objects'
recipient[key1] = unflatten(target[key], opts);
});
return result
}
var flatModule = /*@__PURE__*/getDefaultExportFromCjs(flat$1);
const DELIMITER = '.';
// this is the regex used to find all existing properties starting with a key
const propertyKeyRegex = (propertyPath, options) => {
const delimiter = new RegExp(`\\${DELIMITER}`, 'g');
const escapedDelimiter = `\\${DELIMITER}`;
// but for `nested.1.property.0` it will produce `nested(\.|\.\d+\.)1(\.|\.\d+\.)property.0`
// and this is intentional because user can give an one index in property path for with deeply
// nested arrays
const escapedDelimiterOrIndex = `(${escapedDelimiter}|${escapedDelimiter}\\d+${escapedDelimiter})`;
const path = options?.includeAllSiblings ? propertyPath.replace(delimiter, escapedDelimiterOrIndex) : propertyPath.replace(delimiter, escapedDelimiter);
return new RegExp(`^${path}($|${escapedDelimiter})`, '');
};
/**
* @load ./select-params.doc.md
* @memberof module:flat
* @param {FlattenParams} params
* @param {string | Array<string>} properties
* @param {GetOptions} [options]
* @returns {FlattenParams}
*/
const selectParams = (params, properties, options) => {
const propertyArray = Array.isArray(properties) ? properties : [properties];
const selected = propertyArray.filter(propertyPath => !!propertyPath).reduce((globalMemo, propertyPath) => {
const regex = propertyKeyRegex(propertyPath, options);
const filtered = Object.keys(params)
// filter all keys which starts with property path
.filter(key => key.match(regex)).reduce((memo, key) => {
memo[key] = params[key];
return memo;
}, {});
return {
...globalMemo,
...filtered
};
}, {});
return selected;
};
/**
* @load ./filter-out-params.doc.md
* @memberof module:flat
* @param {FlattenParams} params
* @param {string | Array<string>} properties
* @returns {FlattenParams}
*/
const filterOutParams = (params, properties) => {
const propertyArray = Array.isArray(properties) ? properties : [properties];
return propertyArray.filter(propertyPath => !!propertyPath).reduce((globalFiltered, propertyPath) => {
const regex = propertyKeyRegex(propertyPath);
return Object.keys(globalFiltered).filter(key => !key.match(regex)).reduce((memo, key) => {
memo[key] = params[key];
return memo;
}, {});
}, params);
};
/**
* @memberof module:flat
* @alias PathToPartsOptions
*/
/**
* @load ./path-to-parts.doc.md
* @param {string} propertyPath
* @param {PathToPartsOptions} options
* @returns {PathParts}
*
* @memberof module:flat
* @alias pathToParts
*/
const pathToParts = (propertyPath, options = {}) => {
let allParts = propertyPath.split('.');
if (options.skipArrayIndexes) {
// eslint-disable-next-line no-restricted-globals
allParts = allParts.filter(part => isNaN(+part));
}
return allParts.reduce((memo, part) => {
if (memo.length) {
return [...memo, [memo[memo.length - 1], part].join('.')];
}
return [part];
}, []);
};
const isObject$d = value => {
// Node environment
if (typeof File === 'undefined') {
return typeof value === 'object' && value !== null;
}
// Window environment
return typeof value === 'object' && !(value instanceof File) && value !== null;
};
/**
* @load ./set.doc.md
* @memberof module:flat
* @param {FlattenParams} params
* @param {string} propertyPath
* @param {any} [value] if not give function will only try to remove old keys
* @returns {FlattenParams}
*/
const set = (params = {}, propertyPath, value) => {
const regex = propertyKeyRegex(propertyPath);
// remove all existing keys
const paramsCopy = Object.keys(params).filter(key => !key.match(regex)).reduce((memo, key) => {
memo[key] = params[key];
return memo;
}, {});
if (typeof value !== 'undefined') {
if (isObject$d(value) && !(value instanceof Date)) {
const flattened = flatModule.flatten(value);
if (Object.keys(flattened).length) {
Object.keys(flattened).forEach(key => {
paramsCopy[`${propertyPath}${DELIMITER}${key}`] = flattened[key];
});
} else if (Array.isArray(value)) {
paramsCopy[propertyPath] = [];
} else {
paramsCopy[propertyPath] = {};
}
} else {
paramsCopy[propertyPath] = value;
}
// when user gave { "nested.value": "something" } and had "nested" set to `null`, then
// nested should be removed
const parts = pathToParts(propertyPath).slice(0, -1);
if (parts.length) {
return Object.keys(paramsCopy).filter(key => !parts.includes(key)).reduce((memo, key) => {
memo[key] = paramsCopy[key];
return memo;
}, {});
}
}
return paramsCopy;
};
const TEMP_HOLDING_KEY = 'TEMP_HOLDING_KEY';
/**
* @load ./get.doc.md
* @memberof module:flat
* @param {FlattenParams} params flatten params from which property has to be taken
* @param {string} [propertyPath] name of the property
* @param {GetOptions} options options
* @returns {any} when property key exists directly it returns what is inside,
* otherwise it tries to find any nested objects and returns
* them
*/
const get$3 = (params = {}, propertyPath, options) => {
if (!propertyPath) {
return flatModule.unflatten(params);
}
// when object has this key - simply return it
// we cannot rely on typeof params[propertyPath !== 'undefined' because params can actually be
// undefined and in such case if would pass and function would return [undefined]
if (Object.keys(params).find(key => key === propertyPath)) {
return params[propertyPath];
}
const regex = propertyKeyRegex(propertyPath, options);
const selectedParams = selectParams(params, propertyPath, options);
const nestedProperties = Object.keys(selectedParams).reduce((memo, key, index) => {
let newKey = key.replace(regex, `${TEMP_HOLDING_KEY}${DELIMITER}`);
// when user wants to take allSiblings we have to fix the indexes so nested items from
// different siblings don't overlap
//
// Example for key `nested.1.el`:
// 'nested.0.el.0.value': 'val0.0',
// 'nested.0.el.1.value': 'val0.1',
// 'nested.1.el.0.value': 'val1',
// 'nested.1.el.1.value': 'val2',
//
// has to be changed to:
// 'TEMP_HOLDING_KEY.0.value': 'val0.0',
// 'TEMP_HOLDING_KEY.1.value': 'val0.1',
// 'TEMP_HOLDING_KEY.2.value': 'val1',
// 'TEMP_HOLDING_KEY.3.value': 'val2',
if (options?.includeAllSiblings) {
newKey = newKey.replace(new RegExp(`${TEMP_HOLDING_KEY}\\${DELIMITER}(\\d*)`), `${TEMP_HOLDING_KEY}${DELIMITER}${index}`);
}
memo[newKey] = selectedParams[key];
return memo;
}, {});
if (Object.keys(nestedProperties).length) {
return flatModule.unflatten(nestedProperties)[TEMP_HOLDING_KEY];
}
return undefined;
};
/**
* Merges params together and returns flatten result
*
* @param {any} params
* @param {Array<any>} ...mergeParams
* @returns {FlattenParams}
* @memberof module:flat
*/
const merge$4 = (params = {}, ...mergeParams) => {
const flattenParams = flatModule.flatten(params);
// reverse because we merge from right
return mergeParams.reverse().reduce((globalMemo, mergeParam) => Object.keys(mergeParam).reduce((memo, key) => set(memo, key, mergeParam[key]), globalMemo), flattenParams);
};
/**
* @load ./remove-path.doc.md
* @memberof module:flat
* @param {FlattenParams} params
* @param {...string} properties
* @returns {FlattenParams}
*/
const removePath = (params, path) => {
// by default simply filter out elements from the object
let filtered = filterOutParams(params, path);
// reverse means that we iterate from the closes parent
const parentPaths = pathToParts(path).reverse();
// but if one of the parent is an array
parentPaths.find((parentPath, parentIndex) => {
const parent = get$3(params, parentPath);
if (Array.isArray(parent)) {
// previous element is stringified index like 'property.1'
const previousPaths = parentPaths[parentIndex - 1].split(DELIMITER);
// so this is the index: 1
const previousPathIndex = previousPaths[previousPaths.length - 1];
parent.splice(+previousPathIndex, 1);
filtered = set(params, parentPath, parent);
// this works just for the firstly found array item, because in case of removing the last one
// it leaves `[]` as a value.
return true;
}
return false;
});
return filtered;
};
/**
* @module flat
* @name flat
* @new in version 3.3
* @load ./flat.doc.md
*/
const flat = {
/**
* Raw `flatten` function exported from original {@link https://www.npmjs.com/package/flat flat}
* package.
*/
flatten: flatModule.flatten,
/**
* Raw `unflatten` function exported from original {@link https://www.npmjs.com/package/flat flat}
* package.
*/
unflatten: flatModule.unflatten,
set,
get: get$3,
selectParams,
filterOutParams,
removePath,
DELIMITER,
pathToParts,
merge: merge$4
};
/* eslint complexity: [2, 18], max-statements: [2, 33] */
var shams = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = shams;
var hasSymbols$1 = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice$2 = Array.prototype.slice;
var toStr$1 = Object.prototype.toString;
var funcType = '[object Function]';
var implementation$1 = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr$1.call(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slice$2.call(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
args.concat(slice$2.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(
that,
args.concat(slice$2.call(arguments))
);
}
};
var boundLength = Math.max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs.push('$' + i);
}
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
var implementation = implementation$1;
var functionBind = Function.prototype.bind || implementation;
var bind$2 = functionBind;
var src = bind$2.call(Function.call, Object.prototype.hasOwnProperty);
var undefined$1;
var $SyntaxError = SyntaxError;
var $Function = Function;
var $TypeError$1 = TypeError;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError$1();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = hasSymbols$1();
var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' ? undefined$1 : getProto(Uint8Array);
var INTRINSICS = {
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined$1 : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined$1,
'%AsyncFromSyncIteratorPrototype%': undefined$1,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined$1 : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined$1 : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined$1 : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined$1 : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined$1,
'%JSON%': typeof JSON === 'object' ? JSON : undefined$1,
'%Map%': typeof Map === 'undefined' ? undefined$1 : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined$1 : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy,
'%RangeError%': RangeError,
'%ReferenceError%': ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined$1 : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined$1 : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined$1,
'%Symbol%': hasSymbols ? Symbol : undefined$1,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError$1,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array,
'%URIError%': URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined$1 : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet
};
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind$1 = functionBind;
var hasOwn$1 = src;
var $concat$1 = bind$1.call(Function.call, Array.prototype.concat);
var $spliceApply = bind$1.call(Function.apply, Array.prototype.splice);
var $replace$1 = bind$1.call(Function.call, String.prototype.replace);
var $strSlice = bind$1.call(Function.call, String.prototype.slice);
var $exec = bind$1.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName$1 = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar$1 = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath$2 = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace$1(string, rePropName$1, function (match, number, quote, subString) {
result[result.length] = quote ? $replace$1(subString, reEscapeChar$1, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn$1(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn$1(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError$1('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
var getIntrinsic = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError$1('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError$1('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath$2(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat$1([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn$1(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError$1('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined$1;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn$1(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
var callBind$1 = {exports: {}};
(function (module) {
var bind = functionBind;
var GetIntrinsic = getIntrinsic;
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
var $max = GetIntrinsic('%Math.max%');
if ($defineProperty) {
try {
$defineProperty({}, 'a', { value: 1 });
} catch (e) {
// IE 8 has a broken defineProperty
$defineProperty = null;
}
}
module.exports = function callBind(originalFunction) {
var func = $reflectApply(bind, $call, arguments);
if ($gOPD && $defineProperty) {
var desc = $gOPD(func, 'length');
if (desc.configurable) {
// original length, plus the receiver, minus any additional arguments (after the receiver)
$defineProperty(
func,
'length',
{ value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }
);
}
}
return func;
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
} (callBind$1));
var callBindExports = callBind$1.exports;
var GetIntrinsic$1 = getIntrinsic;
var callBind = callBindExports;
var $indexOf = callBind(GetIntrinsic$1('String.prototype.indexOf'));
var callBound$1 = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic$1(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
var _nodeResolve_empty = {};
var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
default: _nodeResolve_empty
});
var require$$0 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1);
var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;
var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString$2 = Object.prototype.toString;
var functionToString = Function.prototype.toString;
var $match = String.prototype.match;
var $slice = String.prototype.slice;
var $replace = String.prototype.replace;
var $toUpperCase = String.prototype.toUpperCase;
var $toLowerCase = String.prototype.toLowerCase;
var $test = RegExp.prototype.test;
var $concat = Array.prototype.concat;
var $join = Array.prototype.join;
var $arrSlice = Array.prototype.slice;
var $floor = Math.floor;
var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;
var gOPS = Object.getOwnPropertySymbols;
var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null;
var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object';
// ie, `has-tostringtag/shams
var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol')
? Symbol.toStringTag
: null;
var isEnumerable = Object.prototype.propertyIsEnumerable;
var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || (
[].__proto__ === Array.prototype // eslint-disable-line no-proto
? function (O) {
return O.__proto__; // eslint-disable-line no-proto
}
: null
);
function addNumericSeparator(num, str) {
if (
num === Infinity
|| num === -Infinity
|| num !== num
|| (num && num > -1000 && num < 1000)
|| $test.call(/e/, str)
) {
return str;
}
var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
if (typeof num === 'number') {
var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num)
if (int !== num) {
var intStr = String(int);
var dec = $slice.call(str, intStr.length + 1);
return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, '');
}
}
return $replace.call(str, sepRegex, '$&_');
}
var utilInspect = require$$0;
var inspectCustom = utilInspect.custom;
var inspectSymbol = isSymbol$5(inspectCustom) ? inspectCustom : null;
var objectInspect = function inspect_(obj, options, depth, seen) {
var opts = options || {};
if (has$3(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {
throw new TypeError('option "quoteStyle" must be "single" or "double"');
}
if (
has$3(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number'
? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity
: opts.maxStringLength !== null
)
) {
throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
}
var customInspect = has$3(opts, 'customInspect') ? opts.customInspect : true;
if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') {
throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`');
}
if (
has$3(opts, 'indent')
&& opts.indent !== null
&& opts.indent !== '\t'
&& !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)
) {
throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
}
if (has$3(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') {
throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
}
var numericSeparator = opts.numericSeparator;
if (typeof obj === 'undefined') {
return 'undefined';
}
if (obj === null) {
return 'null';
}
if (typeof obj === 'boolean') {
return obj ? 'true' : 'false';
}
if (typeof obj === 'string') {
return inspectString(obj, opts);
}
if (typeof obj === 'number') {
if (obj === 0) {
return Infinity / obj > 0 ? '0' : '-0';
}
var str = String(obj);
return numericSeparator ? addNumericSeparator(obj, str) : str;
}
if (typeof obj === 'bigint') {
var bigIntStr = String(obj) + 'n';
return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
}
var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
if (typeof depth === 'undefined') { depth = 0; }
if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
return isArray$f(obj) ? '[Array]' : '[Object]';
}
var indent = getIndent(opts, depth);
if (typeof seen === 'undefined') {
seen = [];
} else if (indexOf(seen, obj) >= 0) {
return '[Circular]';
}
function inspect(value, from, noIndent) {
if (from) {
seen = $arrSlice.call(seen);
seen.push(from);
}
if (noIndent) {
var newOpts = {
depth: opts.depth
};
if (has$3(opts, 'quoteStyle')) {
newOpts.quoteStyle = opts.quoteStyle;
}
return inspect_(value, newOpts, depth + 1, seen);
}
return inspect_(value, opts, depth + 1, seen);
}
if (typeof obj === 'function' && !isRegExp$4(obj)) { // in older engines, regexes are callable
var name = nameOf(obj);
var keys = arrObjKeys(obj, inspect);
return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : '');
}
if (isSymbol$5(obj)) {
var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj);
return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString;
}
if (isElement$1(obj)) {
var s = '<' + $toLowerCase.call(String(obj.nodeName));
var attrs = obj.attributes || [];
for (var i = 0; i < attrs.length; i++) {
s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
}
s += '>';
if (obj.childNodes && obj.childNodes.length) { s += '...'; }
s += '</' + $toLowerCase.call(String(obj.nodeName)) + '>';
return s;
}
if (isArray$f(obj)) {
if (obj.length === 0) { return '[]'; }
var xs = arrObjKeys(obj, inspect);
if (indent && !singleLineValues(xs)) {
return '[' + indentedJoin(xs, indent) + ']';
}
return '[ ' + $join.call(xs, ', ') + ' ]';
}
if (isError(obj)) {
var parts = arrObjKeys(obj, inspect);
if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) {
return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }';
}
if (parts.length === 0) { return '[' + String(obj) + ']'; }
return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }';
}
if (typeof obj === 'object' && customInspect) {
if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) {
return utilInspect(obj, { depth: maxDepth - depth });
} else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') {
return obj.inspect();
}
}
if (isMap(obj)) {
var mapParts = [];
if (mapForEach) {
mapForEach.call(obj, function (value, key) {
mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj));
});
}
return collectionOf('Map', mapSize.call(obj), mapParts, indent);
}
if (isSet(obj)) {
var setParts = [];
if (setForEach) {
setForEach.call(obj, function (value) {
setParts.push(inspect(value, obj));
});
}
return collectionOf('Set', setSize.call(obj), setParts, indent);
}
if (isWeakMap(obj)) {
return weakCollectionOf('WeakMap');
}
if (isWeakSet(obj)) {
return weakCollectionOf('WeakSet');
}
if (isWeakRef(obj)) {
return weakCollectionOf('WeakRef');
}
if (isNumber$1(obj)) {
return markBoxed(inspect(Number(obj)));
}
if (isBigInt(obj)) {
return markBoxed(inspect(bigIntValueOf.call(obj)));
}
if (isBoolean$2(obj)) {
return markBoxed(booleanValueOf.call(obj));
}
if (isString$1(obj)) {
return markBoxed(inspect(String(obj)));
}
if (!isDate$1(obj) && !isRegExp$4(obj)) {
var ys = arrObjKeys(obj, inspect);
var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
var protoTag = obj instanceof Object ? '' : 'null prototype';
var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : '';
var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : '';
var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : '');
if (ys.length === 0) { return tag + '{}'; }
if (indent) {
return tag + '{' + indentedJoin(ys, indent) + '}';
}
return tag + '{ ' + $join.call(ys, ', ') + ' }';
}
return String(obj);
};
function wrapQuotes(s, defaultStyle, opts) {
var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'";
return quoteChar + s + quoteChar;
}
function quote(s) {
return $replace.call(String(s), /"/g, '"');
}
function isArray$f(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isDate$1(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isRegExp$4(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isString$1(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isNumber$1(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isBoolean$2(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives
function isSymbol$5(obj) {
if (hasShammedSymbols) {
return obj && typeof obj === 'object' && obj instanceof Symbol;
}
if (typeof obj === 'symbol') {
return true;
}
if (!obj || typeof obj !== 'object' || !symToString) {
return false;
}
try {
symToString.call(obj);
return true;
} catch (e) {}
return false;
}
function isBigInt(obj) {
if (!obj || typeof obj !== 'object' || !bigIntValueOf) {
return false;
}
try {
bigIntValueOf.call(obj);
return true;
} catch (e) {}
return false;
}
var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
function has$3(obj, key) {
return hasOwn.call(obj, key);
}
function toStr(obj) {
return objectToString$2.call(obj);
}
function nameOf(f) {
if (f.name) { return f.name; }
var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/);
if (m) { return m[1]; }
return null;
}
function indexOf(xs, x) {
if (xs.indexOf) { return xs.indexOf(x); }
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) { return i; }
}
return -1;
}
function isMap(x) {
if (!mapSize || !x || typeof x !== 'object') {
return false;
}
try {
mapSize.call(x);
try {
setSize.call(x);
} catch (s) {
return true;
}
return x instanceof Map; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakMap(x) {
if (!weakMapHas || !x || typeof x !== 'object') {
return false;
}
try {
weakMapHas.call(x, weakMapHas);
try {
weakSetHas.call(x, weakSetHas);
} catch (s) {
return true;
}
return x instanceof WeakMap; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakRef(x) {
if (!weakRefDeref || !x || typeof x !== 'object') {
return false;
}
try {
weakRefDeref.call(x);
return true;
} catch (e) {}
return false;
}
function isSet(x) {
if (!setSize || !x || typeof x !== 'object') {
return false;
}
try {
setSize.call(x);
try {
mapSize.call(x);
} catch (m) {
return true;
}
return x instanceof Set; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakSet(x) {
if (!weakSetHas || !x || typeof x !== 'object') {
return false;
}
try {
weakSetHas.call(x, weakSetHas);
try {
weakMapHas.call(x, weakMapHas);
} catch (s) {
return true;
}
return x instanceof WeakSet; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isElement$1(x) {
if (!x || typeof x !== 'object') { return false; }
if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
return true;
}
return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';
}
function inspectString(str, opts) {
if (str.length > opts.maxStringLength) {
var remaining = str.length - opts.maxStringLength;
var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : '');
return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;
}
// eslint-disable-next-line no-control-regex
var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte);
return wrapQuotes(s, 'single', opts);
}
function lowbyte(c) {
var n = c.charCodeAt(0);
var x = {
8: 'b',
9: 't',
10: 'n',
12: 'f',
13: 'r'
}[n];
if (x) { return '\\' + x; }
return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16));
}
function markBoxed(str) {
return 'Object(' + str + ')';
}
function weakCollectionOf(type) {
return type + ' { ? }';
}
function collectionOf(type, size, entries, indent) {
var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', ');
return type + ' (' + size + ') {' + joinedEntries + '}';
}
function singleLineValues(xs) {
for (var i = 0; i < xs.length; i++) {
if (indexOf(xs[i], '\n') >= 0) {
return false;
}
}
return true;
}
function getIndent(opts, depth) {
var baseIndent;
if (opts.indent === '\t') {
baseIndent = '\t';
} else if (typeof opts.indent === 'number' && opts.indent > 0) {
baseIndent = $join.call(Array(opts.indent + 1), ' ');
} else {
return null;
}
return {
base: baseIndent,
prev: $join.call(Array(depth + 1), baseIndent)
};
}
function indentedJoin(xs, indent) {
if (xs.length === 0) { return ''; }
var lineJoiner = '\n' + indent.prev + indent.base;
return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev;
}
function arrObjKeys(obj, inspect) {
var isArr = isArray$f(obj);
var xs = [];
if (isArr) {
xs.length = obj.length;
for (var i = 0; i < obj.length; i++) {
xs[i] = has$3(obj, i) ? inspect(obj[i], obj) : '';
}
}
var syms = typeof gOPS === 'function' ? gOPS(obj) : [];
var symMap;
if (hasShammedSymbols) {
symMap = {};
for (var k = 0; k < syms.length; k++) {
symMap['$' + syms[k]] = syms[k];
}
}
for (var key in obj) { // eslint-disable-line no-restricted-syntax
if (!has$3(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) {
// this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section
continue; // eslint-disable-line no-restricted-syntax, no-continue
} else if ($test.call(/[^\w$]/, key)) {
xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
} else {
xs.push(key + ': ' + inspect(obj[key], obj));
}
}
if (typeof gOPS === 'function') {
for (var j = 0; j < syms.length; j++) {
if (isEnumerable.call(obj, syms[j])) {
xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj));
}
}
}
return xs;
}
var GetIntrinsic = getIntrinsic;
var callBound = callBound$1;
var inspect = objectInspect;
var $TypeError = GetIntrinsic('%TypeError%');
var $WeakMap = GetIntrinsic('%WeakMap%', true);
var $Map = GetIntrinsic('%Map%', true);
var $weakMapGet = callBound('WeakMap.prototype.get', true);
var $weakMapSet = callBound('WeakMap.prototype.set', true);
var $weakMapHas = callBound('WeakMap.prototype.has', true);
var $mapGet = callBound('Map.prototype.get', true);
var $mapSet = callBound('Map.prototype.set', true);
var $mapHas = callBound('Map.prototype.has', true);
/*
* This function traverses the list returning the node corresponding to the
* given key.
*
* That node is also moved to the head of the list, so that if it's accessed
* again we don't need to traverse the whole list. By doing so, all the recently
* used nodes can be accessed relatively quickly.
*/
var listGetNode = function (list, key) { // eslint-disable-line consistent-return
for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) {
if (curr.key === key) {
prev.next = curr.next;
curr.next = list.next;
list.next = curr; // eslint-disable-line no-param-reassign
return curr;
}
}
};
var listGet = function (objects, key) {
var node = listGetNode(objects, key);
return node && node.value;
};
var listSet = function (objects, key, value) {
var node = listGetNode(objects, key);
if (node) {
node.value = value;
} else {
// Prepend the new node to the beginning of the list
objects.next = { // eslint-disable-line no-param-reassign
key: key,
next: objects.next,
value: value
};
}
};
var listHas = function (objects, key) {
return !!listGetNode(objects, key);
};
var sideChannel = function getSideChannel() {
var $wm;
var $m;
var $o;
var channel = {
assert: function (key) {
if (!channel.has(key)) {
throw new $TypeError('Side channel does not contain ' + inspect(key));
}
},
get: function (key) { // eslint-disable-line consistent-return
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
if ($wm) {
return $weakMapGet($wm, key);
}
} else if ($Map) {
if ($m) {
return $mapGet($m, key);
}
} else {
if ($o) { // eslint-disable-line no-lonely-if
return listGet($o, key);
}
}
},
has: function (key) {
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
if ($wm) {
return $weakMapHas($wm, key);
}
} else if ($Map) {
if ($m) {
return $mapHas($m, key);
}
} else {
if ($o) { // eslint-disable-line no-lonely-if
return listHas($o, key);
}
}
return false;
},
set: function (key, value) {
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
if (!$wm) {
$wm = new $WeakMap();
}
$weakMapSet($wm, key, value);
} else if ($Map) {
if (!$m) {
$m = new $Map();
}
$mapSet($m, key, value);
} else {
if (!$o) {
/*
* Initialize the linked list as an empty node, so that we don't have
* to special-case handling of the first node: we can always refer to
* it as (previous node).next, instead of something like (list).head
*/
$o = { key: {}, next: null };
}
listSet($o, key, value);
}
}
};
return channel;
};
var replace = String.prototype.replace;
var percentTwenties = /%20/g;
var Format = {
RFC1738: 'RFC1738',
RFC3986: 'RFC3986'
};
var formats$3 = {
'default': Format.RFC3986,
formatters: {
RFC1738: function (value) {
return replace.call(value, percentTwenties, '+');
},
RFC3986: function (value) {
return String(value);
}
},
RFC1738: Format.RFC1738,
RFC3986: Format.RFC3986
};
var formats$2 = formats$3;
var has$2 = Object.prototype.hasOwnProperty;
var isArray$e = Array.isArray;
var hexTable = (function () {
var array = [];
for (var i = 0; i < 256; ++i) {
array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
}
return array;
}());
var compactQueue = function compactQueue(queue) {
while (queue.length > 1) {
var item = queue.pop();
var obj = item.obj[item.prop];
if (isArray$e(obj)) {
var compacted = [];
for (var j = 0; j < obj.length; ++j) {
if (typeof obj[j] !== 'undefined') {
compacted.push(obj[j]);
}
}
item.obj[item.prop] = compacted;
}
}
};
var arrayToObject$1 = function arrayToObject(source, options) {
var obj = options && options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
var merge$3 = function merge(target, source, options) {
/* eslint no-param-reassign: 0 */
if (!source) {
return target;
}
if (typeof source !== 'object') {
if (isArray$e(target)) {
target.push(source);
} else if (target && typeof target === 'object') {
if ((options && (options.plainObjects || options.allowPrototypes)) || !has$2.call(Object.prototype, source)) {
target[source] = true;
}
} else {
return [target, source];
}
return target;
}
if (!target || typeof target !== 'object') {
return [target].concat(source);
}
var mergeTarget = target;
if (isArray$e(target) && !isArray$e(source)) {
mergeTarget = arrayToObject$1(target, options);
}
if (isArray$e(target) && isArray$e(source)) {
source.forEach(function (item, i) {
if (has$2.call(target, i)) {
var targetItem = target[i];
if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {
target[i] = merge(targetItem, item, options);
} else {
target.push(item);
}
} else {
target[i] = item;
}
});
return target;
}
return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
if (has$2.call(acc, key)) {
acc[key] = merge(acc[key], value, options);
} else {
acc[key] = value;
}
return acc;
}, mergeTarget);
};
var assign$1 = function assignSingleSource(target, source) {
return Object.keys(source).reduce(function (acc, key) {
acc[key] = source[key];
return acc;
}, target);
};
var decode = function (str, decoder, charset) {
var strWithoutPlus = str.replace(/\+/g, ' ');
if (charset === 'iso-8859-1') {
// unescape never throws, no try...catch needed:
return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
}
// utf-8
try {
return decodeURIComponent(strWithoutPlus);
} catch (e) {
return strWithoutPlus;
}
};
var encode$2 = function encode(str, defaultEncoder, charset, kind, format) {
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
var string = str;
if (typeof str === 'symbol') {
string = Symbol.prototype.toString.call(str);
} else if (typeof str !== 'string') {
string = String(str);
}
if (charset === 'iso-8859-1') {
return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {
return '%26%23' + parseInt($0.slice(2), 16) + '%3B';
});
}
var out = '';
for (var i = 0; i < string.length; ++i) {
var c = string.charCodeAt(i);
if (
c === 0x2D // -
|| c === 0x2E // .
|| c === 0x5F // _
|| c === 0x7E // ~
|| (c >= 0x30 && c <= 0x39) // 0-9
|| (c >= 0x41 && c <= 0x5A) // a-z
|| (c >= 0x61 && c <= 0x7A) // A-Z
|| (format === formats$2.RFC1738 && (c === 0x28 || c === 0x29)) // ( )
) {
out += string.charAt(i);
continue;
}
if (c < 0x80) {
out = out + hexTable[c];
continue;
}
if (c < 0x800) {
out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
i += 1;
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
/* eslint operator-linebreak: [2, "before"] */
out += hexTable[0xF0 | (c >> 18)]
+ hexTable[0x80 | ((c >> 12) & 0x3F)]
+ hexTable[0x80 | ((c >> 6) & 0x3F)]
+ hexTable[0x80 | (c & 0x3F)];
}
return out;
};
var compact = function compact(value) {
var queue = [{ obj: { o: value }, prop: 'o' }];
var refs = [];
for (var i = 0; i < queue.length; ++i) {
var item = queue[i];
var obj = item.obj[item.prop];
var keys = Object.keys(obj);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
var val = obj[key];
if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
queue.push({ obj: obj, prop: key });
refs.push(val);
}
}
}
compactQueue(queue);
return value;
};
var isRegExp$3 = function isRegExp(obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
var isBuffer$5 = function isBuffer(obj) {
if (!obj || typeof obj !== 'object') {
return false;
}
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
var combine$1 = function combine(a, b) {
return [].concat(a, b);
};
var maybeMap = function maybeMap(val, fn) {
if (isArray$e(val)) {
var mapped = [];
for (var i = 0; i < val.length; i += 1) {
mapped.push(fn(val[i]));
}
return mapped;
}
return fn(val);
};
var utils$3 = {
arrayToObject: arrayToObject$1,
assign: assign$1,
combine: combine$1,
compact: compact,
decode: decode,
encode: encode$2,
isBuffer: isBuffer$5,
isRegExp: isRegExp$3,
maybeMap: maybeMap,
merge: merge$3
};
var getSideChannel = sideChannel;
var utils$2 = utils$3;
var formats$1 = formats$3;
var has$1 = Object.prototype.hasOwnProperty;
var arrayPrefixGenerators = {
brackets: function brackets(prefix) {
return prefix + '[]';
},
comma: 'comma',
indices: function indices(prefix, key) {
return prefix + '[' + key + ']';
},
repeat: function repeat(prefix) {
return prefix;
}
};
var isArray$d = Array.isArray;
var push = Array.prototype.push;
var pushToArray = function (arr, valueOrArray) {
push.apply(arr, isArray$d(valueOrArray) ? valueOrArray : [valueOrArray]);
};
var toISO = Date.prototype.toISOString;
var defaultFormat = formats$1['default'];
var defaults$6 = {
addQueryPrefix: false,
allowDots: false,
charset: 'utf-8',
charsetSentinel: false,
delimiter: '&',
encode: true,
encoder: utils$2.encode,
encodeValuesOnly: false,
format: defaultFormat,
formatter: formats$1.formatters[defaultFormat],
// deprecated
indices: false,
serializeDate: function serializeDate(date) {
return toISO.call(date);
},
skipNulls: false,
strictNullHandling: false
};
var isNonNullishPrimitive = function isNonNullishPrimitive(v) {
return typeof v === 'string'
|| typeof v === 'number'
|| typeof v === 'boolean'
|| typeof v === 'symbol'
|| typeof v === 'bigint';
};
var sentinel = {};
var stringify$1 = function stringify(
object,
prefix,
generateArrayPrefix,
commaRoundTrip,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
format,
formatter,
encodeValuesOnly,
charset,
sideChannel
) {
var obj = object;
var tmpSc = sideChannel;
var step = 0;
var findFlag = false;
while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) {
// Where object last appeared in the ref tree
var pos = tmpSc.get(object);
step += 1;
if (typeof pos !== 'undefined') {
if (pos === step) {
throw new RangeError('Cyclic object value');
} else {
findFlag = true; // Break while
}
}
if (typeof tmpSc.get(sentinel) === 'undefined') {
step = 0;
}
}
if (typeof filter === 'function') {
obj = filter(prefix, obj);
} else if (obj instanceof Date) {
obj = serializeDate(obj);
} else if (generateArrayPrefix === 'comma' && isArray$d(obj)) {
obj = utils$2.maybeMap(obj, function (value) {
if (value instanceof Date) {
return serializeDate(value);
}
return value;
});
}
if (obj === null) {
if (strictNullHandling) {
return encoder && !encodeValuesOnly ? encoder(prefix, defaults$6.encoder, charset, 'key', format) : prefix;
}
obj = '';
}
if (isNonNullishPrimitive(obj) || utils$2.isBuffer(obj)) {
if (encoder) {
var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults$6.encoder, charset, 'key', format);
return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults$6.encoder, charset, 'value', format))];
}
return [formatter(prefix) + '=' + formatter(String(obj))];
}
var values = [];
if (typeof obj === 'undefined') {
return values;
}
var objKeys;
if (generateArrayPrefix === 'comma' && isArray$d(obj)) {
// we need to join elements in
if (encodeValuesOnly && encoder) {
obj = utils$2.maybeMap(obj, encoder);
}
objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];
} else if (isArray$d(filter)) {
objKeys = filter;
} else {
var keys = Object.keys(obj);
objKeys = sort ? keys.sort(sort) : keys;
}
var adjustedPrefix = commaRoundTrip && isArray$d(obj) && obj.length === 1 ? prefix + '[]' : prefix;
for (var j = 0; j < objKeys.length; ++j) {
var key = objKeys[j];
var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key];
if (skipNulls && value === null) {
continue;
}
var keyPrefix = isArray$d(obj)
? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix
: adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']');
sideChannel.set(object, step);
var valueSideChannel = getSideChannel();
valueSideChannel.set(sentinel, sideChannel);
pushToArray(values, stringify(
value,
keyPrefix,
generateArrayPrefix,
commaRoundTrip,
strictNullHandling,
skipNulls,
generateArrayPrefix === 'comma' && encodeValuesOnly && isArray$d(obj) ? null : encoder,
filter,
sort,
allowDots,
serializeDate,
format,
formatter,
encodeValuesOnly,
charset,
valueSideChannel
));
}
return values;
};
var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
if (!opts) {
return defaults$6;
}
if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') {
throw new TypeError('Encoder has to be a function.');
}
var charset = opts.charset || defaults$6.charset;
if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
}
var format = formats$1['default'];
if (typeof opts.format !== 'undefined') {
if (!has$1.call(formats$1.formatters, opts.format)) {
throw new TypeError('Unknown format option provided.');
}
format = opts.format;
}
var formatter = formats$1.formatters[format];
var filter = defaults$6.filter;
if (typeof opts.filter === 'function' || isArray$d(opts.filter)) {
filter = opts.filter;
}
return {
addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults$6.addQueryPrefix,
allowDots: typeof opts.allowDots === 'undefined' ? defaults$6.allowDots : !!opts.allowDots,
charset: charset,
charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults$6.charsetSentinel,
delimiter: typeof opts.delimiter === 'undefined' ? defaults$6.delimiter : opts.delimiter,
encode: typeof opts.encode === 'boolean' ? opts.encode : defaults$6.encode,
encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults$6.encoder,
encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults$6.encodeValuesOnly,
filter: filter,
format: format,
formatter: formatter,
serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults$6.serializeDate,
skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults$6.skipNulls,
sort: typeof opts.sort === 'function' ? opts.sort : null,
strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults$6.strictNullHandling
};
};
var stringify_1 = function (object, opts) {
var obj = object;
var options = normalizeStringifyOptions(opts);
var objKeys;
var filter;
if (typeof options.filter === 'function') {
filter = options.filter;
obj = filter('', obj);
} else if (isArray$d(options.filter)) {
filter = options.filter;
objKeys = filter;
}
var keys = [];
if (typeof obj !== 'object' || obj === null) {
return '';
}
var arrayFormat;
if (opts && opts.arrayFormat in arrayPrefixGenerators) {
arrayFormat = opts.arrayFormat;
} else if (opts && 'indices' in opts) {
arrayFormat = opts.indices ? 'indices' : 'repeat';
} else {
arrayFormat = 'indices';
}
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') {
throw new TypeError('`commaRoundTrip` must be a boolean, or absent');
}
var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip;
if (!objKeys) {
objKeys = Object.keys(obj);
}
if (options.sort) {
objKeys.sort(options.sort);
}
var sideChannel = getSideChannel();
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (options.skipNulls && obj[key] === null) {
continue;
}
pushToArray(keys, stringify$1(
obj[key],
key,
generateArrayPrefix,
commaRoundTrip,
options.strictNullHandling,
options.skipNulls,
options.encode ? options.encoder : null,
options.filter,
options.sort,
options.allowDots,
options.serializeDate,
options.format,
options.formatter,
options.encodeValuesOnly,
options.charset,
sideChannel
));
}
var joined = keys.join(options.delimiter);
var prefix = options.addQueryPrefix === true ? '?' : '';
if (options.charsetSentinel) {
if (options.charset === 'iso-8859-1') {
// encodeURIComponent('✓'), the "numeric entity" representation of a checkmark
prefix += 'utf8=%26%2310003%3B&';
} else {
// encodeURIComponent('✓')
prefix += 'utf8=%E2%9C%93&';
}
}
return joined.length > 0 ? prefix + joined : '';
};
var utils$1 = utils$3;
var has = Object.prototype.hasOwnProperty;
var isArray$c = Array.isArray;
var defaults$5 = {
allowDots: false,
allowPrototypes: false,
allowSparse: false,
arrayLimit: 20,
charset: 'utf-8',
charsetSentinel: false,
comma: false,
decoder: utils$1.decode,
delimiter: '&',
depth: 5,
ignoreQueryPrefix: false,
interpretNumericEntities: false,
parameterLimit: 1000,
parseArrays: true,
plainObjects: false,
strictNullHandling: false
};
var interpretNumericEntities = function (str) {
return str.replace(/&#(\d+);/g, function ($0, numberStr) {
return String.fromCharCode(parseInt(numberStr, 10));
});
};
var parseArrayValue = function (val, options) {
if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {
return val.split(',');
}
return val;
};
// This is what browsers will submit when the ✓ character occurs in an
// application/x-www-form-urlencoded body and the encoding of the page containing
// the form is iso-8859-1, or when the submitted form has an accept-charset
// attribute of iso-8859-1. Presumably also with other charsets that do not contain
// the ✓ character, such as us-ascii.
var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓')
// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')
var parseValues = function parseQueryStringValues(str, options) {
var obj = {};
var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
var parts = cleanStr.split(options.delimiter, limit);
var skipIndex = -1; // Keep track of where the utf8 sentinel was found
var i;
var charset = options.charset;
if (options.charsetSentinel) {
for (i = 0; i < parts.length; ++i) {
if (parts[i].indexOf('utf8=') === 0) {
if (parts[i] === charsetSentinel) {
charset = 'utf-8';
} else if (parts[i] === isoSentinel) {
charset = 'iso-8859-1';
}
skipIndex = i;
i = parts.length; // The eslint settings do not allow break;
}
}
}
for (i = 0; i < parts.length; ++i) {
if (i === skipIndex) {
continue;
}
var part = parts[i];
var bracketEqualsPos = part.indexOf(']=');
var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
var key, val;
if (pos === -1) {
key = options.decoder(part, defaults$5.decoder, charset, 'key');
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos), defaults$5.decoder, charset, 'key');
val = utils$1.maybeMap(
parseArrayValue(part.slice(pos + 1), options),
function (encodedVal) {
return options.decoder(encodedVal, defaults$5.decoder, charset, 'value');
}
);
}
if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
val = interpretNumericEntities(val);
}
if (part.indexOf('[]=') > -1) {
val = isArray$c(val) ? [val] : val;
}
if (has.call(obj, key)) {
obj[key] = utils$1.combine(obj[key], val);
} else {
obj[key] = val;
}
}
return obj;
};
var parseObject = function (chain, val, options, valuesParsed) {
var leaf = valuesParsed ? val : parseArrayValue(val, options);
for (var i = chain.length - 1; i >= 0; --i) {
var obj;
var root = chain[i];
if (root === '[]' && options.parseArrays) {
obj = [].concat(leaf);
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
var index = parseInt(cleanRoot, 10);
if (!options.parseArrays && cleanRoot === '') {
obj = { 0: leaf };
} else if (
!isNaN(index)
&& root !== cleanRoot
&& String(index) === cleanRoot
&& index >= 0
&& (options.parseArrays && index <= options.arrayLimit)
) {
obj = [];
obj[index] = leaf;
} else if (cleanRoot !== '__proto__') {
obj[cleanRoot] = leaf;
}
}
leaf = obj;
}
return leaf;
};
var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
if (!givenKey) {
return;
}
// Transform dot notation to bracket notation
var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
// The regex chunks
var brackets = /(\[[^[\]]*])/;
var child = /(\[[^[\]]*])/g;
// Get the parent
var segment = options.depth > 0 && brackets.exec(key);
var parent = segment ? key.slice(0, segment.index) : key;
// Stash the parent if it exists
var keys = [];
if (parent) {
// If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties
if (!options.plainObjects && has.call(Object.prototype, parent)) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(parent);
}
// Loop through children appending to the array until we hit depth
var i = 0;
while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) {
i += 1;
if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(segment[1]);
}
// If there's a remainder, just add whatever is left
if (segment) {
keys.push('[' + key.slice(segment.index) + ']');
}
return parseObject(keys, val, options, valuesParsed);
};
var normalizeParseOptions = function normalizeParseOptions(opts) {
if (!opts) {
return defaults$5;
}
if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {
throw new TypeError('Decoder has to be a function.');
}
if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
}
var charset = typeof opts.charset === 'undefined' ? defaults$5.charset : opts.charset;
return {
allowDots: typeof opts.allowDots === 'undefined' ? defaults$5.allowDots : !!opts.allowDots,
allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults$5.allowPrototypes,
allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults$5.allowSparse,
arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults$5.arrayLimit,
charset: charset,
charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults$5.charsetSentinel,
comma: typeof opts.comma === 'boolean' ? opts.comma : defaults$5.comma,
decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults$5.decoder,
delimiter: typeof opts.delimiter === 'string' || utils$1.isRegExp(opts.delimiter) ? opts.delimiter : defaults$5.delimiter,
// eslint-disable-next-line no-implicit-coercion, no-extra-parens
depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults$5.depth,
ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults$5.interpretNumericEntities,
parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults$5.parameterLimit,
parseArrays: opts.parseArrays !== false,
plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults$5.plainObjects,
strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults$5.strictNullHandling
};
};
var parse$2 = function (str, opts) {
var options = normalizeParseOptions(opts);
if (str === '' || str === null || typeof str === 'undefined') {
return options.plainObjects ? Object.create(null) : {};
}
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
var obj = options.plainObjects ? Object.create(null) : {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');
obj = utils$1.merge(obj, newObj, options);
}
if (options.allowSparse === true) {
return obj;
}
return utils$1.compact(obj);
};
var stringify = stringify_1;
var parse$1 = parse$2;
var formats = formats$3;
var lib$2 = {
formats: formats,
parse: parse$1,
stringify: stringify
};
function _extends$t() { _extends$t = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$t.apply(this, arguments); }
/**
* @private
*
* @classdesc
* Overrides one of the AdminJS core components when user passes it's name to ComponentLoader
*
* If case of being overridden, component receives additional prop: `OriginalComponent`
*
* @example
* new ComponentLoader().override('SidebarFooter', MySidebarFooter)
*/
function allowOverride(OriginalComponent, name) {
const WrapperComponent = props => {
let Component = OriginalComponent;
/**
* @new in version 6.3
*
* This adds support for future theme-specific components via their "theme.bundle.js"
*
*/
if (typeof window !== 'undefined') {
Component = window.AdminJS?.UserComponents?.[name] ?? window.THEME_COMPONENTS?.[name] ?? OriginalComponent;
}
return /*#__PURE__*/React__default$1.default.createElement(Component, _extends$t({}, props, {
OriginalComponent: OriginalComponent
}));
};
return WrapperComponent;
}
const actionHasDisabledComponent = action => typeof action.component !== 'undefined' && action.component === false;
const actionHasCustomComponent = action => typeof action.component === 'string';
const h$3 = new ViewHelpers();
const actionHref = (action, params) => {
const actionName = action.name;
if (!action.component && !action.hasHandler) {
return null;
}
if (params.recordIds?.length) {
params.recordIds = [...new Set(params.recordIds)];
}
const hrefMap = {
record: () => h$3.recordActionUrl({
...params,
actionName
}),
resource: () => h$3.resourceActionUrl({
resourceId: params.resourceId,
actionName,
search: params.search
}),
bulk: () => h$3.bulkActionUrl({
...params,
actionName
})
};
if (hrefMap[action.actionType]) {
return hrefMap[action.actionType]();
}
throw new Error('"actionType" should be either record, resource or bulk');
};
function bind(fn, thisArg) {
return function wrap() {
return fn.apply(thisArg, arguments);
};
}
// utils is a library of generic helper functions non-specific to axios
const {toString: toString$6} = Object.prototype;
const {getPrototypeOf} = Object;
const kindOf = (cache => thing => {
const str = toString$6.call(thing);
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
})(Object.create(null));
const kindOfTest = (type) => {
type = type.toLowerCase();
return (thing) => kindOf(thing) === type
};
const typeOfTest = type => thing => typeof thing === type;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
*
* @returns {boolean} True if value is an Array, otherwise false
*/
const {isArray: isArray$b} = Array;
/**
* Determine if a value is undefined
*
* @param {*} val The value to test
*
* @returns {boolean} True if the value is undefined, otherwise false
*/
const isUndefined = typeOfTest('undefined');
/**
* Determine if a value is a Buffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer$4(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
&& isFunction$4(val.constructor.isBuffer) && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
const isArrayBuffer = kindOfTest('ArrayBuffer');
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
let result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
}
return result;
}
/**
* Determine if a value is a String
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a String, otherwise false
*/
const isString = typeOfTest('string');
/**
* Determine if a value is a Function
*
* @param {*} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
const isFunction$4 = typeOfTest('function');
/**
* Determine if a value is a Number
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Number, otherwise false
*/
const isNumber = typeOfTest('number');
/**
* Determine if a value is an Object
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an Object, otherwise false
*/
const isObject$c = (thing) => thing !== null && typeof thing === 'object';
/**
* Determine if a value is a Boolean
*
* @param {*} thing The value to test
* @returns {boolean} True if value is a Boolean, otherwise false
*/
const isBoolean$1 = thing => thing === true || thing === false;
/**
* Determine if a value is a plain Object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a plain Object, otherwise false
*/
const isPlainObject$2 = (val) => {
if (kindOf(val) !== 'object') {
return false;
}
const prototype = getPrototypeOf(val);
return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
};
/**
* Determine if a value is a Date
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Date, otherwise false
*/
const isDate = kindOfTest('Date');
/**
* Determine if a value is a File
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
const isFile = kindOfTest('File');
/**
* Determine if a value is a Blob
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Blob, otherwise false
*/
const isBlob = kindOfTest('Blob');
/**
* Determine if a value is a FileList
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
const isFileList = kindOfTest('FileList');
/**
* Determine if a value is a Stream
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Stream, otherwise false
*/
const isStream = (val) => isObject$c(val) && isFunction$4(val.pipe);
/**
* Determine if a value is a FormData
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an FormData, otherwise false
*/
const isFormData = (thing) => {
const pattern = '[object FormData]';
return thing && (
(typeof FormData === 'function' && thing instanceof FormData) ||
toString$6.call(thing) === pattern ||
(isFunction$4(thing.toString) && thing.toString() === pattern)
);
};
/**
* Determine if a value is a URLSearchParams object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
const isURLSearchParams = kindOfTest('URLSearchParams');
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
*
* @returns {String} The String freed of excess whitespace
*/
const trim = (str) => str.trim ?
str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*
* @param {Boolean} [allOwnKeys = false]
* @returns {any}
*/
function forEach(obj, fn, {allOwnKeys = false} = {}) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
let i;
let l;
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray$b(obj)) {
// Iterate over array values
for (i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
fn.call(null, obj[key], key, obj);
}
}
}
function findKey(obj, key) {
key = key.toLowerCase();
const keys = Object.keys(obj);
let i = keys.length;
let _key;
while (i-- > 0) {
_key = keys[i];
if (key === _key.toLowerCase()) {
return _key;
}
}
return null;
}
const _global = (() => {
/*eslint no-undef:0*/
if (typeof globalThis !== "undefined") return globalThis;
return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global)
})();
const isContextDefined = (context) => !isUndefined(context) && context !== _global;
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
*
* @returns {Object} Result of all merge properties
*/
function merge$2(/* obj1, obj2, obj3, ... */) {
const {caseless} = isContextDefined(this) && this || {};
const result = {};
const assignValue = (val, key) => {
const targetKey = caseless && findKey(result, key) || key;
if (isPlainObject$2(result[targetKey]) && isPlainObject$2(val)) {
result[targetKey] = merge$2(result[targetKey], val);
} else if (isPlainObject$2(val)) {
result[targetKey] = merge$2({}, val);
} else if (isArray$b(val)) {
result[targetKey] = val.slice();
} else {
result[targetKey] = val;
}
};
for (let i = 0, l = arguments.length; i < l; i++) {
arguments[i] && forEach(arguments[i], assignValue);
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
*
* @param {Boolean} [allOwnKeys]
* @returns {Object} The resulting value of object a
*/
const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
forEach(b, (val, key) => {
if (thisArg && isFunction$4(val)) {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
}, {allOwnKeys});
return a;
};
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
*
* @returns {string} content value without BOM
*/
const stripBOM = (content) => {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
};
/**
* Inherit the prototype methods from one constructor into another
* @param {function} constructor
* @param {function} superConstructor
* @param {object} [props]
* @param {object} [descriptors]
*
* @returns {void}
*/
const inherits = (constructor, superConstructor, props, descriptors) => {
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
constructor.prototype.constructor = constructor;
Object.defineProperty(constructor, 'super', {
value: superConstructor.prototype
});
props && Object.assign(constructor.prototype, props);
};
/**
* Resolve object with deep prototype chain to a flat object
* @param {Object} sourceObj source object
* @param {Object} [destObj]
* @param {Function|Boolean} [filter]
* @param {Function} [propFilter]
*
* @returns {Object}
*/
const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
let props;
let i;
let prop;
const merged = {};
destObj = destObj || {};
// eslint-disable-next-line no-eq-null,eqeqeq
if (sourceObj == null) return destObj;
do {
props = Object.getOwnPropertyNames(sourceObj);
i = props.length;
while (i-- > 0) {
prop = props[i];
if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
destObj[prop] = sourceObj[prop];
merged[prop] = true;
}
}
sourceObj = filter !== false && getPrototypeOf(sourceObj);
} while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
return destObj;
};
/**
* Determines whether a string ends with the characters of a specified string
*
* @param {String} str
* @param {String} searchString
* @param {Number} [position= 0]
*
* @returns {boolean}
*/
const endsWith = (str, searchString, position) => {
str = String(str);
if (position === undefined || position > str.length) {
position = str.length;
}
position -= searchString.length;
const lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
/**
* Returns new array from array like object or null if failed
*
* @param {*} [thing]
*
* @returns {?Array}
*/
const toArray = (thing) => {
if (!thing) return null;
if (isArray$b(thing)) return thing;
let i = thing.length;
if (!isNumber(i)) return null;
const arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
return arr;
};
/**
* Checking if the Uint8Array exists and if it does, it returns a function that checks if the
* thing passed in is an instance of Uint8Array
*
* @param {TypedArray}
*
* @returns {Array}
*/
// eslint-disable-next-line func-names
const isTypedArray$4 = (TypedArray => {
// eslint-disable-next-line func-names
return thing => {
return TypedArray && thing instanceof TypedArray;
};
})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
/**
* For each entry in the object, call the function with the key and value.
*
* @param {Object<any, any>} obj - The object to iterate over.
* @param {Function} fn - The function to call for each entry.
*
* @returns {void}
*/
const forEachEntry = (obj, fn) => {
const generator = obj && obj[Symbol.iterator];
const iterator = generator.call(obj);
let result;
while ((result = iterator.next()) && !result.done) {
const pair = result.value;
fn.call(obj, pair[0], pair[1]);
}
};
/**
* It takes a regular expression and a string, and returns an array of all the matches
*
* @param {string} regExp - The regular expression to match against.
* @param {string} str - The string to search.
*
* @returns {Array<boolean>}
*/
const matchAll = (regExp, str) => {
let matches;
const arr = [];
while ((matches = regExp.exec(str)) !== null) {
arr.push(matches);
}
return arr;
};
/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
const isHTMLForm = kindOfTest('HTMLFormElement');
const toCamelCase = str => {
return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
function replacer(m, p1, p2) {
return p1.toUpperCase() + p2;
}
);
};
/* Creating a function that will check if an object has a property. */
const hasOwnProperty$c = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
/**
* Determine if a value is a RegExp object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a RegExp object, otherwise false
*/
const isRegExp$2 = kindOfTest('RegExp');
const reduceDescriptors = (obj, reducer) => {
const descriptors = Object.getOwnPropertyDescriptors(obj);
const reducedDescriptors = {};
forEach(descriptors, (descriptor, name) => {
if (reducer(descriptor, name, obj) !== false) {
reducedDescriptors[name] = descriptor;
}
});
Object.defineProperties(obj, reducedDescriptors);
};
/**
* Makes all methods read-only
* @param {Object} obj
*/
const freezeMethods = (obj) => {
reduceDescriptors(obj, (descriptor, name) => {
// skip restricted props in strict mode
if (isFunction$4(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
return false;
}
const value = obj[name];
if (!isFunction$4(value)) return;
descriptor.enumerable = false;
if ('writable' in descriptor) {
descriptor.writable = false;
return;
}
if (!descriptor.set) {
descriptor.set = () => {
throw Error('Can not rewrite read-only method \'' + name + '\'');
};
}
});
};
const toObjectSet = (arrayOrString, delimiter) => {
const obj = {};
const define = (arr) => {
arr.forEach(value => {
obj[value] = true;
});
};
isArray$b(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
return obj;
};
const noop$4 = () => {};
const toFiniteNumber = (value, defaultValue) => {
value = +value;
return Number.isFinite(value) ? value : defaultValue;
};
const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
const DIGIT = '0123456789';
const ALPHABET = {
DIGIT,
ALPHA,
ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
};
const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
let str = '';
const {length} = alphabet;
while (size--) {
str += alphabet[Math.random() * length|0];
}
return str;
};
/**
* If the thing is a FormData object, return true, otherwise return false.
*
* @param {unknown} thing - The thing to check.
*
* @returns {boolean}
*/
function isSpecCompliantForm(thing) {
return !!(thing && isFunction$4(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);
}
const toJSONObject = (obj) => {
const stack = new Array(10);
const visit = (source, i) => {
if (isObject$c(source)) {
if (stack.indexOf(source) >= 0) {
return;
}
if(!('toJSON' in source)) {
stack[i] = source;
const target = isArray$b(source) ? [] : {};
forEach(source, (value, key) => {
const reducedValue = visit(value, i + 1);
!isUndefined(reducedValue) && (target[key] = reducedValue);
});
stack[i] = undefined;
return target;
}
}
return source;
};
return visit(obj, 0);
};
var utils = {
isArray: isArray$b,
isArrayBuffer,
isBuffer: isBuffer$4,
isFormData,
isArrayBufferView,
isString,
isNumber,
isBoolean: isBoolean$1,
isObject: isObject$c,
isPlainObject: isPlainObject$2,
isUndefined,
isDate,
isFile,
isBlob,
isRegExp: isRegExp$2,
isFunction: isFunction$4,
isStream,
isURLSearchParams,
isTypedArray: isTypedArray$4,
isFileList,
forEach,
merge: merge$2,
extend,
trim,
stripBOM,
inherits,
toFlatObject,
kindOf,
kindOfTest,
endsWith,
toArray,
forEachEntry,
matchAll,
isHTMLForm,
hasOwnProperty: hasOwnProperty$c,
hasOwnProp: hasOwnProperty$c, // an alias to avoid ESLint no-prototype-builtins detection
reduceDescriptors,
freezeMethods,
toObjectSet,
toCamelCase,
noop: noop$4,
toFiniteNumber,
findKey,
global: _global,
isContextDefined,
ALPHABET,
generateString,
isSpecCompliantForm,
toJSONObject
};
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [config] The config.
* @param {Object} [request] The request.
* @param {Object} [response] The response.
*
* @returns {Error} The created error.
*/
function AxiosError(message, code, config, request, response) {
Error.call(this);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = (new Error()).stack;
}
this.message = message;
this.name = 'AxiosError';
code && (this.code = code);
config && (this.config = config);
request && (this.request = request);
response && (this.response = response);
}
utils.inherits(AxiosError, Error, {
toJSON: function toJSON() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: utils.toJSONObject(this.config),
code: this.code,
status: this.response && this.response.status ? this.response.status : null
};
}
});
const prototype$1 = AxiosError.prototype;
const descriptors = {};
[
'ERR_BAD_OPTION_VALUE',
'ERR_BAD_OPTION',
'ECONNABORTED',
'ETIMEDOUT',
'ERR_NETWORK',
'ERR_FR_TOO_MANY_REDIRECTS',
'ERR_DEPRECATED',
'ERR_BAD_RESPONSE',
'ERR_BAD_REQUEST',
'ERR_CANCELED',
'ERR_NOT_SUPPORT',
'ERR_INVALID_URL'
// eslint-disable-next-line func-names
].forEach(code => {
descriptors[code] = {value: code};
});
Object.defineProperties(AxiosError, descriptors);
Object.defineProperty(prototype$1, 'isAxiosError', {value: true});
// eslint-disable-next-line func-names
AxiosError.from = (error, code, config, request, response, customProps) => {
const axiosError = Object.create(prototype$1);
utils.toFlatObject(error, axiosError, function filter(obj) {
return obj !== Error.prototype;
}, prop => {
return prop !== 'isAxiosError';
});
AxiosError.call(axiosError, error.message, code, config, request, response);
axiosError.cause = error;
axiosError.name = error.name;
customProps && Object.assign(axiosError, customProps);
return axiosError;
};
// eslint-disable-next-line strict
var httpAdapter = null;
/**
* Determines if the given thing is a array or js object.
*
* @param {string} thing - The object or array to be visited.
*
* @returns {boolean}
*/
function isVisitable(thing) {
return utils.isPlainObject(thing) || utils.isArray(thing);
}
/**
* It removes the brackets from the end of a string
*
* @param {string} key - The key of the parameter.
*
* @returns {string} the key without the brackets.
*/
function removeBrackets(key) {
return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;
}
/**
* It takes a path, a key, and a boolean, and returns a string
*
* @param {string} path - The path to the current key.
* @param {string} key - The key of the current object being iterated over.
* @param {string} dots - If true, the key will be rendered with dots instead of brackets.
*
* @returns {string} The path to the current key.
*/
function renderKey(path, key, dots) {
if (!path) return key;
return path.concat(key).map(function each(token, i) {
// eslint-disable-next-line no-param-reassign
token = removeBrackets(token);
return !dots && i ? '[' + token + ']' : token;
}).join(dots ? '.' : '');
}
/**
* If the array is an array and none of its elements are visitable, then it's a flat array.
*
* @param {Array<any>} arr - The array to check
*
* @returns {boolean}
*/
function isFlatArray(arr) {
return utils.isArray(arr) && !arr.some(isVisitable);
}
const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {
return /^is[A-Z]/.test(prop);
});
/**
* Convert a data object to FormData
*
* @param {Object} obj
* @param {?Object} [formData]
* @param {?Object} [options]
* @param {Function} [options.visitor]
* @param {Boolean} [options.metaTokens = true]
* @param {Boolean} [options.dots = false]
* @param {?Boolean} [options.indexes = false]
*
* @returns {Object}
**/
/**
* It converts an object into a FormData object
*
* @param {Object<any, any>} obj - The object to convert to form data.
* @param {string} formData - The FormData object to append to.
* @param {Object<string, any>} options
*
* @returns
*/
function toFormData(obj, formData, options) {
if (!utils.isObject(obj)) {
throw new TypeError('target must be an object');
}
// eslint-disable-next-line no-param-reassign
formData = formData || new (FormData)();
// eslint-disable-next-line no-param-reassign
options = utils.toFlatObject(options, {
metaTokens: true,
dots: false,
indexes: false
}, false, function defined(option, source) {
// eslint-disable-next-line no-eq-null,eqeqeq
return !utils.isUndefined(source[option]);
});
const metaTokens = options.metaTokens;
// eslint-disable-next-line no-use-before-define
const visitor = options.visitor || defaultVisitor;
const dots = options.dots;
const indexes = options.indexes;
const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
const useBlob = _Blob && utils.isSpecCompliantForm(formData);
if (!utils.isFunction(visitor)) {
throw new TypeError('visitor must be a function');
}
function convertValue(value) {
if (value === null) return '';
if (utils.isDate(value)) {
return value.toISOString();
}
if (!useBlob && utils.isBlob(value)) {
throw new AxiosError('Blob is not supported. Use a Buffer instead.');
}
if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
}
return value;
}
/**
* Default visitor.
*
* @param {*} value
* @param {String|Number} key
* @param {Array<String|Number>} path
* @this {FormData}
*
* @returns {boolean} return true to visit the each prop of the value recursively
*/
function defaultVisitor(value, key, path) {
let arr = value;
if (value && !path && typeof value === 'object') {
if (utils.endsWith(key, '{}')) {
// eslint-disable-next-line no-param-reassign
key = metaTokens ? key : key.slice(0, -2);
// eslint-disable-next-line no-param-reassign
value = JSON.stringify(value);
} else if (
(utils.isArray(value) && isFlatArray(value)) ||
((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))
)) {
// eslint-disable-next-line no-param-reassign
key = removeBrackets(key);
arr.forEach(function each(el, index) {
!(utils.isUndefined(el) || el === null) && formData.append(
// eslint-disable-next-line no-nested-ternary
indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
convertValue(el)
);
});
return false;
}
}
if (isVisitable(value)) {
return true;
}
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
const stack = [];
const exposedHelpers = Object.assign(predicates, {
defaultVisitor,
convertValue,
isVisitable
});
function build(value, path) {
if (utils.isUndefined(value)) return;
if (stack.indexOf(value) !== -1) {
throw Error('Circular reference detected in ' + path.join('.'));
}
stack.push(value);
utils.forEach(value, function each(el, key) {
const result = !(utils.isUndefined(el) || el === null) && visitor.call(
formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers
);
if (result === true) {
build(el, path ? path.concat(key) : [key]);
}
});
stack.pop();
}
if (!utils.isObject(obj)) {
throw new TypeError('data must be an object');
}
build(obj);
return formData;
}
/**
* It encodes a string by replacing all characters that are not in the unreserved set with
* their percent-encoded equivalents
*
* @param {string} str - The string to encode.
*
* @returns {string} The encoded string.
*/
function encode$1(str) {
const charMap = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+',
'%00': '\x00'
};
return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
return charMap[match];
});
}
/**
* It takes a params object and converts it to a FormData object
*
* @param {Object<string, any>} params - The parameters to be converted to a FormData object.
* @param {Object<string, any>} options - The options object passed to the Axios constructor.
*
* @returns {void}
*/
function AxiosURLSearchParams(params, options) {
this._pairs = [];
params && toFormData(params, this, options);
}
const prototype = AxiosURLSearchParams.prototype;
prototype.append = function append(name, value) {
this._pairs.push([name, value]);
};
prototype.toString = function toString(encoder) {
const _encode = encoder ? function(value) {
return encoder.call(this, value, encode$1);
} : encode$1;
return this._pairs.map(function each(pair) {
return _encode(pair[0]) + '=' + _encode(pair[1]);
}, '').join('&');
};
/**
* It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
* URI encoded counterparts
*
* @param {string} val The value to be encoded.
*
* @returns {string} The encoded value.
*/
function encode(val) {
return encodeURIComponent(val).
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @param {?object} options
*
* @returns {string} The formatted url
*/
function buildURL(url, params, options) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
const _encode = options && options.encode || encode;
const serializeFn = options && options.serialize;
let serializedParams;
if (serializeFn) {
serializedParams = serializeFn(params, options);
} else {
serializedParams = utils.isURLSearchParams(params) ?
params.toString() :
new AxiosURLSearchParams(params, options).toString(_encode);
}
if (serializedParams) {
const hashmarkIndex = url.indexOf("#");
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
}
class InterceptorManager {
constructor() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled,
rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
}
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
*/
eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
clear() {
if (this.handlers) {
this.handlers = [];
}
}
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*
* @returns {void}
*/
forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
}
}
var transitionalDefaults = {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
};
var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
var FormData$1 = typeof FormData !== 'undefined' ? FormData : null;
var Blob$1 = typeof Blob !== 'undefined' ? Blob : null;
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*
* @returns {boolean}
*/
const isStandardBrowserEnv = (() => {
let product;
if (typeof navigator !== 'undefined' && (
(product = navigator.product) === 'ReactNative' ||
product === 'NativeScript' ||
product === 'NS')
) {
return false;
}
return typeof window !== 'undefined' && typeof document !== 'undefined';
})();
/**
* Determine if we're running in a standard browser webWorker environment
*
* Although the `isStandardBrowserEnv` method indicates that
* `allows axios to run in a web worker`, the WebWorker will still be
* filtered out due to its judgment standard
* `typeof window !== 'undefined' && typeof document !== 'undefined'`.
* This leads to a problem when axios post `FormData` in webWorker
*/
const isStandardBrowserWebWorkerEnv = (() => {
return (
typeof WorkerGlobalScope !== 'undefined' &&
// eslint-disable-next-line no-undef
self instanceof WorkerGlobalScope &&
typeof self.importScripts === 'function'
);
})();
var platform = {
isBrowser: true,
classes: {
URLSearchParams: URLSearchParams$1,
FormData: FormData$1,
Blob: Blob$1
},
isStandardBrowserEnv,
isStandardBrowserWebWorkerEnv,
protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
};
function toURLEncodedForm(data, options) {
return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
visitor: function(value, key, path, helpers) {
if (platform.isNode && utils.isBuffer(value)) {
this.append(key, value.toString('base64'));
return false;
}
return helpers.defaultVisitor.apply(this, arguments);
}
}, options));
}
/**
* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
*
* @param {string} name - The name of the property to get.
*
* @returns An array of strings.
*/
function parsePropPath(name) {
// foo[x][y][z]
// foo.x.y.z
// foo-x-y-z
// foo x y z
return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
return match[0] === '[]' ? '' : match[1] || match[0];
});
}
/**
* Convert an array to an object.
*
* @param {Array<any>} arr - The array to convert to an object.
*
* @returns An object with the same keys and values as the array.
*/
function arrayToObject(arr) {
const obj = {};
const keys = Object.keys(arr);
let i;
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
obj[key] = arr[key];
}
return obj;
}
/**
* It takes a FormData object and returns a JavaScript object
*
* @param {string} formData The FormData object to convert to JSON.
*
* @returns {Object<string, any> | null} The converted object.
*/
function formDataToJSON(formData) {
function buildPath(path, value, target, index) {
let name = path[index++];
const isNumericKey = Number.isFinite(+name);
const isLast = index >= path.length;
name = !name && utils.isArray(target) ? target.length : name;
if (isLast) {
if (utils.hasOwnProp(target, name)) {
target[name] = [target[name], value];
} else {
target[name] = value;
}
return !isNumericKey;
}
if (!target[name] || !utils.isObject(target[name])) {
target[name] = [];
}
const result = buildPath(path, value, target[name], index);
if (result && utils.isArray(target[name])) {
target[name] = arrayToObject(target[name]);
}
return !isNumericKey;
}
if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {
const obj = {};
utils.forEachEntry(formData, (name, value) => {
buildPath(parsePropPath(name), value, obj, 0);
});
return obj;
}
return null;
}
const DEFAULT_CONTENT_TYPE = {
'Content-Type': undefined
};
/**
* It takes a string, tries to parse it, and if it fails, it returns the stringified version
* of the input
*
* @param {any} rawValue - The value to be stringified.
* @param {Function} parser - A function that parses a string into a JavaScript object.
* @param {Function} encoder - A function that takes a value and returns a string.
*
* @returns {string} A stringified version of the rawValue.
*/
function stringifySafely(rawValue, parser, encoder) {
if (utils.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
const defaults$3 = {
transitional: transitionalDefaults,
adapter: ['xhr', 'http'],
transformRequest: [function transformRequest(data, headers) {
const contentType = headers.getContentType() || '';
const hasJSONContentType = contentType.indexOf('application/json') > -1;
const isObjectPayload = utils.isObject(data);
if (isObjectPayload && utils.isHTMLForm(data)) {
data = new FormData(data);
}
const isFormData = utils.isFormData(data);
if (isFormData) {
if (!hasJSONContentType) {
return data;
}
return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
}
if (utils.isArrayBuffer(data) ||
utils.isBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
return data.toString();
}
let isFileList;
if (isObjectPayload) {
if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
return toURLEncodedForm(data, this.formSerializer).toString();
}
if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
const _FormData = this.env && this.env.FormData;
return toFormData(
isFileList ? {'files[]': data} : data,
_FormData && new _FormData(),
this.formSerializer
);
}
}
if (isObjectPayload || hasJSONContentType ) {
headers.setContentType('application/json', false);
return stringifySafely(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
const transitional = this.transitional || defaults$3.transitional;
const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
const JSONRequested = this.responseType === 'json';
if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
const silentJSONParsing = transitional && transitional.silentJSONParsing;
const strictJSONParsing = !silentJSONParsing && JSONRequested;
try {
return JSON.parse(data);
} catch (e) {
if (strictJSONParsing) {
if (e.name === 'SyntaxError') {
throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
}
throw e;
}
}
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: {
FormData: platform.classes.FormData,
Blob: platform.classes.Blob
},
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
}
}
};
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
defaults$3.headers[method] = {};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
defaults$3.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});
var defaults$4 = defaults$3;
// RawAxiosHeaders whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
const ignoreDuplicateOf = utils.toObjectSet([
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
]);
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} rawHeaders Headers needing to be parsed
*
* @returns {Object} Headers parsed into an object
*/
var parseHeaders = rawHeaders => {
const parsed = {};
let key;
let val;
let i;
rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
i = line.indexOf(':');
key = line.substring(0, i).trim().toLowerCase();
val = line.substring(i + 1).trim();
if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
return;
}
if (key === 'set-cookie') {
if (parsed[key]) {
parsed[key].push(val);
} else {
parsed[key] = [val];
}
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
};
const $internals = Symbol('internals');
function normalizeHeader(header) {
return header && String(header).trim().toLowerCase();
}
function normalizeValue(value) {
if (value === false || value == null) {
return value;
}
return utils.isArray(value) ? value.map(normalizeValue) : String(value);
}
function parseTokens(str) {
const tokens = Object.create(null);
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
let match;
while ((match = tokensRE.exec(str))) {
tokens[match[1]] = match[2];
}
return tokens;
}
function isValidHeaderName(str) {
return /^[-_a-zA-Z]+$/.test(str.trim());
}
function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
if (utils.isFunction(filter)) {
return filter.call(this, value, header);
}
if (isHeaderNameFilter) {
value = header;
}
if (!utils.isString(value)) return;
if (utils.isString(filter)) {
return value.indexOf(filter) !== -1;
}
if (utils.isRegExp(filter)) {
return filter.test(value);
}
}
function formatHeader(header) {
return header.trim()
.toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
return char.toUpperCase() + str;
});
}
function buildAccessors(obj, header) {
const accessorName = utils.toCamelCase(' ' + header);
['get', 'set', 'has'].forEach(methodName => {
Object.defineProperty(obj, methodName + accessorName, {
value: function(arg1, arg2, arg3) {
return this[methodName].call(this, header, arg1, arg2, arg3);
},
configurable: true
});
});
}
class AxiosHeaders {
constructor(headers) {
headers && this.set(headers);
}
set(header, valueOrRewrite, rewrite) {
const self = this;
function setHeader(_value, _header, _rewrite) {
const lHeader = normalizeHeader(_header);
if (!lHeader) {
throw new Error('header name must be a non-empty string');
}
const key = utils.findKey(self, lHeader);
if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
self[key || _header] = normalizeValue(_value);
}
}
const setHeaders = (headers, _rewrite) =>
utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
if (utils.isPlainObject(header) || header instanceof this.constructor) {
setHeaders(header, valueOrRewrite);
} else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
setHeaders(parseHeaders(header), valueOrRewrite);
} else {
header != null && setHeader(valueOrRewrite, header, rewrite);
}
return this;
}
get(header, parser) {
header = normalizeHeader(header);
if (header) {
const key = utils.findKey(this, header);
if (key) {
const value = this[key];
if (!parser) {
return value;
}
if (parser === true) {
return parseTokens(value);
}
if (utils.isFunction(parser)) {
return parser.call(this, value, key);
}
if (utils.isRegExp(parser)) {
return parser.exec(value);
}
throw new TypeError('parser must be boolean|regexp|function');
}
}
}
has(header, matcher) {
header = normalizeHeader(header);
if (header) {
const key = utils.findKey(this, header);
return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
}
return false;
}
delete(header, matcher) {
const self = this;
let deleted = false;
function deleteHeader(_header) {
_header = normalizeHeader(_header);
if (_header) {
const key = utils.findKey(self, _header);
if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
delete self[key];
deleted = true;
}
}
}
if (utils.isArray(header)) {
header.forEach(deleteHeader);
} else {
deleteHeader(header);
}
return deleted;
}
clear(matcher) {
const keys = Object.keys(this);
let i = keys.length;
let deleted = false;
while (i--) {
const key = keys[i];
if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
delete this[key];
deleted = true;
}
}
return deleted;
}
normalize(format) {
const self = this;
const headers = {};
utils.forEach(this, (value, header) => {
const key = utils.findKey(headers, header);
if (key) {
self[key] = normalizeValue(value);
delete self[header];
return;
}
const normalized = format ? formatHeader(header) : String(header).trim();
if (normalized !== header) {
delete self[header];
}
self[normalized] = normalizeValue(value);
headers[normalized] = true;
});
return this;
}
concat(...targets) {
return this.constructor.concat(this, ...targets);
}
toJSON(asStrings) {
const obj = Object.create(null);
utils.forEach(this, (value, header) => {
value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);
});
return obj;
}
[Symbol.iterator]() {
return Object.entries(this.toJSON())[Symbol.iterator]();
}
toString() {
return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
}
get [Symbol.toStringTag]() {
return 'AxiosHeaders';
}
static from(thing) {
return thing instanceof this ? thing : new this(thing);
}
static concat(first, ...targets) {
const computed = new this(first);
targets.forEach((target) => computed.set(target));
return computed;
}
static accessor(header) {
const internals = this[$internals] = (this[$internals] = {
accessors: {}
});
const accessors = internals.accessors;
const prototype = this.prototype;
function defineAccessor(_header) {
const lHeader = normalizeHeader(_header);
if (!accessors[lHeader]) {
buildAccessors(prototype, _header);
accessors[lHeader] = true;
}
}
utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
return this;
}
}
AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
utils.freezeMethods(AxiosHeaders.prototype);
utils.freezeMethods(AxiosHeaders);
var AxiosHeaders$1 = AxiosHeaders;
/**
* Transform the data for a request or a response
*
* @param {Array|Function} fns A single function or Array of functions
* @param {?Object} response The response object
*
* @returns {*} The resulting transformed data
*/
function transformData(fns, response) {
const config = this || defaults$4;
const context = response || config;
const headers = AxiosHeaders$1.from(context.headers);
let data = context.data;
utils.forEach(fns, function transform(fn) {
data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
});
headers.normalize();
return data;
}
function isCancel(value) {
return !!(value && value.__CANCEL__);
}
/**
* A `CanceledError` is an object that is thrown when an operation is canceled.
*
* @param {string=} message The message.
* @param {Object=} config The config.
* @param {Object=} request The request.
*
* @returns {CanceledError} The created error.
*/
function CanceledError(message, config, request) {
// eslint-disable-next-line no-eq-null,eqeqeq
AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
this.name = 'CanceledError';
}
utils.inherits(CanceledError, AxiosError, {
__CANCEL__: true
});
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*
* @returns {object} The response.
*/
function settle(resolve, reject, response) {
const validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(new AxiosError(
'Request failed with status code ' + response.status,
[AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
response.config,
response.request,
response
));
}
}
var cookies = platform.isStandardBrowserEnv ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
const cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})();
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
*
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
*
* @returns {string} The combined URL
*/
function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
}
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
*
* @returns {string} The combined full path
*/
function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
}
var isURLSameOrigin = platform.isStandardBrowserEnv ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
const msie = /(msie|trident)/i.test(navigator.userAgent);
const urlParsingNode = document.createElement('a');
let originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
let href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})();
function parseProtocol(url) {
const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
return match && match[1] || '';
}
/**
* Calculate data maxRate
* @param {Number} [samplesCount= 10]
* @param {Number} [min= 1000]
* @returns {Function}
*/
function speedometer(samplesCount, min) {
samplesCount = samplesCount || 10;
const bytes = new Array(samplesCount);
const timestamps = new Array(samplesCount);
let head = 0;
let tail = 0;
let firstSampleTS;
min = min !== undefined ? min : 1000;
return function push(chunkLength) {
const now = Date.now();
const startedAt = timestamps[tail];
if (!firstSampleTS) {
firstSampleTS = now;
}
bytes[head] = chunkLength;
timestamps[head] = now;
let i = tail;
let bytesCount = 0;
while (i !== head) {
bytesCount += bytes[i++];
i = i % samplesCount;
}
head = (head + 1) % samplesCount;
if (head === tail) {
tail = (tail + 1) % samplesCount;
}
if (now - firstSampleTS < min) {
return;
}
const passed = startedAt && now - startedAt;
return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
};
}
function progressEventReducer(listener, isDownloadStream) {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);
return e => {
const loaded = e.loaded;
const total = e.lengthComputable ? e.total : undefined;
const progressBytes = loaded - bytesNotified;
const rate = _speedometer(progressBytes);
const inRange = loaded <= total;
bytesNotified = loaded;
const data = {
loaded,
total,
progress: total ? (loaded / total) : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
event: e
};
data[isDownloadStream ? 'download' : 'upload'] = true;
listener(data);
};
}
const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
var xhrAdapter = isXHRAdapterSupported && function (config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
let requestData = config.data;
const requestHeaders = AxiosHeaders$1.from(config.headers).normalize();
const responseType = config.responseType;
let onCanceled;
function done() {
if (config.cancelToken) {
config.cancelToken.unsubscribe(onCanceled);
}
if (config.signal) {
config.signal.removeEventListener('abort', onCanceled);
}
}
if (utils.isFormData(requestData) && (platform.isStandardBrowserEnv || platform.isStandardBrowserWebWorkerEnv)) {
requestHeaders.setContentType(false); // Let the browser set it
}
let request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
const username = config.auth.username || '';
const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password));
}
const fullPath = buildFullPath(config.baseURL, config.url);
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
function onloadend() {
if (!request) {
return;
}
// Prepare the response
const responseHeaders = AxiosHeaders$1.from(
'getAllResponseHeaders' in request && request.getAllResponseHeaders()
);
const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
request.responseText : request.response;
const response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config,
request
};
settle(function _resolve(value) {
resolve(value);
done();
}, function _reject(err) {
reject(err);
done();
}, response);
// Clean up request
request = null;
}
if ('onloadend' in request) {
// Use onloadend if available
request.onloadend = onloadend;
} else {
// Listen for ready state to emulate onloadend
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// readystate handler is calling before onerror or ontimeout handlers,
// so we should call onloadend on the next 'tick'
setTimeout(onloadend);
};
}
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
const transitional = config.transitional || transitionalDefaults;
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(new AxiosError(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
config,
request));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (platform.isStandardBrowserEnv) {
// Add xsrf header
const xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath))
&& config.xsrfCookieName && cookies.read(config.xsrfCookieName);
if (xsrfValue) {
requestHeaders.set(config.xsrfHeaderName, xsrfValue);
}
}
// Remove Content-Type if data is undefined
requestData === undefined && requestHeaders.setContentType(null);
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
request.setRequestHeader(key, val);
});
}
// Add withCredentials to request if needed
if (!utils.isUndefined(config.withCredentials)) {
request.withCredentials = !!config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = config.responseType;
}
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true));
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress));
}
if (config.cancelToken || config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = cancel => {
if (!request) {
return;
}
reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
request.abort();
request = null;
};
config.cancelToken && config.cancelToken.subscribe(onCanceled);
if (config.signal) {
config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
}
}
const protocol = parseProtocol(fullPath);
if (protocol && platform.protocols.indexOf(protocol) === -1) {
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
return;
}
// Send the request
request.send(requestData || null);
});
};
const knownAdapters = {
http: httpAdapter,
xhr: xhrAdapter
};
utils.forEach(knownAdapters, (fn, value) => {
if(fn) {
try {
Object.defineProperty(fn, 'name', {value});
} catch (e) {
// eslint-disable-next-line no-empty
}
Object.defineProperty(fn, 'adapterName', {value});
}
});
var adapters = {
getAdapter: (adapters) => {
adapters = utils.isArray(adapters) ? adapters : [adapters];
const {length} = adapters;
let nameOrAdapter;
let adapter;
for (let i = 0; i < length; i++) {
nameOrAdapter = adapters[i];
if((adapter = utils.isString(nameOrAdapter) ? knownAdapters[nameOrAdapter.toLowerCase()] : nameOrAdapter)) {
break;
}
}
if (!adapter) {
if (adapter === false) {
throw new AxiosError(
`Adapter ${nameOrAdapter} is not supported by the environment`,
'ERR_NOT_SUPPORT'
);
}
throw new Error(
utils.hasOwnProp(knownAdapters, nameOrAdapter) ?
`Adapter '${nameOrAdapter}' is not available in the build` :
`Unknown adapter '${nameOrAdapter}'`
);
}
if (!utils.isFunction(adapter)) {
throw new TypeError('adapter is not a function');
}
return adapter;
},
adapters: knownAdapters
};
/**
* Throws a `CanceledError` if cancellation has been requested.
*
* @param {Object} config The config that is to be used for the request
*
* @returns {void}
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new CanceledError(null, config);
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
*
* @returns {Promise} The Promise to be fulfilled
*/
function dispatchRequest(config) {
throwIfCancellationRequested(config);
config.headers = AxiosHeaders$1.from(config.headers);
// Transform request data
config.data = transformData.call(
config,
config.transformRequest
);
if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
config.headers.setContentType('application/x-www-form-urlencoded', false);
}
const adapter = adapters.getAdapter(config.adapter || defaults$4.adapter);
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData.call(
config,
config.transformResponse,
response
);
response.headers = AxiosHeaders$1.from(response.headers);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
config.transformResponse,
reason.response
);
reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
}
}
return Promise.reject(reason);
});
}
const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? thing.toJSON() : thing;
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
*
* @returns {Object} New object resulting from merging config2 to config1
*/
function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
const config = {};
function getMergedValue(target, source, caseless) {
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
return utils.merge.call({caseless}, target, source);
} else if (utils.isPlainObject(source)) {
return utils.merge({}, source);
} else if (utils.isArray(source)) {
return source.slice();
}
return source;
}
// eslint-disable-next-line consistent-return
function mergeDeepProperties(a, b, caseless) {
if (!utils.isUndefined(b)) {
return getMergedValue(a, b, caseless);
} else if (!utils.isUndefined(a)) {
return getMergedValue(undefined, a, caseless);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(a, b) {
if (!utils.isUndefined(b)) {
return getMergedValue(undefined, b);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(a, b) {
if (!utils.isUndefined(b)) {
return getMergedValue(undefined, b);
} else if (!utils.isUndefined(a)) {
return getMergedValue(undefined, a);
}
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(a, b, prop) {
if (prop in config2) {
return getMergedValue(a, b);
} else if (prop in config1) {
return getMergedValue(undefined, a);
}
}
const mergeMap = {
url: valueFromConfig2,
method: valueFromConfig2,
data: valueFromConfig2,
baseURL: defaultToConfig2,
transformRequest: defaultToConfig2,
transformResponse: defaultToConfig2,
paramsSerializer: defaultToConfig2,
timeout: defaultToConfig2,
timeoutMessage: defaultToConfig2,
withCredentials: defaultToConfig2,
adapter: defaultToConfig2,
responseType: defaultToConfig2,
xsrfCookieName: defaultToConfig2,
xsrfHeaderName: defaultToConfig2,
onUploadProgress: defaultToConfig2,
onDownloadProgress: defaultToConfig2,
decompress: defaultToConfig2,
maxContentLength: defaultToConfig2,
maxBodyLength: defaultToConfig2,
beforeRedirect: defaultToConfig2,
transport: defaultToConfig2,
httpAgent: defaultToConfig2,
httpsAgent: defaultToConfig2,
cancelToken: defaultToConfig2,
socketPath: defaultToConfig2,
responseEncoding: defaultToConfig2,
validateStatus: mergeDirectKeys,
headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)
};
utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
const merge = mergeMap[prop] || mergeDeepProperties;
const configValue = merge(config1[prop], config2[prop], prop);
(utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
return config;
}
const VERSION = "1.3.4";
const validators$1 = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
validators$1[type] = function validator(thing) {
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
const deprecatedWarnings = {};
/**
* Transitional option validator
*
* @param {function|boolean?} validator - set to false if the transitional option has been removed
* @param {string?} version - deprecated version / removed since version
* @param {string?} message - some message with additional info
*
* @returns {function}
*/
validators$1.transitional = function transitional(validator, version, message) {
function formatMessage(opt, desc) {
return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
}
// eslint-disable-next-line func-names
return (value, opt, opts) => {
if (validator === false) {
throw new AxiosError(
formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
AxiosError.ERR_DEPRECATED
);
}
if (version && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
// eslint-disable-next-line no-console
console.warn(
formatMessage(
opt,
' has been deprecated since v' + version + ' and will be removed in the near future'
)
);
}
return validator ? validator(value, opt, opts) : true;
};
};
/**
* Assert object's properties type
*
* @param {object} options
* @param {object} schema
* @param {boolean?} allowUnknown
*
* @returns {object}
*/
function assertOptions(options, schema, allowUnknown) {
if (typeof options !== 'object') {
throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
}
const keys = Object.keys(options);
let i = keys.length;
while (i-- > 0) {
const opt = keys[i];
const validator = schema[opt];
if (validator) {
const value = options[opt];
const result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
}
continue;
}
if (allowUnknown !== true) {
throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
}
}
}
var validator = {
assertOptions,
validators: validators$1
};
const validators = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*
* @return {Axios} A new instance of Axios
*/
class Axios {
constructor(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
* @param {?Object} config
*
* @returns {Promise} The Promise to be fulfilled
*/
request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
config = mergeConfig(this.defaults, config);
const {transitional, paramsSerializer, headers} = config;
if (transitional !== undefined) {
validator.assertOptions(transitional, {
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean)
}, false);
}
if (paramsSerializer !== undefined) {
validator.assertOptions(paramsSerializer, {
encode: validators.function,
serialize: validators.function
}, true);
}
// Set config.method
config.method = (config.method || this.defaults.method || 'get').toLowerCase();
let contextHeaders;
// Flatten headers
contextHeaders = headers && utils.merge(
headers.common,
headers[config.method]
);
contextHeaders && utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
(method) => {
delete headers[method];
}
);
config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
// filter out skipped interceptors
const requestInterceptorChain = [];
let synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
const responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
let promise;
let i = 0;
let len;
if (!synchronousRequestInterceptors) {
const chain = [dispatchRequest.bind(this), undefined];
chain.unshift.apply(chain, requestInterceptorChain);
chain.push.apply(chain, responseInterceptorChain);
len = chain.length;
promise = Promise.resolve(config);
while (i < len) {
promise = promise.then(chain[i++], chain[i++]);
}
return promise;
}
len = requestInterceptorChain.length;
let newConfig = config;
i = 0;
while (i < len) {
const onFulfilled = requestInterceptorChain[i++];
const onRejected = requestInterceptorChain[i++];
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected.call(this, error);
break;
}
}
try {
promise = dispatchRequest.call(this, newConfig);
} catch (error) {
return Promise.reject(error);
}
i = 0;
len = responseInterceptorChain.length;
while (i < len) {
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
}
return promise;
}
getUri(config) {
config = mergeConfig(this.defaults, config);
const fullPath = buildFullPath(config.baseURL, config.url);
return buildURL(fullPath, config.params, config.paramsSerializer);
}
}
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(mergeConfig(config || {}, {
method,
url,
data: (config || {}).data
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
function generateHTTPMethod(isForm) {
return function httpMethod(url, data, config) {
return this.request(mergeConfig(config || {}, {
method,
headers: isForm ? {
'Content-Type': 'multipart/form-data'
} : {},
url,
data
}));
};
}
Axios.prototype[method] = generateHTTPMethod();
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
});
var Axios$1 = Axios;
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @param {Function} executor The executor function.
*
* @returns {CancelToken}
*/
class CancelToken {
constructor(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
let resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
const token = this;
// eslint-disable-next-line func-names
this.promise.then(cancel => {
if (!token._listeners) return;
let i = token._listeners.length;
while (i-- > 0) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = onfulfilled => {
let _resolve;
// eslint-disable-next-line func-names
const promise = new Promise(resolve => {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message, config, request) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new CanceledError(message, config, request);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
throwIfRequested() {
if (this.reason) {
throw this.reason;
}
}
/**
* Subscribe to the cancel signal
*/
subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
}
/**
* Unsubscribe from the cancel signal
*/
unsubscribe(listener) {
if (!this._listeners) {
return;
}
const index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
}
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
static source() {
let cancel;
const token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token,
cancel
};
}
}
var CancelToken$1 = CancelToken;
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
*
* @returns {Function}
*/
function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
}
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
*
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
function isAxiosError(payload) {
return utils.isObject(payload) && (payload.isAxiosError === true);
}
const HttpStatusCode = {
Continue: 100,
SwitchingProtocols: 101,
Processing: 102,
EarlyHints: 103,
Ok: 200,
Created: 201,
Accepted: 202,
NonAuthoritativeInformation: 203,
NoContent: 204,
ResetContent: 205,
PartialContent: 206,
MultiStatus: 207,
AlreadyReported: 208,
ImUsed: 226,
MultipleChoices: 300,
MovedPermanently: 301,
Found: 302,
SeeOther: 303,
NotModified: 304,
UseProxy: 305,
Unused: 306,
TemporaryRedirect: 307,
PermanentRedirect: 308,
BadRequest: 400,
Unauthorized: 401,
PaymentRequired: 402,
Forbidden: 403,
NotFound: 404,
MethodNotAllowed: 405,
NotAcceptable: 406,
ProxyAuthenticationRequired: 407,
RequestTimeout: 408,
Conflict: 409,
Gone: 410,
LengthRequired: 411,
PreconditionFailed: 412,
PayloadTooLarge: 413,
UriTooLong: 414,
UnsupportedMediaType: 415,
RangeNotSatisfiable: 416,
ExpectationFailed: 417,
ImATeapot: 418,
MisdirectedRequest: 421,
UnprocessableEntity: 422,
Locked: 423,
FailedDependency: 424,
TooEarly: 425,
UpgradeRequired: 426,
PreconditionRequired: 428,
TooManyRequests: 429,
RequestHeaderFieldsTooLarge: 431,
UnavailableForLegalReasons: 451,
InternalServerError: 500,
NotImplemented: 501,
BadGateway: 502,
ServiceUnavailable: 503,
GatewayTimeout: 504,
HttpVersionNotSupported: 505,
VariantAlsoNegotiates: 506,
InsufficientStorage: 507,
LoopDetected: 508,
NotExtended: 510,
NetworkAuthenticationRequired: 511,
};
Object.entries(HttpStatusCode).forEach(([key, value]) => {
HttpStatusCode[value] = key;
});
var HttpStatusCode$1 = HttpStatusCode;
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
*
* @returns {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
const context = new Axios$1(defaultConfig);
const instance = bind(Axios$1.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios$1.prototype, context, {allOwnKeys: true});
// Copy context to instance
utils.extend(instance, context, null, {allOwnKeys: true});
// Factory for creating new instances
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig(defaultConfig, instanceConfig));
};
return instance;
}
// Create the default instance to be exported
const axios = createInstance(defaults$4);
// Expose Axios class to allow class inheritance
axios.Axios = Axios$1;
// Expose Cancel & CancelToken
axios.CanceledError = CanceledError;
axios.CancelToken = CancelToken$1;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData;
// Expose AxiosError class
axios.AxiosError = AxiosError;
// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = spread;
// Expose isAxiosError
axios.isAxiosError = isAxiosError;
// Expose mergeConfig
axios.mergeConfig = mergeConfig;
axios.AxiosHeaders = AxiosHeaders$1;
axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
axios.HttpStatusCode = HttpStatusCode$1;
axios.default = axios;
let globalAny$1 = {};
try {
globalAny$1 = window;
} catch (error) {
if (!(error instanceof ReferenceError)) {
throw error;
} else {
globalAny$1 = {
isOnServer: true
};
}
} finally {
if (!globalAny$1) {
globalAny$1 = {
isOnServer: true
};
}
}
/**
* Type of an [axios request]{@link https://github.com/axios/axios/blob/master/index.d.ts#L43}
*
* @typedef {object} AxiosRequestConfig
* @alias AxiosRequestConfig
* @memberof ApiClient
* @see https://github.com/axios/axios/blob/master/index.d.ts#L43
*/
const checkResponse = response => {
if (globalAny$1.isOnServer) {
return;
}
const loginUrl = [globalAny$1.location.origin, globalAny$1.REDUX_STATE.paths.loginPath].join('');
// if response has redirect to loginUrl
if (response.request.responseURL && response.request.responseURL.match(loginUrl)) {
// eslint-disable-next-line no-undef, no-alert
alert('Your session expired. You will be redirected to login screen');
globalAny$1.location.assign(loginUrl);
}
};
/**
* Extends {@link AxiosRequestConfig}
*
* @alias ActionAPIParams
* @memberof ApiClient
* @property {any} ... any property supported by {@link AxiosRequestConfig}
*/
/**
* Extends {@link ActionAPIParams}
*
* @alias ResourceActionAPIParams
* @memberof ApiClient
* @property {any} ... any property supported by {@link AxiosRequestConfig}
*/
/**
* Extends {@link ActionAPIParams}
*
* @alias RecordActionAPIParams
* @memberof ApiClient
* @property {any} ... any property supported by {@link ActionAPIParams}
*/
/**
* Extends {@link ActionAPIParams}
*
* @alias BulkActionAPIParams
* @memberof ApiClient
* @see https://github.com/axios/axios/blob/master/index.d.ts#L43
* @property {any} ... any property supported by {@link ActionAPIParams}
*/
/**
* Extends {@link AxiosRequestConfig}
*
* @alias GetPageAPIParams
* @memberof ApiClient
* @property {any} ... any property supported by {@link AxiosRequestConfig}
*/
/**
* Client which access the admin API.
* Use it to fetch data from auto generated AdminJS API.
*
* In the backend it uses [axios](https://github.com/axios/axios) client
* library.
*
* Usage:
* ```javascript
* import { ApiClient } from 'adminjs'
*
* const api = new ApiClient()
* // fetching all records
* api.resourceAction({ resourceId: 'Comments', actionName: 'list' }).then(results => {...})
* ```
* @see https://github.com/axios/axios
* @hideconstructor
*/
class ApiClient {
constructor() {
this.baseURL = ApiClient.getBaseUrl();
this.client = axios.create({
baseURL: this.baseURL
});
}
static getBaseUrl() {
if (globalAny$1.isOnServer) {
return '';
}
return [globalAny$1.location.origin, globalAny$1.REDUX_STATE?.paths.rootPath].join('');
}
/**
* Search by query string for records in a given resource.
*
* @param {Object} options
* @param {String} options.resourceId id of a {@link ResourceJSON}
* @param {String} options.query query string
* @param {String} options.searchProperty optional property name
*
* @return {Promise<SearchResponse>}
*/
async searchRecords({
resourceId,
query,
searchProperty
}) {
if (globalAny$1.isOnServer) {
return [];
}
const actionName = 'search';
const response = await this.resourceAction({
resourceId,
actionName,
query,
...(searchProperty ? {
params: {
searchProperty
}
} : undefined)
});
checkResponse(response);
return response.data.records;
}
/**
* Invokes given resource {@link Action} on the backend.
*
* @param {ResourceActionAPIParams} options
* @return {Promise<ActionResponse>} response from an {@link Action}
*/
async resourceAction(options) {
const {
resourceId,
actionName,
data,
query,
...axiosParams
} = options;
let url = `/api/resources/${resourceId}/actions/${actionName}`;
if (query) {
const q = encodeURIComponent(query);
url = [url, q].join('/');
}
const response = await this.client.request({
url,
method: data ? 'POST' : 'GET',
...axiosParams,
data
});
checkResponse(response);
return response;
}
/**
* Invokes given record {@link Action} on the backend.
*
* @param {RecordActionAPIParams} options
* @return {Promise<RecordActionResponse>} response from an {@link Action}
*/
async recordAction(options) {
const {
resourceId,
recordId,
actionName,
data,
...axiosParams
} = options;
const response = await this.client.request({
url: `/api/resources/${resourceId}/records/${recordId}/${actionName}`,
method: data ? 'POST' : 'GET',
...axiosParams,
data
});
checkResponse(response);
return response;
}
/**
* Invokes given bulk {@link Action} on the backend.
*
* @param {BulkActionAPIParams} options
* @return {Promise<BulkActionResponse>} response from an {@link Action}
*/
async bulkAction(options) {
const {
resourceId,
recordIds,
actionName,
data,
...axiosParams
} = options;
const params = new URLSearchParams();
params.set('recordIds', (recordIds || []).join(','));
const response = await this.client.request({
url: `/api/resources/${resourceId}/bulk/${actionName}`,
method: data ? 'POST' : 'GET',
...axiosParams,
data,
params
});
checkResponse(response);
return response;
}
/**
* Invokes dashboard handler.
*
* @param {AxiosRequestConfig} options
* @return {Promise<AxiosResponse<any>>} response from the handler function defined in
* {@link AdminJSOptions#dashboard}
*/
async getDashboard(options = {}) {
const response = await this.client.get('/api/dashboard', options);
checkResponse(response);
return response;
}
/**
* Invokes handler function of given page and returns its response.
*
* @param {GetPageAPIParams} options
* @return {Promise<AxiosResponse<any>>} response from the handler of given page
* defined in {@link AdminJSOptions#pages}
*/
async getPage(options) {
const {
pageName,
...axiosParams
} = options;
const response = await this.client.request({
url: `/api/pages/${pageName}`,
...axiosParams
});
checkResponse(response);
return response;
}
async refreshToken(data) {
const response = await this.client.request({
url: '/refresh-token',
method: 'POST',
data
});
checkResponse(response);
return response;
}
}
/* eslint-disable max-len */
const getDataCss = (...args) => args.join('-');
const getResourceElementCss = (resourceId, suffix) => getDataCss(resourceId, suffix);
const getActionElementCss = (resourceId, actionName, suffix) => getDataCss(resourceId, actionName, suffix);
const api$4 = new ApiClient();
function callActionApi(action, params, search) {
let promise;
const {
recordId,
recordIds,
resourceId
} = params;
/* Temporary workaround to avoid breaking changes.
TODO: For v8 release, rewrite actions to support PUT & DELETE methods.
Actions should have an option to configure a default method for action buttons. */
let method = 'get';
if (action.name === 'delete') {
method = 'post';
}
switch (action.actionType) {
case 'record':
if (!recordId) {
throw new Error('You have to specify "recordId" for record action');
}
promise = api$4.recordAction({
resourceId,
actionName: action.name,
recordId,
search,
method
});
break;
case 'resource':
promise = api$4.resourceAction({
resourceId,
actionName: action.name,
method
});
break;
case 'bulk':
if (!recordIds) {
throw new Error('You have to specify "recordIds" for bulk action');
}
promise = api$4.bulkAction({
resourceId,
actionName: action.name,
recordIds,
search,
method
});
break;
default:
throw new Error('"actionType" should be either record, resource or bulk');
}
return promise;
}
/* eslint-disable arrow-parens */
const buildActionCallApiTrigger = options => {
const {
action,
params,
actionResponseHandler,
search
} = options;
const callApi = () => {
const promise = callActionApi(action, params, search);
promise.then(actionResponseHandler).catch(error => {
throw error;
});
return promise;
};
return callApi;
};
const buildActionTestId = action => `action-${action.name}`;
const REFRESH_KEY = 'refresh';
const IGNORE_PARAMS_KEY = 'ignore_params';
/**
* Adds refresh=true to the url, which in turn should cause list to reload.
*
* @param {string} url url to which function should add `refresh`
* @param {string} [search] optional search query which should be updated,
* if not given function will use window.location.search
* @private
*/
const appendForceRefresh = (url, search) => {
const searchParamsIdx = url.lastIndexOf('?');
const urlSearchParams = searchParamsIdx !== -1 ? url.substring(searchParamsIdx + 1) : null;
const oldParams = new URLSearchParams(search ?? urlSearchParams ?? window.location.search ?? '');
const shouldIgnoreOldParams = new URLSearchParams(urlSearchParams || '').get(IGNORE_PARAMS_KEY) === 'true';
const newParams = shouldIgnoreOldParams ? new URLSearchParams('') : new URLSearchParams(oldParams.toString());
newParams.set(REFRESH_KEY, 'true');
const newUrl = searchParamsIdx !== -1 ? url.substring(0, searchParamsIdx) : url;
return `${newUrl}?${newParams.toString()}`;
};
const hasForceRefresh = search => {
const params = new URLSearchParams(search);
return !!params.get(REFRESH_KEY);
};
const removeForceRefresh = search => {
const params = new URLSearchParams(search);
if (params.get(REFRESH_KEY)) {
params.delete(REFRESH_KEY);
}
return params.toString();
};
/* eslint-disable no-restricted-globals */
/* eslint-disable no-undef */
/* eslint-disable no-alert */
const buildActionClickHandler = options => {
const {
action,
params,
actionResponseHandler,
navigate,
modalFunctions,
location
} = options;
const {
openModal
} = modalFunctions;
const handleActionClick = event => {
event.preventDefault();
event.stopPropagation();
const href = actionHref(action, params);
const callApi = buildActionCallApiTrigger({
params,
action,
actionResponseHandler
});
// Action has "component" option set to "false" explicitly in it's configuration
if (actionHasDisabledComponent(action)) {
if (action.guard) {
const modalData = {
modalProps: {
variant: 'danger',
label: 'confirm',
title: action.guard,
subTitle: ''
},
type: 'confirm',
resourceId: params.resourceId,
confirmAction: callApi
};
// If confirmation is required, action trigger should be handled in modal
openModal(modalData);
return;
}
// If no confirmation is required, call API
callApi();
return;
}
// Default behaviour - you're navigated to action URL and logic is performed on it's route
if (href) {
const url = new URL(`relative:${href}`);
const hrefParams = new URLSearchParams(url.search);
const currentParams = new URLSearchParams(action.showInDrawer ? location?.search ?? '' : '');
Object.entries(Object.fromEntries(currentParams.entries())).forEach(([key, value]) => {
if (!hrefParams.has(key)) hrefParams.set(key, value);
});
if (location?.pathname === url.pathname) {
hrefParams.set(REFRESH_KEY, 'true');
}
navigate({
pathname: url.pathname,
search: hrefParams.toString()
});
}
};
return handleActionClick;
};
const isBulkAction = (params, action) => 'recordIds' in params && action.actionType === 'bulk';
const isResourceAction = (params, action) => 'recordIds' in params && action.actionType === 'resource';
const isRecordAction = (params, action) => 'recordId' in params && action.actionType === 'record';
var ActionUtils = /*#__PURE__*/Object.freeze({
__proto__: null,
actionHasCustomComponent: actionHasCustomComponent,
actionHasDisabledComponent: actionHasDisabledComponent,
actionHref: actionHref,
buildActionCallApiTrigger: buildActionCallApiTrigger,
buildActionClickHandler: buildActionClickHandler,
buildActionTestId: buildActionTestId,
callActionApi: callActionApi,
isBulkAction: isBulkAction,
isRecordAction: isRecordAction,
isResourceAction: isResourceAction
});
const ADD_NOTICE = 'ADD_NOTICE';
const addNotice = data => ({
type: ADD_NOTICE,
data: {
id: `notice-${Date.now() + Math.random()}`,
progress: 0,
...data
}
});
/**
* @memberof useNotice
* @alias AddNotice
*/
/**
* @classdesc
* Hook which allows you to add notice message to the app.
*
* ```javascript
* import { useNotice, Button } from 'adminjs'
*
* const myComponent = () => {
* const sendNotice = useNotice()
* return (
* <Button onClick={() => sendNotice({ message: 'I am awesome' })}>I am awesome</Button>
* )
* }
* ```
*
* @class
* @subcategory Hooks
* @bundle
* @hideconstructor
*/
const useNotice = () => {
const dispatch = require$$3.useDispatch();
return notice => dispatch(addNotice(notice));
};
/* eslint-disable @typescript-eslint/explicit-function-return-type */
const useActionResponseHandler = onActionCall => {
const location = reactRouter.useLocation();
const navigate = reactRouter.useNavigate();
const addNotice = useNotice();
return response => {
const {
data
} = response;
if (data.notice) {
addNotice(data.notice);
}
if (data.redirectUrl && location.pathname !== data.redirectUrl) {
const appended = appendForceRefresh(data.redirectUrl);
navigate(appended);
}
if (onActionCall) {
onActionCall(data);
}
};
};
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce$1(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
var _arrayReduce = arrayReduce$1;
/**
* The base implementation of `_.propertyOf` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyOf$1(object) {
return function(key) {
return object == null ? undefined : object[key];
};
}
var _basePropertyOf = basePropertyOf$1;
var basePropertyOf = _basePropertyOf;
/** Used to map Latin Unicode letters to basic Latin letters. */
var deburredLetters = {
// Latin-1 Supplement block.
'\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
'\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
'\xc7': 'C', '\xe7': 'c',
'\xd0': 'D', '\xf0': 'd',
'\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
'\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
'\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
'\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
'\xd1': 'N', '\xf1': 'n',
'\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
'\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
'\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
'\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
'\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
'\xc6': 'Ae', '\xe6': 'ae',
'\xde': 'Th', '\xfe': 'th',
'\xdf': 'ss',
// Latin Extended-A block.
'\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
'\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
'\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
'\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
'\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
'\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
'\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
'\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
'\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
'\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
'\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
'\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
'\u0134': 'J', '\u0135': 'j',
'\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
'\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
'\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
'\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
'\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
'\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
'\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
'\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
'\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
'\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
'\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
'\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
'\u0163': 't', '\u0165': 't', '\u0167': 't',
'\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
'\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
'\u0174': 'W', '\u0175': 'w',
'\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
'\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
'\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
'\u0132': 'IJ', '\u0133': 'ij',
'\u0152': 'Oe', '\u0153': 'oe',
'\u0149': "'n", '\u017f': 's'
};
/**
* Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
* letters to basic Latin letters.
*
* @private
* @param {string} letter The matched letter to deburr.
* @returns {string} Returns the deburred letter.
*/
var deburrLetter$1 = basePropertyOf(deburredLetters);
var _deburrLetter = deburrLetter$1;
/** Detect free variable `global` from Node.js. */
var freeGlobal$1 = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
var _freeGlobal = freeGlobal$1;
var freeGlobal = _freeGlobal;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root$8 = freeGlobal || freeSelf || Function('return this')();
var _root = root$8;
var root$7 = _root;
/** Built-in value references. */
var Symbol$6 = root$7.Symbol;
var _Symbol = Symbol$6;
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap$4(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
var _arrayMap = arrayMap$4;
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray$a = Array.isArray;
var isArray_1 = isArray$a;
var Symbol$5 = _Symbol;
/** Used for built-in method references. */
var objectProto$e = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$b = objectProto$e.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString$1 = objectProto$e.toString;
/** Built-in value references. */
var symToStringTag$1 = Symbol$5 ? Symbol$5.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag$1(value) {
var isOwn = hasOwnProperty$b.call(value, symToStringTag$1),
tag = value[symToStringTag$1];
try {
value[symToStringTag$1] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString$1.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag$1] = tag;
} else {
delete value[symToStringTag$1];
}
}
return result;
}
var _getRawTag = getRawTag$1;
/** Used for built-in method references. */
var objectProto$d = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto$d.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString$1(value) {
return nativeObjectToString.call(value);
}
var _objectToString = objectToString$1;
var Symbol$4 = _Symbol,
getRawTag = _getRawTag,
objectToString = _objectToString;
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag = Symbol$4 ? Symbol$4.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag$7(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
var _baseGetTag = baseGetTag$7;
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike$8(value) {
return value != null && typeof value == 'object';
}
var isObjectLike_1 = isObjectLike$8;
var baseGetTag$6 = _baseGetTag,
isObjectLike$7 = isObjectLike_1;
/** `Object#toString` result references. */
var symbolTag$1 = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol$4(value) {
return typeof value == 'symbol' ||
(isObjectLike$7(value) && baseGetTag$6(value) == symbolTag$1);
}
var isSymbol_1 = isSymbol$4;
var Symbol$3 = _Symbol,
arrayMap$3 = _arrayMap,
isArray$9 = isArray_1,
isSymbol$3 = isSymbol_1;
/** Used as references for various `Number` constants. */
var INFINITY$2 = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto$1 = Symbol$3 ? Symbol$3.prototype : undefined,
symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString$2(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray$9(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap$3(value, baseToString$2) + '';
}
if (isSymbol$3(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY$2) ? '-0' : result;
}
var _baseToString = baseToString$2;
var baseToString$1 = _baseToString;
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString$5(value) {
return value == null ? '' : baseToString$1(value);
}
var toString_1 = toString$5;
var deburrLetter = _deburrLetter,
toString$4 = toString_1;
/** Used to match Latin Unicode letters (excluding mathematical operators). */
var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
/** Used to compose unicode character classes. */
var rsComboMarksRange$4 = '\\u0300-\\u036f',
reComboHalfMarksRange$4 = '\\ufe20-\\ufe2f',
rsComboSymbolsRange$4 = '\\u20d0-\\u20ff',
rsComboRange$4 = rsComboMarksRange$4 + reComboHalfMarksRange$4 + rsComboSymbolsRange$4;
/** Used to compose unicode capture groups. */
var rsCombo$3 = '[' + rsComboRange$4 + ']';
/**
* Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
* [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
*/
var reComboMark = RegExp(rsCombo$3, 'g');
/**
* Deburrs `string` by converting
* [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
* and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
* letters to basic Latin letters and removing
* [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to deburr.
* @returns {string} Returns the deburred string.
* @example
*
* _.deburr('déjà vu');
* // => 'deja vu'
*/
function deburr$1(string) {
string = toString$4(string);
return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
}
var deburr_1 = deburr$1;
/** Used to match words composed of alphanumeric characters. */
var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
/**
* Splits an ASCII `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function asciiWords$1(string) {
return string.match(reAsciiWord) || [];
}
var _asciiWords = asciiWords$1;
/** Used to detect strings that need a more robust regexp to match words. */
var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
/**
* Checks if `string` contains a word composed of Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a word is found, else `false`.
*/
function hasUnicodeWord$1(string) {
return reHasUnicodeWord.test(string);
}
var _hasUnicodeWord = hasUnicodeWord$1;
/** Used to compose unicode character classes. */
var rsAstralRange$3 = '\\ud800-\\udfff',
rsComboMarksRange$3 = '\\u0300-\\u036f',
reComboHalfMarksRange$3 = '\\ufe20-\\ufe2f',
rsComboSymbolsRange$3 = '\\u20d0-\\u20ff',
rsComboRange$3 = rsComboMarksRange$3 + reComboHalfMarksRange$3 + rsComboSymbolsRange$3,
rsDingbatRange = '\\u2700-\\u27bf',
rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
rsPunctuationRange = '\\u2000-\\u206f',
rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
rsVarRange$3 = '\\ufe0e\\ufe0f',
rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
/** Used to compose unicode capture groups. */
var rsApos$1 = "['\u2019]",
rsBreak = '[' + rsBreakRange + ']',
rsCombo$2 = '[' + rsComboRange$3 + ']',
rsDigits = '\\d+',
rsDingbat = '[' + rsDingbatRange + ']',
rsLower = '[' + rsLowerRange + ']',
rsMisc = '[^' + rsAstralRange$3 + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
rsFitz$2 = '\\ud83c[\\udffb-\\udfff]',
rsModifier$2 = '(?:' + rsCombo$2 + '|' + rsFitz$2 + ')',
rsNonAstral$2 = '[^' + rsAstralRange$3 + ']',
rsRegional$2 = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair$2 = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsUpper = '[' + rsUpperRange + ']',
rsZWJ$3 = '\\u200d';
/** Used to compose unicode regexes. */
var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',
rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',
rsOptContrLower = '(?:' + rsApos$1 + '(?:d|ll|m|re|s|t|ve))?',
rsOptContrUpper = '(?:' + rsApos$1 + '(?:D|LL|M|RE|S|T|VE))?',
reOptMod$2 = rsModifier$2 + '?',
rsOptVar$2 = '[' + rsVarRange$3 + ']?',
rsOptJoin$2 = '(?:' + rsZWJ$3 + '(?:' + [rsNonAstral$2, rsRegional$2, rsSurrPair$2].join('|') + ')' + rsOptVar$2 + reOptMod$2 + ')*',
rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',
rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',
rsSeq$2 = rsOptVar$2 + reOptMod$2 + rsOptJoin$2,
rsEmoji = '(?:' + [rsDingbat, rsRegional$2, rsSurrPair$2].join('|') + ')' + rsSeq$2;
/** Used to match complex or compound words. */
var reUnicodeWord = RegExp([
rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',
rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,
rsUpper + '+' + rsOptContrUpper,
rsOrdUpper,
rsOrdLower,
rsDigits,
rsEmoji
].join('|'), 'g');
/**
* Splits a Unicode `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function unicodeWords$1(string) {
return string.match(reUnicodeWord) || [];
}
var _unicodeWords = unicodeWords$1;
var asciiWords = _asciiWords,
hasUnicodeWord = _hasUnicodeWord,
toString$3 = toString_1,
unicodeWords = _unicodeWords;
/**
* Splits `string` into an array of its words.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {RegExp|string} [pattern] The pattern to match words.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the words of `string`.
* @example
*
* _.words('fred, barney, & pebbles');
* // => ['fred', 'barney', 'pebbles']
*
* _.words('fred, barney, & pebbles', /[^, ]+/g);
* // => ['fred', 'barney', '&', 'pebbles']
*/
function words$1(string, pattern, guard) {
string = toString$3(string);
pattern = guard ? undefined : pattern;
if (pattern === undefined) {
return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
}
return string.match(pattern) || [];
}
var words_1 = words$1;
var arrayReduce = _arrayReduce,
deburr = deburr_1,
words = words_1;
/** Used to compose unicode capture groups. */
var rsApos = "['\u2019]";
/** Used to match apostrophes. */
var reApos = RegExp(rsApos, 'g');
/**
* Creates a function like `_.camelCase`.
*
* @private
* @param {Function} callback The function to combine each word.
* @returns {Function} Returns the new compounder function.
*/
function createCompounder$1(callback) {
return function(string) {
return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
};
}
var _createCompounder = createCompounder$1;
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice$1(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
var _baseSlice = baseSlice$1;
var baseSlice = _baseSlice;
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/
function castSlice$2(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : baseSlice(array, start, end);
}
var _castSlice = castSlice$2;
/** Used to compose unicode character classes. */
var rsAstralRange$2 = '\\ud800-\\udfff',
rsComboMarksRange$2 = '\\u0300-\\u036f',
reComboHalfMarksRange$2 = '\\ufe20-\\ufe2f',
rsComboSymbolsRange$2 = '\\u20d0-\\u20ff',
rsComboRange$2 = rsComboMarksRange$2 + reComboHalfMarksRange$2 + rsComboSymbolsRange$2,
rsVarRange$2 = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsZWJ$2 = '\\u200d';
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasUnicode = RegExp('[' + rsZWJ$2 + rsAstralRange$2 + rsComboRange$2 + rsVarRange$2 + ']');
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/
function hasUnicode$4(string) {
return reHasUnicode.test(string);
}
var _hasUnicode = hasUnicode$4;
/**
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function asciiToArray$1(string) {
return string.split('');
}
var _asciiToArray = asciiToArray$1;
/** Used to compose unicode character classes. */
var rsAstralRange$1 = '\\ud800-\\udfff',
rsComboMarksRange$1 = '\\u0300-\\u036f',
reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f',
rsComboSymbolsRange$1 = '\\u20d0-\\u20ff',
rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1,
rsVarRange$1 = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsAstral$1 = '[' + rsAstralRange$1 + ']',
rsCombo$1 = '[' + rsComboRange$1 + ']',
rsFitz$1 = '\\ud83c[\\udffb-\\udfff]',
rsModifier$1 = '(?:' + rsCombo$1 + '|' + rsFitz$1 + ')',
rsNonAstral$1 = '[^' + rsAstralRange$1 + ']',
rsRegional$1 = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair$1 = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsZWJ$1 = '\\u200d';
/** Used to compose unicode regexes. */
var reOptMod$1 = rsModifier$1 + '?',
rsOptVar$1 = '[' + rsVarRange$1 + ']?',
rsOptJoin$1 = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral$1, rsRegional$1, rsSurrPair$1].join('|') + ')' + rsOptVar$1 + reOptMod$1 + ')*',
rsSeq$1 = rsOptVar$1 + reOptMod$1 + rsOptJoin$1,
rsSymbol$1 = '(?:' + [rsNonAstral$1 + rsCombo$1 + '?', rsCombo$1, rsRegional$1, rsSurrPair$1, rsAstral$1].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode$1 = RegExp(rsFitz$1 + '(?=' + rsFitz$1 + ')|' + rsSymbol$1 + rsSeq$1, 'g');
/**
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function unicodeToArray$1(string) {
return string.match(reUnicode$1) || [];
}
var _unicodeToArray = unicodeToArray$1;
var asciiToArray = _asciiToArray,
hasUnicode$3 = _hasUnicode,
unicodeToArray = _unicodeToArray;
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray$2(string) {
return hasUnicode$3(string)
? unicodeToArray(string)
: asciiToArray(string);
}
var _stringToArray = stringToArray$2;
var castSlice$1 = _castSlice,
hasUnicode$2 = _hasUnicode,
stringToArray$1 = _stringToArray,
toString$2 = toString_1;
/**
* Creates a function like `_.lowerFirst`.
*
* @private
* @param {string} methodName The name of the `String` case method to use.
* @returns {Function} Returns the new case function.
*/
function createCaseFirst$1(methodName) {
return function(string) {
string = toString$2(string);
var strSymbols = hasUnicode$2(string)
? stringToArray$1(string)
: undefined;
var chr = strSymbols
? strSymbols[0]
: string.charAt(0);
var trailing = strSymbols
? castSlice$1(strSymbols, 1).join('')
: string.slice(1);
return chr[methodName]() + trailing;
};
}
var _createCaseFirst = createCaseFirst$1;
var createCaseFirst = _createCaseFirst;
/**
* Converts the first character of `string` to upper case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.upperFirst('fred');
* // => 'Fred'
*
* _.upperFirst('FRED');
* // => 'FRED'
*/
var upperFirst$1 = createCaseFirst('toUpperCase');
var upperFirst_1 = upperFirst$1;
var createCompounder = _createCompounder,
upperFirst = upperFirst_1;
/**
* Converts `string` to
* [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
*
* @static
* @memberOf _
* @since 3.1.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the start cased string.
* @example
*
* _.startCase('--foo-bar--');
* // => 'Foo Bar'
*
* _.startCase('fooBar');
* // => 'Foo Bar'
*
* _.startCase('__FOO_BAR__');
* // => 'FOO BAR'
*/
var startCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + upperFirst(word);
});
var startCase_1 = startCase;
var startCase$1 = /*@__PURE__*/getDefaultExportFromCjs(startCase_1);
/**
* @memberof TranslateFunctions
* @alias TranslateFunction
*/
/**
* Translate Functions are the helper functions which you can use to translate
* your application.
*
* On the fronted they can be used with {@link useTranslation} hook. On the backend
* they are injected to any {@link AdminJS} instance and {@link ActionContext}.
*/
const translate = (i18n, key, name, resourceId, options = {}) => {
// cspell:disable-next-line
if (i18n.language === 'cimode') return [key, name].join('.');
let realOptions = {
...options,
defaultValue: options.defaultValue ?? startCase$1(name)
};
let keys = [`${key}.${name}`];
if (resourceId && typeof resourceId !== 'string') {
realOptions = resourceId;
} else if (resourceId) {
keys = [`resources.${resourceId}.${key}.${name}`, ...keys];
}
return i18n.t(keys, realOptions);
};
const createFunctions = i18n => {
const translateAction = (actionName, resourceId, options) => translate(i18n, 'actions', actionName, resourceId, options);
const translateButton = (buttonLabel, resourceId, options) => translate(i18n, 'buttons', buttonLabel, resourceId, options);
const translateLabel = (label, resourceId, options) => translate(i18n, 'labels', label, resourceId, options);
const translateProperty = (propertyName, resourceId, options) => translate(i18n, 'properties', propertyName, resourceId, options);
const translateMessage = (messageName, resourceId, options) => translate(i18n, 'messages', messageName, resourceId, {
...options,
defaultValue: options?.defaultValue ?? messageName
});
const translateComponent = (messageName, resourceId, options) => translate(i18n, 'components', messageName, resourceId, options);
const translatePage = (messageName, resourceId, options) => translate(i18n, 'pages', messageName, resourceId, options);
return {
translateAction,
ta: translateAction,
translateButton,
tb: translateButton,
translateLabel,
tl: translateLabel,
translateProperty,
tp: translateProperty,
translateMessage,
tm: translateMessage,
translateComponent,
tc: translateComponent,
translatePage,
t: i18n.t,
translate: i18n.t
};
};
/**
* Extends {@link TranslateFunctions}. Apart from that it also returns all the properties
* defined below.
*
* ```javascript
* import { useTranslation } from 'adminjs'
*
* const MyComponent = () => {
* const { translateButton } = useTranslation()
*
* return (
* <Box>
* <Button variant="contained" onClick={...}>{translateButton('save')}<Button>
* </Box>
* )
* }
* ```
*
* @memberof useTranslation
* @alias UseTranslationResponse
*
* @property {TranslateFunction} ... All functions defined in {@link TranslateFunctions}
*/
/**
* @classdesc
* Extends the useTranslation hook from react-i18next library.
*
* Returns all the {@link TranslateFunctions} + methods returned by the original
* useTranslation method from react-i18next like: `i18n` instance and `ready` flag.
*
* @class
* @subcategory Hooks
* @bundle
* @hideconstructor
* @returns {UseTranslationResponse}
*/
const useTranslation = () => {
// eslint-disable-next-line no-shadow
const {
i18n,
...rest
} = useTranslation$1();
const translateFunctions = createFunctions(i18n);
return {
...rest,
i18n,
...translateFunctions
};
};
const DROP_NOTICE = 'DROP_NOTICE';
const dropNotice = noticeId => ({
type: 'DROP_NOTICE',
data: {
noticeId
}
});
const ASSETS_INITIALIZE = 'ASSETS_INITIALIZE';
const BRANDING_INITIALIZE = 'BRANDING_INITIALIZE';
const DASHBOARD_INITIALIZE = 'DASHBOARD_INITIALIZE';
const LOCALE_INITIALIZE = 'LOCALE_INITIALIZE';
const PAGES_INITIALIZE = 'PAGES_INITIALIZE';
const PATHS_INITIALIZE = 'PATHS_INITIALIZE';
const RESOURCES_INITIALIZE = 'RESOURCES_INITIALIZE';
const THEME_INITIALIZE = 'THEME_INITIALIZE';
const VERSIONS_INITIALIZE = 'VERSIONS_INITIALIZE';
const SHOW_MODAL = 'SHOW_MODAL';
const HIDE_MODAL = 'HIDE_MODAL';
const showModal = data => ({
type: SHOW_MODAL,
data
});
const hideModal = () => ({
type: HIDE_MODAL
});
const INITIAL_ROUTE = 'INITIAL_ROUTE';
const ROUTE_CHANGED = 'ROUTE_CHANGED';
const initializeRoute = location => ({
type: ROUTE_CHANGED,
data: location
});
const changeRoute = location => ({
type: ROUTE_CHANGED,
data: location
});
const SESSION_INITIALIZE = 'SESSION_INITIALIZE';
const setCurrentAdmin = (data = null) => ({
type: SESSION_INITIALIZE,
data
});
const DRAWER_PREROUTE_SET = 'DRAWER_PREROUTE_SET';
const setDrawerPreRoute = data => ({
type: DRAWER_PREROUTE_SET,
data
});
const SET_NOTICE_PROGRESS = 'SET_NOTICE_PROGRESS';
const setNoticeProgress = data => ({
type: SET_NOTICE_PROGRESS,
data
});
const useModal = () => {
const dispatch = require$$3.useDispatch();
const {
translateButton,
translateLabel,
translateMessage
} = useTranslation();
const closeModal = React$1.useCallback(() => {
dispatch(hideModal());
}, []);
const openModal = props => {
const {
modalProps,
type,
confirmAction,
resourceId
} = props;
let buttons = modalProps.buttons || [];
const handleConfirm = () => {
closeModal();
if (confirmAction) confirmAction();
};
if (buttons.length) {
buttons = buttons.map(button => {
button.variant = button.variant || 'default';
if (button.label === 'cancel') {
button.onClick = button.onClick || closeModal;
}
button.label = translateButton(button.label || '', resourceId);
return button;
});
}
if (type === 'confirm') {
buttons.push({
label: translateButton('cancel', resourceId),
onClick: closeModal
});
buttons.push({
label: translateButton('confirm', resourceId),
variant: modalProps.variant || 'primary',
onClick: handleConfirm
});
}
if (type === 'alert') {
buttons.push({
label: translateButton('ok', resourceId),
variant: 'primary',
onClick: closeModal
});
}
const getDefaultTranslationKey = placement => `modal-${placement}`;
const data = {
modalProps: {
...modalProps,
label: translateLabel(modalProps.label ?? getDefaultTranslationKey('label'), resourceId),
title: translateMessage(modalProps.title ?? getDefaultTranslationKey('title'), resourceId),
subTitle: translateMessage(modalProps.subTitle ?? getDefaultTranslationKey('subTitle'), resourceId),
variant: modalProps.variant,
buttons,
onClose: modalProps.onClose || closeModal,
onOverlayClick: modalProps.onOverlayClick || closeModal
}
};
dispatch(showModal(data));
};
return {
openModal,
closeModal
};
};
/**
* @load ./use-action.doc.md
* @subcategory Hooks
*
* @param {ActionJSON} action action object
* @param {ActionParams} params
* @param {ActionCallCallback} onActionCall - callback triggered when action is performed
* @return {UseActionResult}
* @class
* @hideconstructor
*/
function useAction(action, params, onActionCall) {
const navigate = reactRouter.useNavigate();
const location = reactRouter.useLocation();
const translateFunctions = useTranslation();
const modalFunctions = useModal();
const actionResponseHandler = useActionResponseHandler(onActionCall);
const href = actionHref(action, params);
const callApi = buildActionCallApiTrigger({
action,
params,
actionResponseHandler
});
const handleClick = buildActionClickHandler({
action,
params,
actionResponseHandler,
navigate,
translateFunctions,
modalFunctions,
location
});
return {
href,
callApi,
handleClick
};
}
/**
* @classdesc
* Hook which allows you to get and set currentAdmin
*
* ### Usage
*
* ```javascript
* import { useCurrentAdmin } from 'adminjs'
*
* const myComponent = () => {
* const [currentAdmin, setCurrentAdmin] = useCurrentAdmin()
* // ...
* }
* ```
*
* @class
* @subcategory Hooks
* @bundle
* @returns {UseCurrentAdminResponse}
* @hideconstructor
*/
function useCurrentAdmin() {
const currentAdmin = require$$3.useSelector(state => state.session);
const dispatch = require$$3.useDispatch();
return [currentAdmin, admin => dispatch(setCurrentAdmin(admin))];
}
/**
* Result of the {@link useCurrentAdmin}.
* It is a tuple containing value and the setter
*
* @typedef {Array} UseCurrentAdminResponse
* @memberof useCurrentAdmin
* @alias UseCurrentAdminResponse
* @property {CurrentAdmin | null} [0] current admin
* @property {React.Dispatch<React.SetStateAction<CurrentAdmin>>} [1] value setter compatible
* with react useState
*/
const OPEN_FILTER_DRAWER = 'OPEN_FILTER_DRAWER';
const CLOSE_FILTER_DRAWER = 'CLOSE_FILTER_DRAWER';
const showFilterDrawer = () => ({
type: OPEN_FILTER_DRAWER,
isVisible: true
});
const hideFilterDrawer = () => ({
type: CLOSE_FILTER_DRAWER,
isVisible: false
});
var isArray$8 = isArray_1,
isSymbol$2 = isSymbol_1;
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey$3(value, object) {
if (isArray$8(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol$2(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
var _isKey = isKey$3;
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject$b(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
var isObject_1 = isObject$b;
var baseGetTag$5 = _baseGetTag,
isObject$a = isObject_1;
/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
funcTag$1 = '[object Function]',
genTag = '[object GeneratorFunction]',
proxyTag = '[object Proxy]';
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction$3(value) {
if (!isObject$a(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag$5(value);
return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag;
}
var isFunction_1 = isFunction$3;
var root$6 = _root;
/** Used to detect overreaching core-js shims. */
var coreJsData$1 = root$6['__core-js_shared__'];
var _coreJsData = coreJsData$1;
var coreJsData = _coreJsData;
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked$1(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
var _isMasked = isMasked$1;
/** Used for built-in method references. */
var funcProto$2 = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString$2 = funcProto$2.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource$2(func) {
if (func != null) {
try {
return funcToString$2.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
var _toSource = toSource$2;
var isFunction$2 = isFunction_1,
isMasked = _isMasked,
isObject$9 = isObject_1,
toSource$1 = _toSource;
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto$1 = Function.prototype,
objectProto$c = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString$1 = funcProto$1.toString;
/** Used to check objects for own properties. */
var hasOwnProperty$a = objectProto$c.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString$1.call(hasOwnProperty$a).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative$1(value) {
if (!isObject$9(value) || isMasked(value)) {
return false;
}
var pattern = isFunction$2(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource$1(value));
}
var _baseIsNative = baseIsNative$1;
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue$2(object, key) {
return object == null ? undefined : object[key];
}
var _getValue = getValue$2;
var baseIsNative = _baseIsNative,
getValue$1 = _getValue;
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative$7(object, key) {
var value = getValue$1(object, key);
return baseIsNative(value) ? value : undefined;
}
var _getNative = getNative$7;
var getNative$6 = _getNative;
/* Built-in method references that are verified to be native. */
var nativeCreate$4 = getNative$6(Object, 'create');
var _nativeCreate = nativeCreate$4;
var nativeCreate$3 = _nativeCreate;
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear$1() {
this.__data__ = nativeCreate$3 ? nativeCreate$3(null) : {};
this.size = 0;
}
var _hashClear = hashClear$1;
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete$1(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
var _hashDelete = hashDelete$1;
var nativeCreate$2 = _nativeCreate;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto$b = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$9 = objectProto$b.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet$1(key) {
var data = this.__data__;
if (nativeCreate$2) {
var result = data[key];
return result === HASH_UNDEFINED$2 ? undefined : result;
}
return hasOwnProperty$9.call(data, key) ? data[key] : undefined;
}
var _hashGet = hashGet$1;
var nativeCreate$1 = _nativeCreate;
/** Used for built-in method references. */
var objectProto$a = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$8 = objectProto$a.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas$1(key) {
var data = this.__data__;
return nativeCreate$1 ? (data[key] !== undefined) : hasOwnProperty$8.call(data, key);
}
var _hashHas = hashHas$1;
var nativeCreate = _nativeCreate;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet$1(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
return this;
}
var _hashSet = hashSet$1;
var hashClear = _hashClear,
hashDelete = _hashDelete,
hashGet = _hashGet,
hashHas = _hashHas,
hashSet = _hashSet;
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash$1(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash$1.prototype.clear = hashClear;
Hash$1.prototype['delete'] = hashDelete;
Hash$1.prototype.get = hashGet;
Hash$1.prototype.has = hashHas;
Hash$1.prototype.set = hashSet;
var _Hash = Hash$1;
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear$1() {
this.__data__ = [];
this.size = 0;
}
var _listCacheClear = listCacheClear$1;
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq$5(value, other) {
return value === other || (value !== value && other !== other);
}
var eq_1 = eq$5;
var eq$4 = eq_1;
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf$4(array, key) {
var length = array.length;
while (length--) {
if (eq$4(array[length][0], key)) {
return length;
}
}
return -1;
}
var _assocIndexOf = assocIndexOf$4;
var assocIndexOf$3 = _assocIndexOf;
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete$1(key) {
var data = this.__data__,
index = assocIndexOf$3(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
var _listCacheDelete = listCacheDelete$1;
var assocIndexOf$2 = _assocIndexOf;
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet$1(key) {
var data = this.__data__,
index = assocIndexOf$2(data, key);
return index < 0 ? undefined : data[index][1];
}
var _listCacheGet = listCacheGet$1;
var assocIndexOf$1 = _assocIndexOf;
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas$1(key) {
return assocIndexOf$1(this.__data__, key) > -1;
}
var _listCacheHas = listCacheHas$1;
var assocIndexOf = _assocIndexOf;
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet$1(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
var _listCacheSet = listCacheSet$1;
var listCacheClear = _listCacheClear,
listCacheDelete = _listCacheDelete,
listCacheGet = _listCacheGet,
listCacheHas = _listCacheHas,
listCacheSet = _listCacheSet;
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache$4(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache$4.prototype.clear = listCacheClear;
ListCache$4.prototype['delete'] = listCacheDelete;
ListCache$4.prototype.get = listCacheGet;
ListCache$4.prototype.has = listCacheHas;
ListCache$4.prototype.set = listCacheSet;
var _ListCache = ListCache$4;
var getNative$5 = _getNative,
root$5 = _root;
/* Built-in method references that are verified to be native. */
var Map$4 = getNative$5(root$5, 'Map');
var _Map = Map$4;
var Hash = _Hash,
ListCache$3 = _ListCache,
Map$3 = _Map;
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear$1() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map$3 || ListCache$3),
'string': new Hash
};
}
var _mapCacheClear = mapCacheClear$1;
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable$1(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
var _isKeyable = isKeyable$1;
var isKeyable = _isKeyable;
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData$4(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
var _getMapData = getMapData$4;
var getMapData$3 = _getMapData;
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete$1(key) {
var result = getMapData$3(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
var _mapCacheDelete = mapCacheDelete$1;
var getMapData$2 = _getMapData;
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet$1(key) {
return getMapData$2(this, key).get(key);
}
var _mapCacheGet = mapCacheGet$1;
var getMapData$1 = _getMapData;
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas$1(key) {
return getMapData$1(this, key).has(key);
}
var _mapCacheHas = mapCacheHas$1;
var getMapData = _getMapData;
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet$1(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
var _mapCacheSet = mapCacheSet$1;
var mapCacheClear = _mapCacheClear,
mapCacheDelete = _mapCacheDelete,
mapCacheGet = _mapCacheGet,
mapCacheHas = _mapCacheHas,
mapCacheSet = _mapCacheSet;
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache$3(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache$3.prototype.clear = mapCacheClear;
MapCache$3.prototype['delete'] = mapCacheDelete;
MapCache$3.prototype.get = mapCacheGet;
MapCache$3.prototype.has = mapCacheHas;
MapCache$3.prototype.set = mapCacheSet;
var _MapCache = MapCache$3;
var MapCache$2 = _MapCache;
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize$1(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize$1.Cache || MapCache$2);
return memoized;
}
// Expose `MapCache`.
memoize$1.Cache = MapCache$2;
var memoize_1 = memoize$1;
var memoize = memoize_1;
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped$1(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
var _memoizeCapped = memoizeCapped$1;
var memoizeCapped = _memoizeCapped;
/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath$1 = memoizeCapped(function(string) {
var result = [];
if (string.charCodeAt(0) === 46 /* . */) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
var _stringToPath = stringToPath$1;
var isArray$7 = isArray_1,
isKey$2 = _isKey,
stringToPath = _stringToPath,
toString$1 = toString_1;
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath$4(value, object) {
if (isArray$7(value)) {
return value;
}
return isKey$2(value, object) ? [value] : stringToPath(toString$1(value));
}
var _castPath = castPath$4;
var isSymbol$1 = isSymbol_1;
/** Used as references for various `Number` constants. */
var INFINITY$1 = 1 / 0;
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey$5(value) {
if (typeof value == 'string' || isSymbol$1(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
}
var _toKey = toKey$5;
var castPath$3 = _castPath,
toKey$4 = _toKey;
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet$3(object, path) {
path = castPath$3(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[toKey$4(path[index++])];
}
return (index && index == length) ? object : undefined;
}
var _baseGet = baseGet$3;
var getNative$4 = _getNative;
var defineProperty$2 = (function() {
try {
var func = getNative$4(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
var _defineProperty$1 = defineProperty$2;
var defineProperty$1 = _defineProperty$1;
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue$3(object, key, value) {
if (key == '__proto__' && defineProperty$1) {
defineProperty$1(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
var _baseAssignValue = baseAssignValue$3;
var baseAssignValue$2 = _baseAssignValue,
eq$3 = eq_1;
/** Used for built-in method references. */
var objectProto$9 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$7 = objectProto$9.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue$2(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty$7.call(object, key) && eq$3(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue$2(object, key, value);
}
}
var _assignValue = assignValue$2;
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER$1 = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex$4(value, length) {
var type = typeof value;
length = length == null ? MAX_SAFE_INTEGER$1 : length;
return !!length &&
(type == 'number' ||
(type != 'symbol' && reIsUint.test(value))) &&
(value > -1 && value % 1 == 0 && value < length);
}
var _isIndex = isIndex$4;
var assignValue$1 = _assignValue,
castPath$2 = _castPath,
isIndex$3 = _isIndex,
isObject$8 = isObject_1,
toKey$3 = _toKey;
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseSet$1(object, path, value, customizer) {
if (!isObject$8(object)) {
return object;
}
path = castPath$2(path, object);
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while (nested != null && ++index < length) {
var key = toKey$3(path[index]),
newValue = value;
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return object;
}
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined;
if (newValue === undefined) {
newValue = isObject$8(objValue)
? objValue
: (isIndex$3(path[index + 1]) ? [] : {});
}
}
assignValue$1(nested, key, newValue);
nested = nested[key];
}
return object;
}
var _baseSet = baseSet$1;
var baseGet$2 = _baseGet,
baseSet = _baseSet,
castPath$1 = _castPath;
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/
function basePickBy$2(object, paths, predicate) {
var index = -1,
length = paths.length,
result = {};
while (++index < length) {
var path = paths[index],
value = baseGet$2(object, path);
if (predicate(value, path)) {
baseSet(result, castPath$1(path, object), value);
}
}
return result;
}
var _basePickBy = basePickBy$2;
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn$1(object, key) {
return object != null && key in Object(object);
}
var _baseHasIn = baseHasIn$1;
var baseGetTag$4 = _baseGetTag,
isObjectLike$6 = isObjectLike_1;
/** `Object#toString` result references. */
var argsTag$2 = '[object Arguments]';
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments$1(value) {
return isObjectLike$6(value) && baseGetTag$4(value) == argsTag$2;
}
var _baseIsArguments = baseIsArguments$1;
var baseIsArguments = _baseIsArguments,
isObjectLike$5 = isObjectLike_1;
/** Used for built-in method references. */
var objectProto$8 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$6 = objectProto$8.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable$1 = objectProto$8.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments$4 = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike$5(value) && hasOwnProperty$6.call(value, 'callee') &&
!propertyIsEnumerable$1.call(value, 'callee');
};
var isArguments_1 = isArguments$4;
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength$3(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
var isLength_1 = isLength$3;
var castPath = _castPath,
isArguments$3 = isArguments_1,
isArray$6 = isArray_1,
isIndex$2 = _isIndex,
isLength$2 = isLength_1,
toKey$2 = _toKey;
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath$1(object, path, hasFunc) {
path = castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = toKey$2(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength$2(length) && isIndex$2(key, length) &&
(isArray$6(object) || isArguments$3(object));
}
var _hasPath = hasPath$1;
var baseHasIn = _baseHasIn,
hasPath = _hasPath;
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn$2(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}
var hasIn_1 = hasIn$2;
var basePickBy$1 = _basePickBy,
hasIn$1 = hasIn_1;
/**
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @returns {Object} Returns the new object.
*/
function basePick$1(object, paths) {
return basePickBy$1(object, paths, function(value, path) {
return hasIn$1(object, path);
});
}
var _basePick = basePick$1;
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush$3(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
var _arrayPush = arrayPush$3;
var Symbol$2 = _Symbol,
isArguments$2 = isArguments_1,
isArray$5 = isArray_1;
/** Built-in value references. */
var spreadableSymbol = Symbol$2 ? Symbol$2.isConcatSpreadable : undefined;
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable$1(value) {
return isArray$5(value) || isArguments$2(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
var _isFlattenable = isFlattenable$1;
var arrayPush$2 = _arrayPush,
isFlattenable = _isFlattenable;
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten$1(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten$1(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush$2(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
var _baseFlatten = baseFlatten$1;
var baseFlatten = _baseFlatten;
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten$1(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, 1) : [];
}
var flatten_1 = flatten$1;
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply$2(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
var _apply = apply$2;
var apply$1 = _apply;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest$2(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return apply$1(func, this, otherArgs);
};
}
var _overRest = overRest$2;
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant$1(value) {
return function() {
return value;
};
}
var constant_1 = constant$1;
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity$3(value) {
return value;
}
var identity_1 = identity$3;
var constant = constant_1,
defineProperty = _defineProperty$1,
identity$2 = identity_1;
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString$1 = !defineProperty ? identity$2 : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
var _baseSetToString = baseSetToString$1;
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut$1(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
var _shortOut = shortOut$1;
var baseSetToString = _baseSetToString,
shortOut = _shortOut;
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString$2 = shortOut(baseSetToString);
var _setToString = setToString$2;
var flatten = flatten_1,
overRest$1 = _overRest,
setToString$1 = _setToString;
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest$1(func) {
return setToString$1(overRest$1(func, undefined, flatten), func + '');
}
var _flatRest = flatRest$1;
var basePick = _basePick,
flatRest = _flatRest;
/**
* Creates an object composed of the picked `object` properties.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
*/
var pick = flatRest(function(object, paths) {
return object == null ? {} : basePick(object, paths);
});
var pick_1 = pick;
var pick$1 = /*@__PURE__*/getDefaultExportFromCjs(pick_1);
/* eslint-disable no-unused-vars */
// eslint-disable-next-line no-shadow
let QueryParams = /*#__PURE__*/function (QueryParams) {
QueryParams["Tab"] = "tab";
QueryParams["Redirect"] = "redirectUrl";
QueryParams["Refresh"] = "refresh";
return QueryParams;
}({});
// eslint-disable-next-line no-shadow
let QueryListParams = /*#__PURE__*/function (QueryListParams) {
QueryListParams["Page"] = "page";
QueryListParams["SortBy"] = "sortBy";
QueryListParams["Direction"] = "direction";
QueryListParams["Filters"] = "filters";
QueryListParams["Query"] = "query";
return QueryListParams;
}({});
function useQueryParams() {
const {
pathname
} = reactRouterDom.useLocation();
const [searchParams, setSearchParams] = reactRouterDom.useSearchParams();
const parsedQuery = React$1.useMemo(() => lib$2.parse(searchParams.toString(), {
allowDots: true
}), [searchParams, pathname]);
const {
sortBy,
direction,
page,
tab,
filters,
redirectUrl
} = parsedQuery;
const listParams = React$1.useMemo(() => pick$1(parsedQuery, [QueryListParams.SortBy, QueryListParams.Filters, QueryListParams.Direction, QueryListParams.Page, QueryListParams.Query]), [parsedQuery]);
function storeParams(params) {
setSearchParams(lib$2.stringify({
sortBy,
direction,
page,
tab,
filters,
redirectUrl,
...params
}, {
allowDots: true
}));
}
function clearParams(...params) {
const searchParamsKeys = Array.from(searchParams.keys());
const clearCandidates = params.length ? params : searchParamsKeys;
for (const param of searchParamsKeys) {
for (const paramToClear of clearCandidates) {
if (param.startsWith(paramToClear) && searchParams.get(param)) {
searchParams.delete(param);
}
}
}
setSearchParams(searchParams);
}
function getParam(param) {
searchParams.get(param);
}
return {
parsedQuery,
listParams,
filters: filters,
sortBy,
direction,
page,
tab,
redirectUrl,
storeParams,
clearParams,
getParam
};
}
const useFilterDrawer = () => {
const [filtersCount, setFiltersCount] = React$1.useState(0);
const dispatch = require$$3.useDispatch();
const isVisible = require$$3.useSelector(state => state.filterDrawer.isVisible);
const {
filters = {}
} = useQueryParams();
React$1.useEffect(() => {
setFiltersCount(Object.keys(filters).length);
}, [filters]);
const toggleFilter = () => {
dispatch(isVisible ? hideFilterDrawer() : showFilterDrawer());
};
const open = () => {
dispatch(showFilterDrawer());
};
const close = () => {
dispatch(hideFilterDrawer());
};
return {
filtersCount,
isVisible,
toggleFilter,
open,
close
};
};
/* eslint-disable no-console */
/**
* @load ./use-local-storage.doc.md
* @subcategory Hooks
* @class
* @see https://usehooks.com/useLocalStorage
*
* @param {string} key key under which hook will store the data
* @param {T} initialValue value which will be stringified and stored
* @return {UseLocalStorageResult<T>}
* @bundle
* @type {Function}
*/
function useLocalStorage(key, initialValue) {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = React$1.useState(() => {
try {
// Get from local storage by key
const item = window.localStorage.getItem(key);
// Parse stored json or if none return initialValue
return item ? JSON.parse(item) : initialValue;
} catch (error) {
// If error also return initialValue
console.log(error);
return initialValue;
}
});
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue = value => {
try {
// Allow value to be a function so we have same API as useState
const valueToStore = value instanceof Function ? value(storedValue) : value;
// Save state
setStoredValue(valueToStore);
// Save to local storage
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
// A more advanced implementation would handle the error case
console.log(error);
}
};
return [storedValue, setValue];
}
const useHistoryListen = () => {
const location = reactRouter.useLocation();
const [storedPath, setStoredPath] = useLocalStorage('prevPage', {});
const {
to = {},
from = {}
} = require$$3.useSelector(state => state.router);
const dispatch = require$$3.useDispatch();
React$1.useEffect(() => {
if (storedPath) {
dispatch(initializeRoute(storedPath));
}
}, []);
React$1.useEffect(() => {
const previousPath = [to.pathname, to.search].join('');
const currentPath = [location.pathname, location.search].join('');
if (previousPath !== currentPath) {
dispatch(changeRoute(location));
}
}, [location]);
React$1.useEffect(() => {
if (from.pathname) {
setStoredPath(from);
}
}, [from]);
};
const isSelected = (href, location) => {
const regExp = new RegExp(`${href}($|/)`);
return !!location.pathname.match(regExp);
};
function useNavigationResources(resources) {
const [openElements, setOpenElements] = useLocalStorage('sidebarElements', {});
const navigate = reactRouter.useNavigate();
const location = reactRouter.useLocation();
const {
translateLabel
} = useTranslation();
const enrichResource = React$1.useMemo(() => (resource, icon) => ({
href: resource.href || undefined,
icon,
isSelected: isSelected(resource.href, location),
label: translateLabel(resource.name, resource.id),
id: resource.id,
onClick: event => {
if (resource.href) {
event.preventDefault();
navigate(resource.href);
}
}
}), [location, navigate]);
// grouping resources into parents
const map = resources
// first filter out resources which are not visible
.filter(res => res.href && res.navigation?.show !== false).reduce((memo, resource) => {
// in case resource has the same name as parent we namespace it wit "resource-""
const key = resource.navigation?.name || ['resource', resource.name].join('-');
if (!resource.navigation || resource.navigation.name === null) {
memo[key] = enrichResource(resource, resource.navigation?.icon);
} else if (memo[key] && memo[key].elements && resource.navigation?.name) {
memo[key].label = translateLabel(resource.navigation?.name);
memo[key].elements?.push?.(enrichResource(resource));
} else {
memo[key] = {
elements: [enrichResource(resource)],
label: translateLabel(resource.navigation?.name),
icon: resource.navigation?.icon,
onClick: () => setOpenElements({
...openElements,
[key]: !openElements[key]
}),
isOpen: !!openElements[key]
};
}
return memo;
}, {});
return Object.values(map);
}
const FORM_VALUE_NULL = '__FORM_VALUE_NULL__';
const FORM_VALUE_EMPTY_OBJECT = '__FORM_VALUE_EMPTY_OBJECT__';
const FORM_VALUE_EMPTY_ARRAY = '__FORM_VALUE_EMPTY_ARRAY__';
const isObjectOrArray = value => typeof value === 'object' && value.constructor !== File && !(value instanceof Date);
/**
* Changes RecordJSON that it can be send as a FormData to the backend.
*
* FormData is required because we are sending files via the wire. But it has limitations.
* Namely it can only transport files and strings. That is why we have to convert some
* standard types like NULL to constants so they can be property converted back by the backend.
* And thus properly handled.
*
* @private
* @param {RecordJSON} record
* @return {FormData}
*/
function paramsToFormData(params) {
const formData = new FormData();
// Assume that params are flatted
Object.entries(params).forEach(([key, value]) => {
// {@link updateRecord} does not change empty objects "{}" - so in order to prevent having
// them changed to "[object Object]" we have to set them to empty strings.
if (value === null) {
return formData.set(key, FORM_VALUE_NULL);
}
// File objects has to go through because they are handled by FormData
if (isObjectOrArray(value)) {
if (Array.isArray(value)) {
return formData.set(key, FORM_VALUE_EMPTY_ARRAY);
}
return formData.set(key, FORM_VALUE_EMPTY_OBJECT);
}
// Convert Date fields to UTC timezone
if (value instanceof Date) {
return formData.set(key, value.toISOString());
}
// Rest goes as a standard value
return formData.set(key, value);
});
return formData;
}
/**
* Handlers of all [Actions]{@link Action} of type `record` returns record.
* Depending on a place and response we have to merge what was returned
* to the actual state. It is done in following places:
* - {@link useRecord} hook
* - {@link RecordInList} component
* - {@link RecordAction} component
*
* @private
*/
const mergeRecordResponse = (record, response) => ({
// we start from the response because it can have different recordActions or bulkActions
...(response.record || record),
// records has to be reset every time because so that user wont
// see old errors which are not relevant anymore
errors: response.record.errors,
populated: {
...record.populated,
...response.record.populated
},
params: {
...record.params,
...response.record.params
}
});
/**
* HOF returning a function which takes a record and returns an updated record.
* This way we can pass this to setState in react, which takes old state
* (in our case previousRecord) as an argument.
*
* Function is used when to the {@link OnPropertyChange} callback, user passes
* key (property name) and the value (followed by an optional selectedRecord).
*
* The responsibility of the function is to:
* - clear old values under passed key: so when user passes property === `some.key`
* function removes `some.key.1`, `some.key.2` etc
* - sets new value under the passed key for primitive types
* - in case of objects - it flattens them first and then sets all the resulted values
* under the path provided in the property argument
* - it fills value in RecordJSON#populated when selectedRecord is given
* - finally it invalidates populated for given property
*
*
* @param {string} property property that must be updated, supports nesting
* with dots
* @param {any} value value that must be set, undefined or null if
* deleting, will be flattened
* @param {RecordJSON} selectedRecord if value is reference ID, this must be a record
* it's referencing to
* @private
*/
const updateRecord = (property, value, selectedRecord) => previousRecord => {
let populatedModified = false;
const populatedCopy = {
...previousRecord.populated
};
const paramsCopy = flat.set(previousRecord.params, property, value);
if (property in populatedCopy) {
delete populatedCopy[property];
populatedModified = true;
}
if (selectedRecord) {
populatedCopy[property] = selectedRecord;
populatedModified = true;
}
return {
...previousRecord,
params: paramsCopy,
populated: populatedModified ? populatedCopy : previousRecord.populated
};
};
const isEntireRecordGiven = (propertyOrRecord, value) => !!(typeof value === 'undefined'
// user can pass property and omit value. This makes sense when
// third argument of the function (selectedRecord) is passed to onChange
// callback
&& !(typeof propertyOrRecord === 'string')
// we assume that only params has to be given
&& propertyOrRecord.params);
const filterRecordParams = function (record, options = {}) {
if (options.includeParams && record) {
return {
...record,
params: flat.selectParams(record.params || {}, options.includeParams)
};
}
return record;
};
const isPropertyPermitted = (propertyName, options = {}) => {
const {
includeParams
} = options;
if (includeParams) {
const parts = flat.pathToParts(propertyName, {
skipArrayIndexes: true
});
return parts.some(part => includeParams.includes(part));
}
return true;
};
const api$3 = new ApiClient();
/**
* @load ./use-record.doc.md
* @subcategory Hooks
* @class
* @hideconstructor
* @bundle
* @param {RecordJSON} [initialRecord],
* @param {string} resourceId
* @param {UseRecordOptions} [options]
* @return {UseRecordResult}
*/
const useRecord = (initialRecord, resourceId, options) => {
// setting up state
const [loading, setLoading] = React$1.useState(false);
const [isSynced, setIsSynced] = React$1.useState(true);
const [progress, setProgress] = React$1.useState(0);
const {
parsedQuery
} = useQueryParams();
const filteredRecord = initialRecord ? filterRecordParams(initialRecord, options) : null;
const [record, setRecord] = React$1.useState({
...filteredRecord,
params: filteredRecord?.params ?? {},
errors: initialRecord?.errors ?? {},
populated: initialRecord?.populated ?? {}
});
// it keeps the same format as useState function which can take either value or function
const setFilteredRecord = React$1.useCallback(value => {
const newRecord = value instanceof Function ? value(record) : value;
setRecord(filterRecordParams(newRecord, options));
}, [options, record]);
const onNotice = useNotice();
const handleChange = React$1.useCallback((propertyOrRecord, value, incomingRecord) => {
if (isEntireRecordGiven(propertyOrRecord, value)) {
setFilteredRecord(propertyOrRecord);
} else if (isPropertyPermitted(propertyOrRecord, options)) {
setRecord(updateRecord(propertyOrRecord, value, incomingRecord));
} else {
// eslint-disable-next-line no-console
console.warn([`You are trying to set property: "${propertyOrRecord}" which`, 'is not permitted. Take a look at `useRecord(..., { includeParams: [...]})`'].join('\n'));
}
setIsSynced(false);
}, [setRecord, options]);
const handleSubmit = React$1.useCallback((customParams = {}, submitOptions) => {
setLoading(true);
const mergedParams = flat.merge(record.params, customParams);
const formData = paramsToFormData(mergedParams);
const actionParams = {
resourceId,
onUploadProgress: e => setProgress(Math.round(e.loaded * 100 / (e.total ?? 1))),
data: formData,
params: parsedQuery,
headers: {
'Content-Type': 'multipart/form-data'
}
};
const promise = initialRecord?.id ? api$3.recordAction({
...actionParams,
actionName: 'edit',
recordId: record.id
}) : api$3.resourceAction({
...actionParams,
actionName: 'new'
});
promise.then(response => {
if (response.data.notice) {
onNotice(response.data.notice);
}
if (submitOptions?.updateOnSave !== false) {
setFilteredRecord(prev => mergeRecordResponse(prev, response.data));
}
setProgress(0);
setLoading(false);
setIsSynced(true);
}).catch(() => {
onNotice({
message: 'There was an error updating record, Check out console to see more information.',
type: 'error'
});
setProgress(0);
setLoading(false);
});
return promise;
}, [record, resourceId, setLoading, setProgress, setRecord]);
return {
record,
handleChange,
submit: handleSubmit,
loading,
progress,
setRecord: setFilteredRecord,
isSynced
};
};
const api$2 = new ApiClient();
/**
* @load ./use-records.doc.md
* @subcategory Hooks
* @class
* @hideconstructor
*
* @param {string} resourceId id of a resource for which you want to fetch records
* @return {UseRecordsResult}
* @bundle
* @type {Function}
*/
function useRecords(resourceId) {
const [records, setRecords] = React$1.useState([]);
const [loading, setLoading] = React$1.useState(false);
const [perPage, setPerPage] = React$1.useState(10);
const [page, setPage] = React$1.useState(1);
const [total, setTotal] = React$1.useState(0);
const [direction, setDirection] = React$1.useState('asc');
const [sortBy, setSortBy] = React$1.useState();
const location = reactRouter.useLocation();
const navigate = reactRouter.useNavigate();
const addNotice = useNotice();
const onNotice = useNotice();
const fetchData = () => {
setLoading(true);
const query = new URLSearchParams(location.search);
const promise = api$2.resourceAction({
actionName: 'list',
resourceId,
params: query
});
promise.then(response => {
const listActionResponse = response.data;
if (listActionResponse.notice) {
onNotice(listActionResponse.notice);
}
if (listActionResponse.redirectUrl) {
navigate(listActionResponse.redirectUrl);
return;
}
setRecords(listActionResponse.records);
setPage(listActionResponse.meta.page);
setPerPage(listActionResponse.meta.perPage);
setTotal(listActionResponse.meta.total);
setDirection(listActionResponse.meta.direction);
setSortBy(listActionResponse.meta.sortBy);
setLoading(false);
}).catch(() => {
addNotice({
message: 'errorFetchingRecords',
type: 'error',
resourceId
});
});
return promise;
};
React$1.useEffect(() => {
if (hasForceRefresh(location.search)) {
navigate({
pathname: location.pathname,
search: removeForceRefresh(location.search).toString()
}, {
replace: true
});
} else {
fetchData();
}
}, [resourceId, location.search, location.state]);
return {
records,
loading,
page,
total,
direction,
sortBy,
perPage,
fetchData
};
}
/**
* @load ./use-resource.doc.md
* @subcategory Hooks
* @class
* @hideconstructor
* @bundle
* @param {string} resourceId Id of a resource you want to get
*/
const useResource = resourceId => {
const resources = require$$3.useSelector(state => state.resources);
const foundResource = resources.find(resource => resource.id === resourceId);
return foundResource;
};
/**
* @load ./use-selected-records.doc.md
* @subcategory Hooks
* @class
* @hideconstructor
* @param {Array<RecordJSON>} records List of records on which you can perform `select` action
* @return {UseSelectedRecordsResult}
* @bundle
* @type {Function}
*/
function useSelectedRecords(records) {
const [selectedRecords, setSelectedRecords] = React$1.useState([]);
const handleSelect = record => {
const selectedIndex = selectedRecords.findIndex(selected => selected.id === record.id);
if (selectedIndex < 0) {
setSelectedRecords([...selectedRecords, record]);
} else {
const newSelectedRecords = [...selectedRecords];
newSelectedRecords.splice(selectedIndex, 1);
setSelectedRecords(newSelectedRecords);
}
};
const handleSelectAll = () => {
const missing = records.filter(record => !selectedRecords.find(selected => selected.id === record.id) && record.bulkActions.length);
if (missing.length) {
setSelectedRecords([...selectedRecords, ...missing]);
} else {
const newSelectedRecords = selectedRecords.filter(selected => !records.find(record => record.id === selected.id));
setSelectedRecords(newSelectedRecords);
}
};
return {
handleSelect,
handleSelectAll,
selectedRecords,
setSelectedRecords
};
}
var Hooks = /*#__PURE__*/Object.freeze({
__proto__: null,
FORM_VALUE_EMPTY_ARRAY: FORM_VALUE_EMPTY_ARRAY,
FORM_VALUE_EMPTY_OBJECT: FORM_VALUE_EMPTY_OBJECT,
FORM_VALUE_NULL: FORM_VALUE_NULL,
QueryListParams: QueryListParams,
QueryParams: QueryParams,
isEntireRecordGiven: isEntireRecordGiven,
paramsToFormData: paramsToFormData,
updateRecord: updateRecord,
useAction: useAction,
useActionResponseHandler: useActionResponseHandler,
useCurrentAdmin: useCurrentAdmin,
useFilterDrawer: useFilterDrawer,
useHistoryListen: useHistoryListen,
useLocalStorage: useLocalStorage,
useModal: useModal,
useNavigationResources: useNavigationResources,
useNotice: useNotice,
useQueryParams: useQueryParams,
useRecord: useRecord,
useRecords: useRecords,
useResource: useResource,
useSelectedRecords: useSelectedRecords,
useTranslation: useTranslation
});
/**
* @alias ActionButtonProps
* @memberof ActionButton
*/
/**
* Renders Button which redirects to given action
*
* ### Usage
*
* ```
* import { ActionButton } from 'adminjs'
* ```
*
* @component
* @subcategory Application
*/
const ActionButton = props => {
const {
children,
action,
actionPerformed,
resourceId,
recordId,
recordIds,
search,
queryParams
} = props;
const {
href,
handleClick
} = useAction(action, {
resourceId,
recordId,
recordIds,
search: lib$2.stringify(queryParams, {
addQueryPrefix: true
}) || search
}, actionPerformed);
if (!action) {
return null;
}
const firstChild = React__default$1.default.Children.toArray(children)[0];
if (!firstChild || typeof firstChild === 'string' || typeof firstChild === 'number' || typeof firstChild === 'boolean') {
throw new Error('ActionButton has to have one child');
}
const contentTag = getActionElementCss(resourceId, action.name, 'button');
const WrappedElement = /*#__PURE__*/React__default$1.default.cloneElement(firstChild, {
onClick: handleClick,
'data-testid': buildActionTestId(action),
'data-css': contentTag,
href
});
return WrappedElement;
};
const OverridableActionButton = allowOverride(ActionButton, 'ActionButton');
const BreadcrumbLink = styledComponents.styled(reactRouterDom.Link)`
color: ${({
theme
}) => theme.colors.grey60};
font-family: ${({
theme
}) => theme.font};
line-height: ${({
theme
}) => theme.lineHeights.default};
font-size: ${({
theme
}) => theme.fontSizes.default};
text-decoration: none;
&:hover {
color: ${({
theme
}) => theme.colors.primary100};
&:after {
color: ${({
theme
}) => theme.colors.grey60};
}
}
&:after {
content: '/';
padding: 0 ${({
theme
}) => theme.space.default};
}
&:last-child {
color: ${({
theme
}) => theme.colors.text};
&:after {
content: '';
}
}
`;
const BreadcrumbText = styledComponents.styled(DesignSystem.Text)`
color: ${({
theme
}) => theme.colors.grey100};
font-family: ${({
theme
}) => theme.font};
font-weight: ${({
theme
}) => theme.fontWeights.normal.toString()};
line-height: ${({
theme
}) => theme.lineHeights.default};
font-size: ${({
theme
}) => theme.fontSizes.default};
cursor: pointer;
display: inline;
&:after {
content: '/';
padding: 0 ${({
theme
}) => theme.space.default};
}
&:last-child {
&:after {
content: '';
}
}
`;
/**
* @memberof Breadcrumbs
*/
/**
* @component
* @private
*/
const Breadcrumbs = props => {
const {
resource,
record,
actionName
} = props;
const listAction = resource.resourceActions.find(({
name
}) => name === 'list');
const action = resource.actions.find(a => a.name === actionName);
const h = new ViewHelpers();
const {
tl,
ta
} = useTranslation();
const contentTag = getActionElementCss(resource.id, actionName, 'breadcrumbs');
return /*#__PURE__*/React__default$1.default.createElement(DesignSystem.Box, {
flexGrow: 1,
className: DesignSystem.cssClass('Breadcrumbs'),
"data-css": contentTag
}, /*#__PURE__*/React__default$1.default.createElement(BreadcrumbLink, {
to: h.dashboardUrl()
}, tl('dashboard')), listAction ? /*#__PURE__*/React__default$1.default.createElement(BreadcrumbLink, {
to: resource.href ? resource.href : '/',
className: record ? 'is-active' : ''
}, tl(resource.name, resource.id)) : /*#__PURE__*/React__default$1.default.createElement(BreadcrumbText, null, tl(resource.name, resource.id)), action && action.name !== 'list' && /*#__PURE__*/React__default$1.default.createElement(BreadcrumbLink, {
to: "#"
}, ta(action.label)));
};
const OverridableBreadcrumbs = allowOverride(Breadcrumbs, 'Breadcrumbs');
const actionsToButtonGroup = options => {
const {
actions,
params,
handleClick,
translateFunctions
} = options;
const {
translateAction
} = translateFunctions;
const {
resourceId
} = params;
const buttons = actions.map(action => {
const href = actionHref(action, params);
return {
icon: action.icon,
label: translateAction(action.label, resourceId),
variant: action.variant,
source: action,
href: href || undefined,
// when href is not defined - handle click should also be not defined
// This prevents from "cursor: pointer;"
onClick: href ? handleClick : undefined,
'data-testid': buildActionTestId(action),
buttons: [],
'data-css': `${action.resourceId}-${action.name}-button`
};
});
// nesting buttons
const buttonsMap = buttons.reduce((memo, button) => {
const action = button.source;
if (action.parent) {
const parent = memo[action.parent] || buttons.find(btn => btn.source.name === action.parent) || {
label: action.parent
};
parent.buttons = parent.buttons || [];
parent.buttons.push(button);
return {
...memo,
[action.parent]: parent
};
}
return {
...memo,
[button.source.name]: button
};
}, {});
return Object.values(buttonsMap);
};
function _extends$s() { _extends$s = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$s.apply(this, arguments); }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const StyledLink$1 = styledComponents.styled(({
rounded,
to,
...rest
}) => /*#__PURE__*/React__default$1.default.createElement(reactRouterDom.Link, _extends$s({
to: to
}, rest)))`${DesignSystem.ButtonCSS}`;
const StyledBackButton = props => {
const location = reactRouter.useLocation();
const {
showInDrawer
} = props;
const cssCloseIcon = showInDrawer ? 'ChevronRight' : 'ChevronLeft';
return /*#__PURE__*/React__default$1.default.createElement(StyledLink$1, {
size: "icon",
to: {
pathname: '..',
search: location.search
},
relative: "route",
rounded: true,
mr: "lg",
type: "button"
}, /*#__PURE__*/React__default$1.default.createElement(DesignSystem.Icon, {
icon: cssCloseIcon
}));
};
const OverridableStyledBackButton = allowOverride(StyledBackButton, 'StyledBackButton');
/* eslint-disable jsx-a11y/anchor-is-valid */
/**
* Header of an action. It renders Action name with buttons for all the actions.
*
* ### Usage
*
* ```
* import { ActionHeader } from 'adminjs'
* ```
*
* @component
* @subcategory Application
*/
const ActionHeader = props => {
const {
resource,
actionPerformed,
record,
action,
tag,
omitActions,
toggleFilter: isFilterButtonVisible
} = props;
const translateFunctions = useTranslation();
const {
translateButton,
translateAction
} = translateFunctions;
const navigate = reactRouter.useNavigate();
const location = reactRouter.useLocation();
const actionResponseHandler = useActionResponseHandler(actionPerformed);
const modalFunctions = useModal();
const {
toggleFilter,
filtersCount
} = useFilterDrawer();
if (action.hideActionHeader) {
return null;
}
const resourceId = resource.id;
const params = {
resourceId,
recordId: record?.id
};
// eslint-disable-next-line max-len
const handleActionClick = (event, sourceAction) => buildActionClickHandler({
action: sourceAction,
params,
actionResponseHandler,
navigate,
location,
translateFunctions,
modalFunctions
})(event);
const actionButtons = actionsToButtonGroup({
actions: record ? record.recordActions.filter(ra => !action || action.name !== ra.name)
// only new action should be seen in regular "Big" actions place
: resource.resourceActions.filter(ra => ra.name === 'new' && (!action || action.name !== ra.name)),
params,
handleClick: handleActionClick,
translateFunctions,
modalFunctions
});
if (typeof isFilterButtonVisible === 'function' || isFilterButtonVisible) {
const filterTranslationKey = filtersCount > 0 ? 'filterActive' : 'filter';
actionButtons.push({
label: translateButton(filterTranslationKey, resource.id, {
count: filtersCount
}),
onClick: toggleFilter,
icon: 'Filter',
'data-css': getResourceElementCss(resource.id, 'filter-button')
});
}
// list and new actions are special and are are always
const customResourceButtons = actionsToButtonGroup({
actions: action.showResourceActions ? resource.resourceActions.filter(ra => !['list', 'new'].includes(ra.name)) : [],
params: {
resourceId
},
handleClick: handleActionClick,
translateFunctions,
modalFunctions
});
const title = action ? translateAction(action.label, resourceId) : resource.name;
// styled which differs if action header is in the drawer or not
const cssIsRootFlex = !action.showInDrawer;
const cssHeaderMT = action.showInDrawer ? '' : 'lg';
const cssActionsMB = action.showInDrawer ? 'xl' : 'default';
const CssHComponent = action.showInDrawer ? DesignSystem.H3 : DesignSystem.H2;
const contentTag = getActionElementCss(resourceId, action.name, 'action-header');
return /*#__PURE__*/React__default$1.default.createElement(DesignSystem.Box, {
className: DesignSystem.cssClass('ActionHeader'),
"data-css": contentTag
}, !action.showInDrawer && /*#__PURE__*/React__default$1.default.createElement(DesignSystem.Box, {
flex: true,
flexDirection: "row",
px: ['default', 0]
}, /*#__PURE__*/React__default$1.default.createElement(OverridableBreadcrumbs, {
resource: resource,
actionName: action.name,
record: record
}), /*#__PURE__*/React__default$1.default.createElement(DesignSystem.Box, {
flexShrink: 0
}, /*#__PURE__*/React__default$1.default.createElement(DesignSystem.ButtonGroup, {
size: "sm",
rounded: true,
buttons: customResourceButtons
}))), /*#__PURE__*/React__default$1.default.createElement(DesignSystem.Box, {
display: ['block', cssIsRootFlex ? 'flex' : 'block']
}, /*#__PURE__*/React__default$1.default.createElement(DesignSystem.Box, {
mt: cssHeaderMT,
flexGrow: 1,
px: ['default', 0]
}, /*#__PURE__*/React__default$1.default.createElement(CssHComponent, {
mb: "lg"
}, action.showInDrawer && /*#__PURE__*/React__default$1.default.createElement(OverridableStyledBackButton, {
showInDrawer: action.showInDrawer
}), title, tag ? /*#__PURE__*/React__default$1.default.createElement(DesignSystem.Badge, {
variant: "default",
outline: true,
ml: "default"
}, tag) : null)), !omitActions && /*#__PURE__*/React__default$1.default.createElement(DesignSystem.Box, {
mt: "xl",
mb: cssActionsMB,
flexShrink: 0
}, /*#__PURE__*/React__default$1.default.createElement(DesignSystem.ButtonGroup, {
buttons: actionButtons
}))));
};
const OverridableActionHeader = allowOverride(ActionHeader, 'ActionHeader');
const AdminModal = () => {
const modalState = require$$3.useSelector(state => state.modal);
return modalState.show ? /*#__PURE__*/React__default$1.default.createElement(DesignSystem.Modal, modalState.modalProps) : null;
};
const AppLoader = () => /*#__PURE__*/React__default$1.default.createElement(DesignSystem.Box, {
width: "100%",
height: "100%",
flex: true,
alignItems: "center",
justifyContent: "center"
}, /*#__PURE__*/React__default$1.default.createElement(DesignSystem.Loader, null));
const AuthenticationBackgroundComponent = () => null;
const OverridableAuthenticationBackgroundComponent = allowOverride(AuthenticationBackgroundComponent, 'AuthenticationBackgroundComponent');
const ErrorMessage = ({
error
}) => {
const {
translateMessage
} = useTranslation();
return /*#__PURE__*/React__default$1.default.createElement(DesignSystem.MessageBox, {
m: "xxl",
variant: "danger",
message: "Javascript Error"
}, /*#__PURE__*/React__default$1.default.createElement(DesignSystem.Text, null, error.toString()), /*#__PURE__*/React__default$1.default.createElement(DesignSystem.Text, {
mt: "default"
}, translateMessage('seeConsoleForMore')));
};
let ErrorBoundary$1 = class ErrorBoundary extends React__default$1.default.Component {
constructor(props) {
super(props);
this.state = {
error: null
};
}
componentDidCatch(error) {
this.setState({
error
});
}
render() {
const {
children
} = this.props;
const {
error
} = this.state;
if (error !== null) {
return /*#__PURE__*/React__default$1.default.createElement(ErrorMessage, {
error: error
});
}
return children || null;
}
};
var dnd_cjs = {};
var useMemoOne_cjs = {};
Object.defineProperty(useMemoOne_cjs, '__esModule', { value: true });
var react = React__default$1.default;
function areInputsEqual$1(newInputs, lastInputs) {
if (newInputs.length !== lastInputs.length) {
return false;
}
for (var i = 0; i < newInputs.length; i++) {
if (newInputs[i] !== lastInputs[i]) {
return false;
}
}
return true;
}
function useMemoOne$1(getResult, inputs) {
var initial = react.useState(function () {
return {
inputs: inputs,
result: getResult()
};
})[0];
var isFirstRun = react.useRef(true);
var committed = react.useRef(initial);
var useCache = isFirstRun.current || Boolean(inputs && committed.current.inputs && areInputsEqual$1(inputs, committed.current.inputs));
var cache = useCache ? committed.current : {
inputs: inputs,
result: getResult()
};
react.useEffect(function () {
isFirstRun.current = false;
committed.current = cache;
}, [cache]);
return cache.result;
}
function useCallbackOne(callback, inputs) {
return useMemoOne$1(function () {
return callback;
}, inputs);
}
var useMemo = useMemoOne$1;
var useCallback = useCallbackOne;
useMemoOne_cjs.useCallback = useCallback;
useMemoOne_cjs.useCallbackOne = useCallbackOne;
useMemoOne_cjs.useMemo = useMemo;
useMemoOne_cjs.useMemoOne = useMemoOne$1;
var cssBoxModel_cjs = {};
var prefix$2 = 'Invariant failed';
function invariant$2(condition, message) {
if (condition) {
return;
}
var provided = typeof message === 'function' ? message() : message;
var value = provided ? "".concat(prefix$2, ": ").concat(provided) : prefix$2;
throw new Error(value);
}
var tinyInvariant_cjs = invariant$2;
Object.defineProperty(cssBoxModel_cjs, '__esModule', { value: true });
function _interopDefault$1 (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var invariant$1 = _interopDefault$1(tinyInvariant_cjs);
var getRect = function getRect(_ref) {
var top = _ref.top,
right = _ref.right,
bottom = _ref.bottom,
left = _ref.left;
var width = right - left;
var height = bottom - top;
var rect = {
top: top,
right: right,
bottom: bottom,
left: left,
width: width,
height: height,
x: left,
y: top,
center: {
x: (right + left) / 2,
y: (bottom + top) / 2
}
};
return rect;
};
var expand = function expand(target, expandBy) {
return {
top: target.top - expandBy.top,
left: target.left - expandBy.left,
bottom: target.bottom + expandBy.bottom,
right: target.right + expandBy.right
};
};
var shrink = function shrink(target, shrinkBy) {
return {
top: target.top + shrinkBy.top,
left: target.left + shrinkBy.left,
bottom: target.bottom - shrinkBy.bottom,
right: target.right - shrinkBy.right
};
};
var shift = function shift(target, shiftBy) {
return {
top: target.top + shiftBy.y,
left: target.left + shiftBy.x,
bottom: target.bottom + shiftBy.y,
right: target.right + shiftBy.x
};
};
var noSpacing$1 = {
top: 0,
right: 0,
bottom: 0,
left: 0
};
var createBox = function createBox(_ref2) {
var borderBox = _ref2.borderBox,
_ref2$margin = _ref2.margin,
margin = _ref2$margin === void 0 ? noSpacing$1 : _ref2$margin,
_ref2$border = _ref2.border,
border = _ref2$border === void 0 ? noSpacing$1 : _ref2$border,
_ref2$padding = _ref2.padding,
padding = _ref2$padding === void 0 ? noSpacing$1 : _ref2$padding;
var marginBox = getRect(expand(borderBox, margin));
var paddingBox = getRect(shrink(borderBox, border));
var contentBox = getRect(shrink(paddingBox, padding));
return {
marginBox: marginBox,
borderBox: getRect(borderBox),
paddingBox: paddingBox,
contentBox: contentBox,
margin: margin,
border: border,
padding: padding
};
};
var parse = function parse(raw) {
var value = raw.slice(0, -2);
var suffix = raw.slice(-2);
if (suffix !== 'px') {
return 0;
}
var result = Number(value);
!!isNaN(result) ? invariant$1(false, "Could not parse value [raw: " + raw + ", without suffix: " + value + "]") : void 0;
return result;
};
var getWindowScroll$1 = function getWindowScroll() {
return {
x: window.pageXOffset,
y: window.pageYOffset
};
};
var offset = function offset(original, change) {
var borderBox = original.borderBox,
border = original.border,
margin = original.margin,
padding = original.padding;
var shifted = shift(borderBox, change);
return createBox({
borderBox: shifted,
border: border,
margin: margin,
padding: padding
});
};
var withScroll = function withScroll(original, scroll) {
if (scroll === void 0) {
scroll = getWindowScroll$1();
}
return offset(original, scroll);
};
var calculateBox = function calculateBox(borderBox, styles) {
var margin = {
top: parse(styles.marginTop),
right: parse(styles.marginRight),
bottom: parse(styles.marginBottom),
left: parse(styles.marginLeft)
};
var padding = {
top: parse(styles.paddingTop),
right: parse(styles.paddingRight),
bottom: parse(styles.paddingBottom),
left: parse(styles.paddingLeft)
};
var border = {
top: parse(styles.borderTopWidth),
right: parse(styles.borderRightWidth),
bottom: parse(styles.borderBottomWidth),
left: parse(styles.borderLeftWidth)
};
return createBox({
borderBox: borderBox,
margin: margin,
padding: padding,
border: border
});
};
var getBox = function getBox(el) {
var borderBox = el.getBoundingClientRect();
var styles = window.getComputedStyle(el);
return calculateBox(borderBox, styles);
};
cssBoxModel_cjs.calculateBox = calculateBox;
cssBoxModel_cjs.createBox = createBox;
cssBoxModel_cjs.expand = expand;
cssBoxModel_cjs.getBox = getBox;
cssBoxModel_cjs.getRect = getRect;
cssBoxModel_cjs.offset = offset;
cssBoxModel_cjs.shrink = shrink;
cssBoxModel_cjs.withScroll = withScroll;
var safeIsNaN = Number.isNaN ||
function ponyfill(value) {
return typeof value === 'number' && value !== value;
};
function isEqual$2(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$2(newInputs[i], lastInputs[i])) {
return false;
}
}
return true;
}
function memoizeOne$1(resultFn, isEqual) {
if (isEqual === void 0) { isEqual = areInputsEqual; }
var cache = null;
function memoized() {
var newArgs = [];
for (var _i = 0; _i < arguments.length; _i++) {
newArgs[_i] = arguments[_i];
}
if (cache && cache.lastThis === this && isEqual(newArgs, cache.lastArgs)) {
return cache.lastResult;
}
var lastResult = resultFn.apply(this, newArgs);
cache = {
lastResult: lastResult,
lastArgs: newArgs,
lastThis: this,
};
return lastResult;
}
memoized.clear = function clear() {
cache = null;
};
return memoized;
}
var memoizeOne_cjs = memoizeOne$1;
var rafSchd$1 = function rafSchd(fn) {
var lastArgs = [];
var frameId = null;
var wrapperFn = function wrapperFn() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
lastArgs = args;
if (frameId) {
return;
}
frameId = requestAnimationFrame(function () {
frameId = null;
fn.apply(void 0, lastArgs);
});
};
wrapperFn.cancel = function () {
if (!frameId) {
return;
}
cancelAnimationFrame(frameId);
frameId = null;
};
return wrapperFn;
};
var rafSchd_cjs = rafSchd$1;
var _extends$r = {exports: {}};
(function (module) {
function _extends() {
module.exports = _extends = Object.assign ? Object.assign.bind() : function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
return _extends.apply(this, arguments);
}
module.exports = _extends, module.exports.__esModule = true, module.exports["default"] = module.exports;
} (_extends$r));
var _extendsExports = _extends$r.exports;
Object.defineProperty(dnd_cjs, '__esModule', { value: true });
var React = React__default$1.default;
var ReactDOM = require$$1__default.default;
var redux = require$$0__default.default;
var reactRedux = require$$3__default.default;
var useMemoOne = useMemoOne_cjs;
var cssBoxModel = cssBoxModel_cjs;
var memoizeOne = memoizeOne_cjs;
var rafSchd = rafSchd_cjs;
var _extends$q = _extendsExports;
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var ReactDOM__default = /*#__PURE__*/_interopDefaultLegacy(ReactDOM);
var memoizeOne__default = /*#__PURE__*/_interopDefaultLegacy(memoizeOne);
var rafSchd__default = /*#__PURE__*/_interopDefaultLegacy(rafSchd);
var _extends__default = /*#__PURE__*/_interopDefaultLegacy(_extends$q);
const spacesAndTabs = /[ \t]{2,}/g;
const lineStartWithSpaces = /^[ \t]*/gm;
const clean$2 = value => value.replace(spacesAndTabs, ' ').replace(lineStartWithSpaces, '').trim();
const getDevMessage = message => clean$2(`
%c@hello-pangea/dnd
%c${clean$2(message)}
%c👷 This is a development only message. It will be removed in production builds.
`);
const getFormattedMessage = message => [getDevMessage(message),
'color: #00C584; font-size: 1.2em; font-weight: bold;',
'line-height: 1.5',
'color: #723874;'];
const isDisabledFlag = '__@hello-pangea/dnd-disable-dev-warnings';
function log(type, message) {
if (typeof window !== 'undefined' && window[isDisabledFlag]) {
return;
}
console[type](...getFormattedMessage(message));
}
const warning = log.bind(null, 'warn');
const error = log.bind(null, 'error');
function noop$2() {}
function getOptions(shared, fromBinding) {
return {
...shared,
...fromBinding
};
}
function bindEvents(el, bindings, sharedOptions) {
const unbindings = bindings.map(binding => {
const options = getOptions(sharedOptions, binding.options);
el.addEventListener(binding.eventName, binding.fn, options);
return function unbind() {
el.removeEventListener(binding.eventName, binding.fn, options);
};
});
return function unbindAll() {
unbindings.forEach(unbind => {
unbind();
});
};
}
const prefix$1 = 'Invariant failed';
class RbdInvariant extends Error {}
RbdInvariant.prototype.toString = function toString() {
return this.message;
};
function invariant(condition, message) {
if (condition) {
return;
}
{
throw new RbdInvariant(`${prefix$1}: ${message || ''}`);
}
}
class ErrorBoundary extends React__default["default"].Component {
constructor() {
super(...arguments);
this.callbacks = null;
this.unbind = noop$2;
this.onWindowError = event => {
const callbacks = this.getCallbacks();
if (callbacks.isDragging()) {
callbacks.tryAbort();
warning(`
An error was caught by our window 'error' event listener while a drag was occurring.
The active drag has been aborted.
`) ;
}
const err = event.error;
if (err instanceof RbdInvariant) {
event.preventDefault();
{
error(err.message);
}
}
};
this.getCallbacks = () => {
if (!this.callbacks) {
throw new Error('Unable to find AppCallbacks in <ErrorBoundary/>');
}
return this.callbacks;
};
this.setCallbacks = callbacks => {
this.callbacks = callbacks;
};
}
componentDidMount() {
this.unbind = bindEvents(window, [{
eventName: 'error',
fn: this.onWindowError
}]);
}
componentDidCatch(err) {
if (err instanceof RbdInvariant) {
{
error(err.message);
}
this.setState({});
return;
}
throw err;
}
componentWillUnmount() {
this.unbind();
}
render() {
return this.props.children(this.setCallbacks);
}
}
const dragHandleUsageInstructions = `
Press space bar to start a drag.
When dragging you can use the arrow keys to move the item around and escape to cancel.
Some screen readers may require you to be in focus mode or to use your pass through key
`;
const position = index => index + 1;
const onDragStart = start => `
You have lifted an item in position ${position(start.source.index)}
`;
const withLocation = (source, destination) => {
const isInHomeList = source.droppableId === destination.droppableId;
const startPosition = position(source.index);
const endPosition = position(destination.index);
if (isInHomeList) {
return `
You have moved the item from position ${startPosition}
to position ${endPosition}
`;
}
return `
You have moved the item from position ${startPosition}
in list ${source.droppableId}
to list ${destination.droppableId}
in position ${endPosition}
`;
};
const withCombine = (id, source, combine) => {
const inHomeList = source.droppableId === combine.droppableId;
if (inHomeList) {
return `
The item ${id}
has been combined with ${combine.draggableId}`;
}
return `
The item ${id}
in list ${source.droppableId}
has been combined with ${combine.draggableId}
in list ${combine.droppableId}
`;
};
const onDragUpdate = update => {
const location = update.destination;
if (location) {
return withLocation(update.source, location);
}
const combine = update.combine;
if (combine) {
return withCombine(update.draggableId, update.source, combine);
}
return 'You are over an area that cannot be dropped on';
};
const returnedToStart = source => `
The item has returned to its starting position
of ${position(source.index)}
`;
const onDragEnd = result => {
if (result.reason === 'CANCEL') {
return `
Movement cancelled.
${returnedToStart(result.source)}
`;
}
const location = result.destination;
const combine = result.combine;
if (location) {
return `
You have dropped the item.
${withLocation(result.source, location)}
`;
}
if (combine) {
return `
You have dropped the item.
${withCombine(result.draggableId, result.source, combine)}
`;
}
return `
The item has been dropped while not over a drop area.
${returnedToStart(result.source)}
`;
};
const preset = {
dragHandleUsageInstructions,
onDragStart,
onDragUpdate,
onDragEnd
};
var preset$1 = preset;
const origin = {
x: 0,
y: 0
};
const add = (point1, point2) => ({
x: point1.x + point2.x,
y: point1.y + point2.y
});
const subtract = (point1, point2) => ({
x: point1.x - point2.x,
y: point1.y - point2.y
});
const isEqual$1 = (point1, point2) => point1.x === point2.x && point1.y === point2.y;
const negate = point => ({
x: point.x !== 0 ? -point.x : 0,
y: point.y !== 0 ? -point.y : 0
});
const patch = function (line, value, otherValue) {
if (otherValue === void 0) {
otherValue = 0;
}
if (line === 'x') {
return {
x: value,
y: otherValue
};
}
return {
x: otherValue,
y: value
};
};
const distance = (point1, point2) => Math.sqrt((point2.x - point1.x) ** 2 + (point2.y - point1.y) ** 2);
const closest$1 = (target, points) => Math.min(...points.map(point => distance(target, point)));
const apply = fn => point => ({
x: fn(point.x),
y: fn(point.y)
});
var executeClip = ((frame, subject) => {
const result = cssBoxModel.getRect({
top: Math.max(subject.top, frame.top),
right: Math.min(subject.right, frame.right),
bottom: Math.min(subject.bottom, frame.bottom),
left: Math.max(subject.left, frame.left)
});
if (result.width <= 0 || result.height <= 0) {
return null;
}
return result;
});
const offsetByPosition = (spacing, point) => ({
top: spacing.top + point.y,
left: spacing.left + point.x,
bottom: spacing.bottom + point.y,
right: spacing.right + point.x
});
const getCorners = spacing => [{
x: spacing.left,
y: spacing.top
}, {
x: spacing.right,
y: spacing.top
}, {
x: spacing.left,
y: spacing.bottom
}, {
x: spacing.right,
y: spacing.bottom
}];
const noSpacing = {
top: 0,
right: 0,
bottom: 0,
left: 0
};
const scroll$1 = (target, frame) => {
if (!frame) {
return target;
}
return offsetByPosition(target, frame.scroll.diff.displacement);
};
const increase = (target, axis, withPlaceholder) => {
if (withPlaceholder && withPlaceholder.increasedBy) {
return {
...target,
[axis.end]: target[axis.end] + withPlaceholder.increasedBy[axis.line]
};
}
return target;
};
const clip = (target, frame) => {
if (frame && frame.shouldClipSubject) {
return executeClip(frame.pageMarginBox, target);
}
return cssBoxModel.getRect(target);
};
var getSubject = (_ref => {
let {
page,
withPlaceholder,
axis,
frame
} = _ref;
const scrolled = scroll$1(page.marginBox, frame);
const increased = increase(scrolled, axis, withPlaceholder);
const clipped = clip(increased, frame);
return {
page,
withPlaceholder,
active: clipped
};
});
var scrollDroppable = ((droppable, newScroll) => {
!droppable.frame ? invariant(false) : void 0;
const scrollable = droppable.frame;
const scrollDiff = subtract(newScroll, scrollable.scroll.initial);
const scrollDisplacement = negate(scrollDiff);
const frame = {
...scrollable,
scroll: {
initial: scrollable.scroll.initial,
current: newScroll,
diff: {
value: scrollDiff,
displacement: scrollDisplacement
},
max: scrollable.scroll.max
}
};
const subject = getSubject({
page: droppable.subject.page,
withPlaceholder: droppable.subject.withPlaceholder,
axis: droppable.axis,
frame
});
const result = {
...droppable,
frame,
subject
};
return result;
});
const toDroppableMap = memoizeOne__default["default"](droppables => droppables.reduce((previous, current) => {
previous[current.descriptor.id] = current;
return previous;
}, {}));
const toDraggableMap = memoizeOne__default["default"](draggables => draggables.reduce((previous, current) => {
previous[current.descriptor.id] = current;
return previous;
}, {}));
const toDroppableList = memoizeOne__default["default"](droppables => Object.values(droppables));
const toDraggableList = memoizeOne__default["default"](draggables => Object.values(draggables));
var getDraggablesInsideDroppable = memoizeOne__default["default"]((droppableId, draggables) => {
const result = toDraggableList(draggables).filter(draggable => droppableId === draggable.descriptor.droppableId)
.sort((a, b) => a.descriptor.index - b.descriptor.index);
return result;
});
function tryGetDestination(impact) {
if (impact.at && impact.at.type === 'REORDER') {
return impact.at.destination;
}
return null;
}
function tryGetCombine(impact) {
if (impact.at && impact.at.type === 'COMBINE') {
return impact.at.combine;
}
return null;
}
var removeDraggableFromList = memoizeOne__default["default"]((remove, list) => list.filter(item => item.descriptor.id !== remove.descriptor.id));
var moveToNextCombine = (_ref => {
let {
isMovingForward,
draggable,
destination,
insideDestination,
previousImpact
} = _ref;
if (!destination.isCombineEnabled) {
return null;
}
const location = tryGetDestination(previousImpact);
if (!location) {
return null;
}
function getImpact(target) {
const at = {
type: 'COMBINE',
combine: {
draggableId: target,
droppableId: destination.descriptor.id
}
};
return {
...previousImpact,
at
};
}
const all = previousImpact.displaced.all;
const closestId = all.length ? all[0] : null;
if (isMovingForward) {
return closestId ? getImpact(closestId) : null;
}
const withoutDraggable = removeDraggableFromList(draggable, insideDestination);
if (!closestId) {
if (!withoutDraggable.length) {
return null;
}
const last = withoutDraggable[withoutDraggable.length - 1];
return getImpact(last.descriptor.id);
}
const indexOfClosest = withoutDraggable.findIndex(d => d.descriptor.id === closestId);
!(indexOfClosest !== -1) ? invariant(false, 'Could not find displaced item in set') : void 0;
const proposedIndex = indexOfClosest - 1;
if (proposedIndex < 0) {
return null;
}
const before = withoutDraggable[proposedIndex];
return getImpact(before.descriptor.id);
});
var isHomeOf = ((draggable, destination) => draggable.descriptor.droppableId === destination.descriptor.id);
const noDisplacedBy = {
point: origin,
value: 0
};
const emptyGroups = {
invisible: {},
visible: {},
all: []
};
const noImpact = {
displaced: emptyGroups,
displacedBy: noDisplacedBy,
at: null
};
var noImpact$1 = noImpact;
var isWithin = ((lowerBound, upperBound) => value => lowerBound <= value && value <= upperBound);
var isPartiallyVisibleThroughFrame = (frame => {
const isWithinVertical = isWithin(frame.top, frame.bottom);
const isWithinHorizontal = isWithin(frame.left, frame.right);
return subject => {
const isContained = isWithinVertical(subject.top) && isWithinVertical(subject.bottom) && isWithinHorizontal(subject.left) && isWithinHorizontal(subject.right);
if (isContained) {
return true;
}
const isPartiallyVisibleVertically = isWithinVertical(subject.top) || isWithinVertical(subject.bottom);
const isPartiallyVisibleHorizontally = isWithinHorizontal(subject.left) || isWithinHorizontal(subject.right);
const isPartiallyContained = isPartiallyVisibleVertically && isPartiallyVisibleHorizontally;
if (isPartiallyContained) {
return true;
}
const isBiggerVertically = subject.top < frame.top && subject.bottom > frame.bottom;
const isBiggerHorizontally = subject.left < frame.left && subject.right > frame.right;
const isTargetBiggerThanFrame = isBiggerVertically && isBiggerHorizontally;
if (isTargetBiggerThanFrame) {
return true;
}
const isTargetBiggerOnOneAxis = isBiggerVertically && isPartiallyVisibleHorizontally || isBiggerHorizontally && isPartiallyVisibleVertically;
return isTargetBiggerOnOneAxis;
};
});
var isTotallyVisibleThroughFrame = (frame => {
const isWithinVertical = isWithin(frame.top, frame.bottom);
const isWithinHorizontal = isWithin(frame.left, frame.right);
return subject => {
const isContained = isWithinVertical(subject.top) && isWithinVertical(subject.bottom) && isWithinHorizontal(subject.left) && isWithinHorizontal(subject.right);
return isContained;
};
});
const vertical = {
direction: 'vertical',
line: 'y',
crossAxisLine: 'x',
start: 'top',
end: 'bottom',
size: 'height',
crossAxisStart: 'left',
crossAxisEnd: 'right',
crossAxisSize: 'width'
};
const horizontal = {
direction: 'horizontal',
line: 'x',
crossAxisLine: 'y',
start: 'left',
end: 'right',
size: 'width',
crossAxisStart: 'top',
crossAxisEnd: 'bottom',
crossAxisSize: 'height'
};
var isTotallyVisibleThroughFrameOnAxis = (axis => frame => {
const isWithinVertical = isWithin(frame.top, frame.bottom);
const isWithinHorizontal = isWithin(frame.left, frame.right);
return subject => {
if (axis === vertical) {
return isWithinVertical(subject.top) && isWithinVertical(subject.bottom);
}
return isWithinHorizontal(subject.left) && isWithinHorizontal(subject.right);
};
});
const getDroppableDisplaced = (target, destination) => {
const displacement = destination.frame ? destination.frame.scroll.diff.displacement : origin;
return offsetByPosition(target, displacement);
};
const isVisibleInDroppable = (target, destination, isVisibleThroughFrameFn) => {
if (!destination.subject.active) {
return false;
}
return isVisibleThroughFrameFn(destination.subject.active)(target);
};
const isVisibleInViewport = (target, viewport, isVisibleThroughFrameFn) => isVisibleThroughFrameFn(viewport)(target);
const isVisible$1 = _ref => {
let {
target: toBeDisplaced,
destination,
viewport,
withDroppableDisplacement,
isVisibleThroughFrameFn
} = _ref;
const displacedTarget = withDroppableDisplacement ? getDroppableDisplaced(toBeDisplaced, destination) : toBeDisplaced;
return isVisibleInDroppable(displacedTarget, destination, isVisibleThroughFrameFn) && isVisibleInViewport(displacedTarget, viewport, isVisibleThroughFrameFn);
};
const isPartiallyVisible = args => isVisible$1({
...args,
isVisibleThroughFrameFn: isPartiallyVisibleThroughFrame
});
const isTotallyVisible = args => isVisible$1({
...args,
isVisibleThroughFrameFn: isTotallyVisibleThroughFrame
});
const isTotallyVisibleOnAxis = args => isVisible$1({
...args,
isVisibleThroughFrameFn: isTotallyVisibleThroughFrameOnAxis(args.destination.axis)
});
const getShouldAnimate = (id, last, forceShouldAnimate) => {
if (typeof forceShouldAnimate === 'boolean') {
return forceShouldAnimate;
}
if (!last) {
return true;
}
const {
invisible,
visible
} = last;
if (invisible[id]) {
return false;
}
const previous = visible[id];
return previous ? previous.shouldAnimate : true;
};
function getTarget(draggable, displacedBy) {
const marginBox = draggable.page.marginBox;
const expandBy = {
top: displacedBy.point.y,
right: 0,
bottom: 0,
left: displacedBy.point.x
};
return cssBoxModel.getRect(cssBoxModel.expand(marginBox, expandBy));
}
function getDisplacementGroups(_ref) {
let {
afterDragging,
destination,
displacedBy,
viewport,
forceShouldAnimate,
last
} = _ref;
return afterDragging.reduce(function process(groups, draggable) {
const target = getTarget(draggable, displacedBy);
const id = draggable.descriptor.id;
groups.all.push(id);
const isVisible = isPartiallyVisible({
target,
destination,
viewport,
withDroppableDisplacement: true
});
if (!isVisible) {
groups.invisible[draggable.descriptor.id] = true;
return groups;
}
const shouldAnimate = getShouldAnimate(id, last, forceShouldAnimate);
const displacement = {
draggableId: id,
shouldAnimate
};
groups.visible[id] = displacement;
return groups;
}, {
all: [],
visible: {},
invisible: {}
});
}
function getIndexOfLastItem(draggables, options) {
if (!draggables.length) {
return 0;
}
const indexOfLastItem = draggables[draggables.length - 1].descriptor.index;
return options.inHomeList ? indexOfLastItem : indexOfLastItem + 1;
}
function goAtEnd(_ref) {
let {
insideDestination,
inHomeList,
displacedBy,
destination
} = _ref;
const newIndex = getIndexOfLastItem(insideDestination, {
inHomeList
});
return {
displaced: emptyGroups,
displacedBy,
at: {
type: 'REORDER',
destination: {
droppableId: destination.descriptor.id,
index: newIndex
}
}
};
}
function calculateReorderImpact(_ref2) {
let {
draggable,
insideDestination,
destination,
viewport,
displacedBy,
last,
index,
forceShouldAnimate
} = _ref2;
const inHomeList = isHomeOf(draggable, destination);
if (index == null) {
return goAtEnd({
insideDestination,
inHomeList,
displacedBy,
destination
});
}
const match = insideDestination.find(item => item.descriptor.index === index);
if (!match) {
return goAtEnd({
insideDestination,
inHomeList,
displacedBy,
destination
});
}
const withoutDragging = removeDraggableFromList(draggable, insideDestination);
const sliceFrom = insideDestination.indexOf(match);
const impacted = withoutDragging.slice(sliceFrom);
const displaced = getDisplacementGroups({
afterDragging: impacted,
destination,
displacedBy,
last,
viewport: viewport.frame,
forceShouldAnimate
});
return {
displaced,
displacedBy,
at: {
type: 'REORDER',
destination: {
droppableId: destination.descriptor.id,
index
}
}
};
}
function didStartAfterCritical(draggableId, afterCritical) {
return Boolean(afterCritical.effected[draggableId]);
}
var fromCombine = (_ref => {
let {
isMovingForward,
destination,
draggables,
combine,
afterCritical
} = _ref;
if (!destination.isCombineEnabled) {
return null;
}
const combineId = combine.draggableId;
const combineWith = draggables[combineId];
const combineWithIndex = combineWith.descriptor.index;
const didCombineWithStartAfterCritical = didStartAfterCritical(combineId, afterCritical);
if (didCombineWithStartAfterCritical) {
if (isMovingForward) {
return combineWithIndex;
}
return combineWithIndex - 1;
}
if (isMovingForward) {
return combineWithIndex + 1;
}
return combineWithIndex;
});
var fromReorder = (_ref => {
let {
isMovingForward,
isInHomeList,
insideDestination,
location
} = _ref;
if (!insideDestination.length) {
return null;
}
const currentIndex = location.index;
const proposedIndex = isMovingForward ? currentIndex + 1 : currentIndex - 1;
const firstIndex = insideDestination[0].descriptor.index;
const lastIndex = insideDestination[insideDestination.length - 1].descriptor.index;
const upperBound = isInHomeList ? lastIndex : lastIndex + 1;
if (proposedIndex < firstIndex) {
return null;
}
if (proposedIndex > upperBound) {
return null;
}
return proposedIndex;
});
var moveToNextIndex = (_ref => {
let {
isMovingForward,
isInHomeList,
draggable,
draggables,
destination,
insideDestination,
previousImpact,
viewport,
afterCritical
} = _ref;
const wasAt = previousImpact.at;
!wasAt ? invariant(false, 'Cannot move in direction without previous impact location') : void 0;
if (wasAt.type === 'REORDER') {
const newIndex = fromReorder({
isMovingForward,
isInHomeList,
location: wasAt.destination,
insideDestination
});
if (newIndex == null) {
return null;
}
return calculateReorderImpact({
draggable,
insideDestination,
destination,
viewport,
last: previousImpact.displaced,
displacedBy: previousImpact.displacedBy,
index: newIndex
});
}
const newIndex = fromCombine({
isMovingForward,
destination,
displaced: previousImpact.displaced,
draggables,
combine: wasAt.combine,
afterCritical
});
if (newIndex == null) {
return null;
}
return calculateReorderImpact({
draggable,
insideDestination,
destination,
viewport,
last: previousImpact.displaced,
displacedBy: previousImpact.displacedBy,
index: newIndex
});
});
var getCombinedItemDisplacement = (_ref => {
let {
displaced,
afterCritical,
combineWith,
displacedBy
} = _ref;
const isDisplaced = Boolean(displaced.visible[combineWith] || displaced.invisible[combineWith]);
if (didStartAfterCritical(combineWith, afterCritical)) {
return isDisplaced ? origin : negate(displacedBy.point);
}
return isDisplaced ? displacedBy.point : origin;
});
var whenCombining = (_ref => {
let {
afterCritical,
impact,
draggables
} = _ref;
const combine = tryGetCombine(impact);
!combine ? invariant(false) : void 0;
const combineWith = combine.draggableId;
const center = draggables[combineWith].page.borderBox.center;
const displaceBy = getCombinedItemDisplacement({
displaced: impact.displaced,
afterCritical,
combineWith,
displacedBy: impact.displacedBy
});
return add(center, displaceBy);
});
const distanceFromStartToBorderBoxCenter = (axis, box) => box.margin[axis.start] + box.borderBox[axis.size] / 2;
const distanceFromEndToBorderBoxCenter = (axis, box) => box.margin[axis.end] + box.borderBox[axis.size] / 2;
const getCrossAxisBorderBoxCenter = (axis, target, isMoving) => target[axis.crossAxisStart] + isMoving.margin[axis.crossAxisStart] + isMoving.borderBox[axis.crossAxisSize] / 2;
const goAfter = _ref => {
let {
axis,
moveRelativeTo,
isMoving
} = _ref;
return patch(axis.line,
moveRelativeTo.marginBox[axis.end] + distanceFromStartToBorderBoxCenter(axis, isMoving), getCrossAxisBorderBoxCenter(axis, moveRelativeTo.marginBox, isMoving));
};
const goBefore = _ref2 => {
let {
axis,
moveRelativeTo,
isMoving
} = _ref2;
return patch(axis.line,
moveRelativeTo.marginBox[axis.start] - distanceFromEndToBorderBoxCenter(axis, isMoving), getCrossAxisBorderBoxCenter(axis, moveRelativeTo.marginBox, isMoving));
};
const goIntoStart = _ref3 => {
let {
axis,
moveInto,
isMoving
} = _ref3;
return patch(axis.line, moveInto.contentBox[axis.start] + distanceFromStartToBorderBoxCenter(axis, isMoving), getCrossAxisBorderBoxCenter(axis, moveInto.contentBox, isMoving));
};
var whenReordering = (_ref => {
let {
impact,
draggable,
draggables,
droppable,
afterCritical
} = _ref;
const insideDestination = getDraggablesInsideDroppable(droppable.descriptor.id, draggables);
const draggablePage = draggable.page;
const axis = droppable.axis;
if (!insideDestination.length) {
return goIntoStart({
axis,
moveInto: droppable.page,
isMoving: draggablePage
});
}
const {
displaced,
displacedBy
} = impact;
const closestAfter = displaced.all[0];
if (closestAfter) {
const closest = draggables[closestAfter];
if (didStartAfterCritical(closestAfter, afterCritical)) {
return goBefore({
axis,
moveRelativeTo: closest.page,
isMoving: draggablePage
});
}
const withDisplacement = cssBoxModel.offset(closest.page, displacedBy.point);
return goBefore({
axis,
moveRelativeTo: withDisplacement,
isMoving: draggablePage
});
}
const last = insideDestination[insideDestination.length - 1];
if (last.descriptor.id === draggable.descriptor.id) {
return draggablePage.borderBox.center;
}
if (didStartAfterCritical(last.descriptor.id, afterCritical)) {
const page = cssBoxModel.offset(last.page, negate(afterCritical.displacedBy.point));
return goAfter({
axis,
moveRelativeTo: page,
isMoving: draggablePage
});
}
return goAfter({
axis,
moveRelativeTo: last.page,
isMoving: draggablePage
});
});
var withDroppableDisplacement = ((droppable, point) => {
const frame = droppable.frame;
if (!frame) {
return point;
}
return add(point, frame.scroll.diff.displacement);
});
const getResultWithoutDroppableDisplacement = _ref => {
let {
impact,
draggable,
droppable,
draggables,
afterCritical
} = _ref;
const original = draggable.page.borderBox.center;
const at = impact.at;
if (!droppable) {
return original;
}
if (!at) {
return original;
}
if (at.type === 'REORDER') {
return whenReordering({
impact,
draggable,
draggables,
droppable,
afterCritical
});
}
return whenCombining({
impact,
draggables,
afterCritical
});
};
var getPageBorderBoxCenterFromImpact = (args => {
const withoutDisplacement = getResultWithoutDroppableDisplacement(args);
const droppable = args.droppable;
const withDisplacement = droppable ? withDroppableDisplacement(droppable, withoutDisplacement) : withoutDisplacement;
return withDisplacement;
});
var scrollViewport = ((viewport, newScroll) => {
const diff = subtract(newScroll, viewport.scroll.initial);
const displacement = negate(diff);
const frame = cssBoxModel.getRect({
top: newScroll.y,
bottom: newScroll.y + viewport.frame.height,
left: newScroll.x,
right: newScroll.x + viewport.frame.width
});
const updated = {
frame,
scroll: {
initial: viewport.scroll.initial,
max: viewport.scroll.max,
current: newScroll,
diff: {
value: diff,
displacement
}
}
};
return updated;
});
function getDraggables$1(ids, draggables) {
return ids.map(id => draggables[id]);
}
function tryGetVisible(id, groups) {
for (let i = 0; i < groups.length; i++) {
const displacement = groups[i].visible[id];
if (displacement) {
return displacement;
}
}
return null;
}
var speculativelyIncrease = (_ref => {
let {
impact,
viewport,
destination,
draggables,
maxScrollChange
} = _ref;
const scrolledViewport = scrollViewport(viewport, add(viewport.scroll.current, maxScrollChange));
const scrolledDroppable = destination.frame ? scrollDroppable(destination, add(destination.frame.scroll.current, maxScrollChange)) : destination;
const last = impact.displaced;
const withViewportScroll = getDisplacementGroups({
afterDragging: getDraggables$1(last.all, draggables),
destination,
displacedBy: impact.displacedBy,
viewport: scrolledViewport.frame,
last,
forceShouldAnimate: false
});
const withDroppableScroll = getDisplacementGroups({
afterDragging: getDraggables$1(last.all, draggables),
destination: scrolledDroppable,
displacedBy: impact.displacedBy,
viewport: viewport.frame,
last,
forceShouldAnimate: false
});
const invisible = {};
const visible = {};
const groups = [
last, withViewportScroll, withDroppableScroll];
last.all.forEach(id => {
const displacement = tryGetVisible(id, groups);
if (displacement) {
visible[id] = displacement;
return;
}
invisible[id] = true;
});
const newImpact = {
...impact,
displaced: {
all: last.all,
invisible,
visible
}
};
return newImpact;
});
var withViewportDisplacement = ((viewport, point) => add(viewport.scroll.diff.displacement, point));
var getClientFromPageBorderBoxCenter = (_ref => {
let {
pageBorderBoxCenter,
draggable,
viewport
} = _ref;
const withoutPageScrollChange = withViewportDisplacement(viewport, pageBorderBoxCenter);
const offset = subtract(withoutPageScrollChange, draggable.page.borderBox.center);
return add(draggable.client.borderBox.center, offset);
});
var isTotallyVisibleInNewLocation = (_ref => {
let {
draggable,
destination,
newPageBorderBoxCenter,
viewport,
withDroppableDisplacement,
onlyOnMainAxis = false
} = _ref;
const changeNeeded = subtract(newPageBorderBoxCenter, draggable.page.borderBox.center);
const shifted = offsetByPosition(draggable.page.borderBox, changeNeeded);
const args = {
target: shifted,
destination,
withDroppableDisplacement,
viewport
};
return onlyOnMainAxis ? isTotallyVisibleOnAxis(args) : isTotallyVisible(args);
});
var moveToNextPlace = (_ref => {
let {
isMovingForward,
draggable,
destination,
draggables,
previousImpact,
viewport,
previousPageBorderBoxCenter,
previousClientSelection,
afterCritical
} = _ref;
if (!destination.isEnabled) {
return null;
}
const insideDestination = getDraggablesInsideDroppable(destination.descriptor.id, draggables);
const isInHomeList = isHomeOf(draggable, destination);
const impact = moveToNextCombine({
isMovingForward,
draggable,
destination,
insideDestination,
previousImpact
}) || moveToNextIndex({
isMovingForward,
isInHomeList,
draggable,
draggables,
destination,
insideDestination,
previousImpact,
viewport,
afterCritical
});
if (!impact) {
return null;
}
const pageBorderBoxCenter = getPageBorderBoxCenterFromImpact({
impact,
draggable,
droppable: destination,
draggables,
afterCritical
});
const isVisibleInNewLocation = isTotallyVisibleInNewLocation({
draggable,
destination,
newPageBorderBoxCenter: pageBorderBoxCenter,
viewport: viewport.frame,
withDroppableDisplacement: false,
onlyOnMainAxis: true
});
if (isVisibleInNewLocation) {
const clientSelection = getClientFromPageBorderBoxCenter({
pageBorderBoxCenter,
draggable,
viewport
});
return {
clientSelection,
impact,
scrollJumpRequest: null
};
}
const distance = subtract(pageBorderBoxCenter, previousPageBorderBoxCenter);
const cautious = speculativelyIncrease({
impact,
viewport,
destination,
draggables,
maxScrollChange: distance
});
return {
clientSelection: previousClientSelection,
impact: cautious,
scrollJumpRequest: distance
};
});
const getKnownActive = droppable => {
const rect = droppable.subject.active;
!rect ? invariant(false, 'Cannot get clipped area from droppable') : void 0;
return rect;
};
var getBestCrossAxisDroppable = (_ref => {
let {
isMovingForward,
pageBorderBoxCenter,
source,
droppables,
viewport
} = _ref;
const active = source.subject.active;
if (!active) {
return null;
}
const axis = source.axis;
const isBetweenSourceClipped = isWithin(active[axis.start], active[axis.end]);
const candidates = toDroppableList(droppables)
.filter(droppable => droppable !== source)
.filter(droppable => droppable.isEnabled)
.filter(droppable => Boolean(droppable.subject.active))
.filter(droppable => isPartiallyVisibleThroughFrame(viewport.frame)(getKnownActive(droppable))).filter(droppable => {
const activeOfTarget = getKnownActive(droppable);
if (isMovingForward) {
return active[axis.crossAxisEnd] < activeOfTarget[axis.crossAxisEnd];
}
return activeOfTarget[axis.crossAxisStart] < active[axis.crossAxisStart];
})
.filter(droppable => {
const activeOfTarget = getKnownActive(droppable);
const isBetweenDestinationClipped = isWithin(activeOfTarget[axis.start], activeOfTarget[axis.end]);
return isBetweenSourceClipped(activeOfTarget[axis.start]) || isBetweenSourceClipped(activeOfTarget[axis.end]) || isBetweenDestinationClipped(active[axis.start]) || isBetweenDestinationClipped(active[axis.end]);
})
.sort((a, b) => {
const first = getKnownActive(a)[axis.crossAxisStart];
const second = getKnownActive(b)[axis.crossAxisStart];
if (isMovingForward) {
return first - second;
}
return second - first;
})
.filter((droppable, index, array) => getKnownActive(droppable)[axis.crossAxisStart] === getKnownActive(array[0])[axis.crossAxisStart]);
if (!candidates.length) {
return null;
}
if (candidates.length === 1) {
return candidates[0];
}
const contains = candidates.filter(droppable => {
const isWithinDroppable = isWithin(getKnownActive(droppable)[axis.start], getKnownActive(droppable)[axis.end]);
return isWithinDroppable(pageBorderBoxCenter[axis.line]);
});
if (contains.length === 1) {
return contains[0];
}
if (contains.length > 1) {
return contains.sort((a, b) => getKnownActive(a)[axis.start] - getKnownActive(b)[axis.start])[0];
}
return candidates.sort((a, b) => {
const first = closest$1(pageBorderBoxCenter, getCorners(getKnownActive(a)));
const second = closest$1(pageBorderBoxCenter, getCorners(getKnownActive(b)));
if (first !== second) {
return first - second;
}
return getKnownActive(a)[axis.start] - getKnownActive(b)[axis.start];
})[0];
});
const getCurrentPageBorderBoxCenter = (draggable, afterCritical) => {
const original = draggable.page.borderBox.center;
return didStartAfterCritical(draggable.descriptor.id, afterCritical) ? subtract(original, afterCritical.displacedBy.point) : original;
};
const getCurrentPageBorderBox = (draggable, afterCritical) => {
const original = draggable.page.borderBox;
return didStartAfterCritical(draggable.descriptor.id, afterCritical) ? offsetByPosition(original, negate(afterCritical.displacedBy.point)) : original;
};
var getClosestDraggable = (_ref => {
let {
pageBorderBoxCenter,
viewport,
destination,
insideDestination,
afterCritical
} = _ref;
const sorted = insideDestination.filter(draggable =>
isTotallyVisible({
target: getCurrentPageBorderBox(draggable, afterCritical),
destination,
viewport: viewport.frame,
withDroppableDisplacement: true
})).sort((a, b) => {
const distanceToA = distance(pageBorderBoxCenter, withDroppableDisplacement(destination, getCurrentPageBorderBoxCenter(a, afterCritical)));
const distanceToB = distance(pageBorderBoxCenter, withDroppableDisplacement(destination, getCurrentPageBorderBoxCenter(b, afterCritical)));
if (distanceToA < distanceToB) {
return -1;
}
if (distanceToB < distanceToA) {
return 1;
}
return a.descriptor.index - b.descriptor.index;
});
return sorted[0] || null;
});
var getDisplacedBy = memoizeOne__default["default"](function getDisplacedBy(axis, displaceBy) {
const displacement = displaceBy[axis.line];
return {
value: displacement,
point: patch(axis.line, displacement)
};
});
const getRequiredGrowthForPlaceholder = (droppable, placeholderSize, draggables) => {
const axis = droppable.axis;
if (droppable.descriptor.mode === 'virtual') {
return patch(axis.line, placeholderSize[axis.line]);
}
const availableSpace = droppable.subject.page.contentBox[axis.size];
const insideDroppable = getDraggablesInsideDroppable(droppable.descriptor.id, draggables);
const spaceUsed = insideDroppable.reduce((sum, dimension) => sum + dimension.client.marginBox[axis.size], 0);
const requiredSpace = spaceUsed + placeholderSize[axis.line];
const needsToGrowBy = requiredSpace - availableSpace;
if (needsToGrowBy <= 0) {
return null;
}
return patch(axis.line, needsToGrowBy);
};
const withMaxScroll = (frame, max) => ({
...frame,
scroll: {
...frame.scroll,
max
}
});
const addPlaceholder = (droppable, draggable, draggables) => {
const frame = droppable.frame;
!!isHomeOf(draggable, droppable) ? invariant(false, 'Should not add placeholder space to home list') : void 0;
!!droppable.subject.withPlaceholder ? invariant(false, 'Cannot add placeholder size to a subject when it already has one') : void 0;
const placeholderSize = getDisplacedBy(droppable.axis, draggable.displaceBy).point;
const requiredGrowth = getRequiredGrowthForPlaceholder(droppable, placeholderSize, draggables);
const added = {
placeholderSize,
increasedBy: requiredGrowth,
oldFrameMaxScroll: droppable.frame ? droppable.frame.scroll.max : null
};
if (!frame) {
const subject = getSubject({
page: droppable.subject.page,
withPlaceholder: added,
axis: droppable.axis,
frame: droppable.frame
});
return {
...droppable,
subject
};
}
const maxScroll = requiredGrowth ? add(frame.scroll.max, requiredGrowth) : frame.scroll.max;
const newFrame = withMaxScroll(frame, maxScroll);
const subject = getSubject({
page: droppable.subject.page,
withPlaceholder: added,
axis: droppable.axis,
frame: newFrame
});
return {
...droppable,
subject,
frame: newFrame
};
};
const removePlaceholder = droppable => {
const added = droppable.subject.withPlaceholder;
!added ? invariant(false, 'Cannot remove placeholder form subject when there was none') : void 0;
const frame = droppable.frame;
if (!frame) {
const subject = getSubject({
page: droppable.subject.page,
axis: droppable.axis,
frame: null,
withPlaceholder: null
});
return {
...droppable,
subject
};
}
const oldMaxScroll = added.oldFrameMaxScroll;
!oldMaxScroll ? invariant(false, 'Expected droppable with frame to have old max frame scroll when removing placeholder') : void 0;
const newFrame = withMaxScroll(frame, oldMaxScroll);
const subject = getSubject({
page: droppable.subject.page,
axis: droppable.axis,
frame: newFrame,
withPlaceholder: null
});
return {
...droppable,
subject,
frame: newFrame
};
};
var moveToNewDroppable = (_ref => {
let {
previousPageBorderBoxCenter,
moveRelativeTo,
insideDestination,
draggable,
draggables,
destination,
viewport,
afterCritical
} = _ref;
if (!moveRelativeTo) {
if (insideDestination.length) {
return null;
}
const proposed = {
displaced: emptyGroups,
displacedBy: noDisplacedBy,
at: {
type: 'REORDER',
destination: {
droppableId: destination.descriptor.id,
index: 0
}
}
};
const proposedPageBorderBoxCenter = getPageBorderBoxCenterFromImpact({
impact: proposed,
draggable,
droppable: destination,
draggables,
afterCritical
});
const withPlaceholder = isHomeOf(draggable, destination) ? destination : addPlaceholder(destination, draggable, draggables);
const isVisibleInNewLocation = isTotallyVisibleInNewLocation({
draggable,
destination: withPlaceholder,
newPageBorderBoxCenter: proposedPageBorderBoxCenter,
viewport: viewport.frame,
withDroppableDisplacement: false,
onlyOnMainAxis: true
});
return isVisibleInNewLocation ? proposed : null;
}
const isGoingBeforeTarget = Boolean(
previousPageBorderBoxCenter[destination.axis.line] <= moveRelativeTo.page.borderBox.center[destination.axis.line]);
const proposedIndex = (() => {
const relativeTo = moveRelativeTo.descriptor.index;
if (moveRelativeTo.descriptor.id === draggable.descriptor.id) {
return relativeTo;
}
if (isGoingBeforeTarget) {
return relativeTo;
}
return relativeTo + 1;
})();
const displacedBy = getDisplacedBy(destination.axis, draggable.displaceBy);
return calculateReorderImpact({
draggable,
insideDestination,
destination,
viewport,
displacedBy,
last: emptyGroups,
index: proposedIndex
});
});
var moveCrossAxis = (_ref => {
let {
isMovingForward,
previousPageBorderBoxCenter,
draggable,
isOver,
draggables,
droppables,
viewport,
afterCritical
} = _ref;
const destination = getBestCrossAxisDroppable({
isMovingForward,
pageBorderBoxCenter: previousPageBorderBoxCenter,
source: isOver,
droppables,
viewport
});
if (!destination) {
return null;
}
const insideDestination = getDraggablesInsideDroppable(destination.descriptor.id, draggables);
const moveRelativeTo = getClosestDraggable({
pageBorderBoxCenter: previousPageBorderBoxCenter,
viewport,
destination,
insideDestination,
afterCritical
});
const impact = moveToNewDroppable({
previousPageBorderBoxCenter,
destination,
draggable,
draggables,
moveRelativeTo,
insideDestination,
viewport,
afterCritical
});
if (!impact) {
return null;
}
const pageBorderBoxCenter = getPageBorderBoxCenterFromImpact({
impact,
draggable,
droppable: destination,
draggables,
afterCritical
});
const clientSelection = getClientFromPageBorderBoxCenter({
pageBorderBoxCenter,
draggable,
viewport
});
return {
clientSelection,
impact,
scrollJumpRequest: null
};
});
var whatIsDraggedOver = (impact => {
const at = impact.at;
if (!at) {
return null;
}
if (at.type === 'REORDER') {
return at.destination.droppableId;
}
return at.combine.droppableId;
});
const getDroppableOver$1 = (impact, droppables) => {
const id = whatIsDraggedOver(impact);
return id ? droppables[id] : null;
};
var moveInDirection = (_ref => {
let {
state,
type
} = _ref;
const isActuallyOver = getDroppableOver$1(state.impact, state.dimensions.droppables);
const isMainAxisMovementAllowed = Boolean(isActuallyOver);
const home = state.dimensions.droppables[state.critical.droppable.id];
const isOver = isActuallyOver || home;
const direction = isOver.axis.direction;
const isMovingOnMainAxis = direction === 'vertical' && (type === 'MOVE_UP' || type === 'MOVE_DOWN') || direction === 'horizontal' && (type === 'MOVE_LEFT' || type === 'MOVE_RIGHT');
if (isMovingOnMainAxis && !isMainAxisMovementAllowed) {
return null;
}
const isMovingForward = type === 'MOVE_DOWN' || type === 'MOVE_RIGHT';
const draggable = state.dimensions.draggables[state.critical.draggable.id];
const previousPageBorderBoxCenter = state.current.page.borderBoxCenter;
const {
draggables,
droppables
} = state.dimensions;
return isMovingOnMainAxis ? moveToNextPlace({
isMovingForward,
previousPageBorderBoxCenter,
draggable,
destination: isOver,
draggables,
viewport: state.viewport,
previousClientSelection: state.current.client.selection,
previousImpact: state.impact,
afterCritical: state.afterCritical
}) : moveCrossAxis({
isMovingForward,
previousPageBorderBoxCenter,
draggable,
isOver,
draggables,
droppables,
viewport: state.viewport,
afterCritical: state.afterCritical
});
});
function isMovementAllowed(state) {
return state.phase === 'DRAGGING' || state.phase === 'COLLECTING';
}
function isPositionInFrame(frame) {
const isWithinVertical = isWithin(frame.top, frame.bottom);
const isWithinHorizontal = isWithin(frame.left, frame.right);
return function run(point) {
return isWithinVertical(point.y) && isWithinHorizontal(point.x);
};
}
function getHasOverlap(first, second) {
return first.left < second.right && first.right > second.left && first.top < second.bottom && first.bottom > second.top;
}
function getFurthestAway(_ref) {
let {
pageBorderBox,
draggable,
candidates
} = _ref;
const startCenter = draggable.page.borderBox.center;
const sorted = candidates.map(candidate => {
const axis = candidate.axis;
const target = patch(candidate.axis.line,
pageBorderBox.center[axis.line],
candidate.page.borderBox.center[axis.crossAxisLine]);
return {
id: candidate.descriptor.id,
distance: distance(startCenter, target)
};
})
.sort((a, b) => b.distance - a.distance);
return sorted[0] ? sorted[0].id : null;
}
function getDroppableOver(_ref2) {
let {
pageBorderBox,
draggable,
droppables
} = _ref2;
const candidates = toDroppableList(droppables).filter(item => {
if (!item.isEnabled) {
return false;
}
const active = item.subject.active;
if (!active) {
return false;
}
if (!getHasOverlap(pageBorderBox, active)) {
return false;
}
if (isPositionInFrame(active)(pageBorderBox.center)) {
return true;
}
const axis = item.axis;
const childCenter = active.center[axis.crossAxisLine];
const crossAxisStart = pageBorderBox[axis.crossAxisStart];
const crossAxisEnd = pageBorderBox[axis.crossAxisEnd];
const isContained = isWithin(active[axis.crossAxisStart], active[axis.crossAxisEnd]);
const isStartContained = isContained(crossAxisStart);
const isEndContained = isContained(crossAxisEnd);
if (!isStartContained && !isEndContained) {
return true;
}
if (isStartContained) {
return crossAxisStart < childCenter;
}
return crossAxisEnd > childCenter;
});
if (!candidates.length) {
return null;
}
if (candidates.length === 1) {
return candidates[0].descriptor.id;
}
return getFurthestAway({
pageBorderBox,
draggable,
candidates
});
}
const offsetRectByPosition = (rect, point) => cssBoxModel.getRect(offsetByPosition(rect, point));
var withDroppableScroll = ((droppable, area) => {
const frame = droppable.frame;
if (!frame) {
return area;
}
return offsetRectByPosition(area, frame.scroll.diff.value);
});
function getIsDisplaced(_ref) {
let {
displaced,
id
} = _ref;
return Boolean(displaced.visible[id] || displaced.invisible[id]);
}
function atIndex(_ref) {
let {
draggable,
closest,
inHomeList
} = _ref;
if (!closest) {
return null;
}
if (!inHomeList) {
return closest.descriptor.index;
}
if (closest.descriptor.index > draggable.descriptor.index) {
return closest.descriptor.index - 1;
}
return closest.descriptor.index;
}
var getReorderImpact = (_ref2 => {
let {
pageBorderBoxWithDroppableScroll: targetRect,
draggable,
destination,
insideDestination,
last,
viewport,
afterCritical
} = _ref2;
const axis = destination.axis;
const displacedBy = getDisplacedBy(destination.axis, draggable.displaceBy);
const displacement = displacedBy.value;
const targetStart = targetRect[axis.start];
const targetEnd = targetRect[axis.end];
const withoutDragging = removeDraggableFromList(draggable, insideDestination);
const closest = withoutDragging.find(child => {
const id = child.descriptor.id;
const childCenter = child.page.borderBox.center[axis.line];
const didStartAfterCritical$1 = didStartAfterCritical(id, afterCritical);
const isDisplaced = getIsDisplaced({
displaced: last,
id
});
if (didStartAfterCritical$1) {
if (isDisplaced) {
return targetEnd <= childCenter;
}
return targetStart < childCenter - displacement;
}
if (isDisplaced) {
return targetEnd <= childCenter + displacement;
}
return targetStart < childCenter;
}) || null;
const newIndex = atIndex({
draggable,
closest,
inHomeList: isHomeOf(draggable, destination)
});
return calculateReorderImpact({
draggable,
insideDestination,
destination,
viewport,
last,
displacedBy,
index: newIndex
});
});
const combineThresholdDivisor = 4;
var getCombineImpact = (_ref => {
let {
draggable,
pageBorderBoxWithDroppableScroll: targetRect,
previousImpact,
destination,
insideDestination,
afterCritical
} = _ref;
if (!destination.isCombineEnabled) {
return null;
}
const axis = destination.axis;
const displacedBy = getDisplacedBy(destination.axis, draggable.displaceBy);
const displacement = displacedBy.value;
const targetStart = targetRect[axis.start];
const targetEnd = targetRect[axis.end];
const withoutDragging = removeDraggableFromList(draggable, insideDestination);
const combineWith = withoutDragging.find(child => {
const id = child.descriptor.id;
const childRect = child.page.borderBox;
const childSize = childRect[axis.size];
const threshold = childSize / combineThresholdDivisor;
const didStartAfterCritical$1 = didStartAfterCritical(id, afterCritical);
const isDisplaced = getIsDisplaced({
displaced: previousImpact.displaced,
id
});
if (didStartAfterCritical$1) {
if (isDisplaced) {
return targetEnd > childRect[axis.start] + threshold && targetEnd < childRect[axis.end] - threshold;
}
return targetStart > childRect[axis.start] - displacement + threshold && targetStart < childRect[axis.end] - displacement - threshold;
}
if (isDisplaced) {
return targetEnd > childRect[axis.start] + displacement + threshold && targetEnd < childRect[axis.end] + displacement - threshold;
}
return targetStart > childRect[axis.start] + threshold && targetStart < childRect[axis.end] - threshold;
});
if (!combineWith) {
return null;
}
const impact = {
displacedBy,
displaced: previousImpact.displaced,
at: {
type: 'COMBINE',
combine: {
draggableId: combineWith.descriptor.id,
droppableId: destination.descriptor.id
}
}
};
return impact;
});
var getDragImpact = (_ref => {
let {
pageOffset,
draggable,
draggables,
droppables,
previousImpact,
viewport,
afterCritical
} = _ref;
const pageBorderBox = offsetRectByPosition(draggable.page.borderBox, pageOffset);
const destinationId = getDroppableOver({
pageBorderBox,
draggable,
droppables
});
if (!destinationId) {
return noImpact$1;
}
const destination = droppables[destinationId];
const insideDestination = getDraggablesInsideDroppable(destination.descriptor.id, draggables);
const pageBorderBoxWithDroppableScroll = withDroppableScroll(destination, pageBorderBox);
return getCombineImpact({
pageBorderBoxWithDroppableScroll,
draggable,
previousImpact,
destination,
insideDestination,
afterCritical
}) || getReorderImpact({
pageBorderBoxWithDroppableScroll,
draggable,
destination,
insideDestination,
last: previousImpact.displaced,
viewport,
afterCritical
});
});
var patchDroppableMap = ((droppables, updated) => ({
...droppables,
[updated.descriptor.id]: updated
}));
const clearUnusedPlaceholder = _ref => {
let {
previousImpact,
impact,
droppables
} = _ref;
const last = whatIsDraggedOver(previousImpact);
const now = whatIsDraggedOver(impact);
if (!last) {
return droppables;
}
if (last === now) {
return droppables;
}
const lastDroppable = droppables[last];
if (!lastDroppable.subject.withPlaceholder) {
return droppables;
}
const updated = removePlaceholder(lastDroppable);
return patchDroppableMap(droppables, updated);
};
var recomputePlaceholders = (_ref2 => {
let {
draggable,
draggables,
droppables,
previousImpact,
impact
} = _ref2;
const cleaned = clearUnusedPlaceholder({
previousImpact,
impact,
droppables
});
const isOver = whatIsDraggedOver(impact);
if (!isOver) {
return cleaned;
}
const droppable = droppables[isOver];
if (isHomeOf(draggable, droppable)) {
return cleaned;
}
if (droppable.subject.withPlaceholder) {
return cleaned;
}
const patched = addPlaceholder(droppable, draggable, draggables);
return patchDroppableMap(cleaned, patched);
});
var update = (_ref => {
let {
state,
clientSelection: forcedClientSelection,
dimensions: forcedDimensions,
viewport: forcedViewport,
impact: forcedImpact,
scrollJumpRequest
} = _ref;
const viewport = forcedViewport || state.viewport;
const dimensions = forcedDimensions || state.dimensions;
const clientSelection = forcedClientSelection || state.current.client.selection;
const offset = subtract(clientSelection, state.initial.client.selection);
const client = {
offset,
selection: clientSelection,
borderBoxCenter: add(state.initial.client.borderBoxCenter, offset)
};
const page = {
selection: add(client.selection, viewport.scroll.current),
borderBoxCenter: add(client.borderBoxCenter, viewport.scroll.current),
offset: add(client.offset, viewport.scroll.diff.value)
};
const current = {
client,
page
};
if (state.phase === 'COLLECTING') {
return {
...state,
dimensions,
viewport,
current
};
}
const draggable = dimensions.draggables[state.critical.draggable.id];
const newImpact = forcedImpact || getDragImpact({
pageOffset: page.offset,
draggable,
draggables: dimensions.draggables,
droppables: dimensions.droppables,
previousImpact: state.impact,
viewport,
afterCritical: state.afterCritical
});
const withUpdatedPlaceholders = recomputePlaceholders({
draggable,
impact: newImpact,
previousImpact: state.impact,
draggables: dimensions.draggables,
droppables: dimensions.droppables
});
const result = {
...state,
current,
dimensions: {
draggables: dimensions.draggables,
droppables: withUpdatedPlaceholders
},
impact: newImpact,
viewport,
scrollJumpRequest: scrollJumpRequest || null,
forceShouldAnimate: scrollJumpRequest ? false : null
};
return result;
});
function getDraggables(ids, draggables) {
return ids.map(id => draggables[id]);
}
var recompute = (_ref => {
let {
impact,
viewport,
draggables,
destination,
forceShouldAnimate
} = _ref;
const last = impact.displaced;
const afterDragging = getDraggables(last.all, draggables);
const displaced = getDisplacementGroups({
afterDragging,
destination,
displacedBy: impact.displacedBy,
viewport: viewport.frame,
forceShouldAnimate,
last
});
return {
...impact,
displaced
};
});
var getClientBorderBoxCenter = (_ref => {
let {
impact,
draggable,
droppable,
draggables,
viewport,
afterCritical
} = _ref;
const pageBorderBoxCenter = getPageBorderBoxCenterFromImpact({
impact,
draggable,
draggables,
droppable,
afterCritical
});
return getClientFromPageBorderBoxCenter({
pageBorderBoxCenter,
draggable,
viewport
});
});
var refreshSnap = (_ref => {
let {
state,
dimensions: forcedDimensions,
viewport: forcedViewport
} = _ref;
!(state.movementMode === 'SNAP') ? invariant(false) : void 0;
const needsVisibilityCheck = state.impact;
const viewport = forcedViewport || state.viewport;
const dimensions = forcedDimensions || state.dimensions;
const {
draggables,
droppables
} = dimensions;
const draggable = draggables[state.critical.draggable.id];
const isOver = whatIsDraggedOver(needsVisibilityCheck);
!isOver ? invariant(false, 'Must be over a destination in SNAP movement mode') : void 0;
const destination = droppables[isOver];
const impact = recompute({
impact: needsVisibilityCheck,
viewport,
destination,
draggables
});
const clientSelection = getClientBorderBoxCenter({
impact,
draggable,
droppable: destination,
draggables,
viewport,
afterCritical: state.afterCritical
});
return update({
impact,
clientSelection,
state,
dimensions,
viewport
});
});
var getHomeLocation = (descriptor => ({
index: descriptor.index,
droppableId: descriptor.droppableId
}));
var getLiftEffect = (_ref => {
let {
draggable,
home,
draggables,
viewport
} = _ref;
const displacedBy = getDisplacedBy(home.axis, draggable.displaceBy);
const insideHome = getDraggablesInsideDroppable(home.descriptor.id, draggables);
const rawIndex = insideHome.indexOf(draggable);
!(rawIndex !== -1) ? invariant(false, 'Expected draggable to be inside home list') : void 0;
const afterDragging = insideHome.slice(rawIndex + 1);
const effected = afterDragging.reduce((previous, item) => {
previous[item.descriptor.id] = true;
return previous;
}, {});
const afterCritical = {
inVirtualList: home.descriptor.mode === 'virtual',
displacedBy,
effected
};
const displaced = getDisplacementGroups({
afterDragging,
destination: home,
displacedBy,
last: null,
viewport: viewport.frame,
forceShouldAnimate: false
});
const impact = {
displaced,
displacedBy,
at: {
type: 'REORDER',
destination: getHomeLocation(draggable.descriptor)
}
};
return {
impact,
afterCritical
};
});
var patchDimensionMap = ((dimensions, updated) => ({
draggables: dimensions.draggables,
droppables: patchDroppableMap(dimensions.droppables, updated)
}));
var offsetDraggable = (_ref => {
let {
draggable,
offset,
initialWindowScroll
} = _ref;
const client = cssBoxModel.offset(draggable.client, offset);
const page = cssBoxModel.withScroll(client, initialWindowScroll);
const moved = {
...draggable,
placeholder: {
...draggable.placeholder,
client
},
client,
page
};
return moved;
});
var getFrame = (droppable => {
const frame = droppable.frame;
!frame ? invariant(false, 'Expected Droppable to have a frame') : void 0;
return frame;
});
var adjustAdditionsForScrollChanges = (_ref => {
let {
additions,
updatedDroppables,
viewport
} = _ref;
const windowScrollChange = viewport.scroll.diff.value;
return additions.map(draggable => {
const droppableId = draggable.descriptor.droppableId;
const modified = updatedDroppables[droppableId];
const frame = getFrame(modified);
const droppableScrollChange = frame.scroll.diff.value;
const totalChange = add(windowScrollChange, droppableScrollChange);
const moved = offsetDraggable({
draggable,
offset: totalChange,
initialWindowScroll: viewport.scroll.initial
});
return moved;
});
});
var publishWhileDraggingInVirtual = (_ref => {
let {
state,
published
} = _ref;
const withScrollChange = published.modified.map(update => {
const existing = state.dimensions.droppables[update.droppableId];
const scrolled = scrollDroppable(existing, update.scroll);
return scrolled;
});
const droppables = {
...state.dimensions.droppables,
...toDroppableMap(withScrollChange)
};
const updatedAdditions = toDraggableMap(adjustAdditionsForScrollChanges({
additions: published.additions,
updatedDroppables: droppables,
viewport: state.viewport
}));
const draggables = {
...state.dimensions.draggables,
...updatedAdditions
};
published.removals.forEach(id => {
delete draggables[id];
});
const dimensions = {
droppables,
draggables
};
const wasOverId = whatIsDraggedOver(state.impact);
const wasOver = wasOverId ? dimensions.droppables[wasOverId] : null;
const draggable = dimensions.draggables[state.critical.draggable.id];
const home = dimensions.droppables[state.critical.droppable.id];
const {
impact: onLiftImpact,
afterCritical
} = getLiftEffect({
draggable,
home,
draggables,
viewport: state.viewport
});
const previousImpact = wasOver && wasOver.isCombineEnabled ?
state.impact : onLiftImpact;
const impact = getDragImpact({
pageOffset: state.current.page.offset,
draggable: dimensions.draggables[state.critical.draggable.id],
draggables: dimensions.draggables,
droppables: dimensions.droppables,
previousImpact,
viewport: state.viewport,
afterCritical
});
const draggingState = {
...state,
phase: 'DRAGGING',
impact,
onLiftImpact,
dimensions,
afterCritical,
forceShouldAnimate: false
};
if (state.phase === 'COLLECTING') {
return draggingState;
}
const dropPending = {
...draggingState,
phase: 'DROP_PENDING',
reason: state.reason,
isWaiting: false
};
return dropPending;
});
const isSnapping = state => state.movementMode === 'SNAP';
const postDroppableChange = (state, updated, isEnabledChanging) => {
const dimensions = patchDimensionMap(state.dimensions, updated);
if (!isSnapping(state) || isEnabledChanging) {
return update({
state,
dimensions
});
}
return refreshSnap({
state,
dimensions
});
};
function removeScrollJumpRequest(state) {
if (state.isDragging && state.movementMode === 'SNAP') {
return {
...state,
scrollJumpRequest: null
};
}
return state;
}
const idle$2 = {
phase: 'IDLE',
completed: null,
shouldFlush: false
};
var reducer$1 = (function (state, action) {
if (state === void 0) {
state = idle$2;
}
if (action.type === 'FLUSH') {
return {
...idle$2,
shouldFlush: true
};
}
if (action.type === 'INITIAL_PUBLISH') {
!(state.phase === 'IDLE') ? invariant(false, 'INITIAL_PUBLISH must come after a IDLE phase') : void 0;
const {
critical,
clientSelection,
viewport,
dimensions,
movementMode
} = action.payload;
const draggable = dimensions.draggables[critical.draggable.id];
const home = dimensions.droppables[critical.droppable.id];
const client = {
selection: clientSelection,
borderBoxCenter: draggable.client.borderBox.center,
offset: origin
};
const initial = {
client,
page: {
selection: add(client.selection, viewport.scroll.initial),
borderBoxCenter: add(client.selection, viewport.scroll.initial),
offset: add(client.selection, viewport.scroll.diff.value)
}
};
const isWindowScrollAllowed = toDroppableList(dimensions.droppables).every(item => !item.isFixedOnPage);
const {
impact,
afterCritical
} = getLiftEffect({
draggable,
home,
draggables: dimensions.draggables,
viewport
});
const result = {
phase: 'DRAGGING',
isDragging: true,
critical,
movementMode,
dimensions,
initial,
current: initial,
isWindowScrollAllowed,
impact,
afterCritical,
onLiftImpact: impact,
viewport,
scrollJumpRequest: null,
forceShouldAnimate: null
};
return result;
}
if (action.type === 'COLLECTION_STARTING') {
if (state.phase === 'COLLECTING' || state.phase === 'DROP_PENDING') {
return state;
}
!(state.phase === 'DRAGGING') ? invariant(false, `Collection cannot start from phase ${state.phase}`) : void 0;
const result = {
...state,
phase: 'COLLECTING'
};
return result;
}
if (action.type === 'PUBLISH_WHILE_DRAGGING') {
!(state.phase === 'COLLECTING' || state.phase === 'DROP_PENDING') ? invariant(false, `Unexpected ${action.type} received in phase ${state.phase}`) : void 0;
return publishWhileDraggingInVirtual({
state,
published: action.payload
});
}
if (action.type === 'MOVE') {
if (state.phase === 'DROP_PENDING') {
return state;
}
!isMovementAllowed(state) ? invariant(false, `${action.type} not permitted in phase ${state.phase}`) : void 0;
const {
client: clientSelection
} = action.payload;
if (isEqual$1(clientSelection, state.current.client.selection)) {
return state;
}
return update({
state,
clientSelection,
impact: isSnapping(state) ? state.impact : null
});
}
if (action.type === 'UPDATE_DROPPABLE_SCROLL') {
if (state.phase === 'DROP_PENDING') {
return removeScrollJumpRequest(state);
}
if (state.phase === 'COLLECTING') {
return removeScrollJumpRequest(state);
}
!isMovementAllowed(state) ? invariant(false, `${action.type} not permitted in phase ${state.phase}`) : void 0;
const {
id,
newScroll
} = action.payload;
const target = state.dimensions.droppables[id];
if (!target) {
return state;
}
const scrolled = scrollDroppable(target, newScroll);
return postDroppableChange(state, scrolled, false);
}
if (action.type === 'UPDATE_DROPPABLE_IS_ENABLED') {
if (state.phase === 'DROP_PENDING') {
return state;
}
!isMovementAllowed(state) ? invariant(false, `Attempting to move in an unsupported phase ${state.phase}`) : void 0;
const {
id,
isEnabled
} = action.payload;
const target = state.dimensions.droppables[id];
!target ? invariant(false, `Cannot find Droppable[id: ${id}] to toggle its enabled state`) : void 0;
!(target.isEnabled !== isEnabled) ? invariant(false, `Trying to set droppable isEnabled to ${String(isEnabled)}
but it is already ${String(target.isEnabled)}`) : void 0;
const updated = {
...target,
isEnabled
};
return postDroppableChange(state, updated, true);
}
if (action.type === 'UPDATE_DROPPABLE_IS_COMBINE_ENABLED') {
if (state.phase === 'DROP_PENDING') {
return state;
}
!isMovementAllowed(state) ? invariant(false, `Attempting to move in an unsupported phase ${state.phase}`) : void 0;
const {
id,
isCombineEnabled
} = action.payload;
const target = state.dimensions.droppables[id];
!target ? invariant(false, `Cannot find Droppable[id: ${id}] to toggle its isCombineEnabled state`) : void 0;
!(target.isCombineEnabled !== isCombineEnabled) ? invariant(false, `Trying to set droppable isCombineEnabled to ${String(isCombineEnabled)}
but it is already ${String(target.isCombineEnabled)}`) : void 0;
const updated = {
...target,
isCombineEnabled
};
return postDroppableChange(state, updated, true);
}
if (action.type === 'MOVE_BY_WINDOW_SCROLL') {
if (state.phase === 'DROP_PENDING' || state.phase === 'DROP_ANIMATING') {
return state;
}
!isMovementAllowed(state) ? invariant(false, `Cannot move by window in phase ${state.phase}`) : void 0;
!state.isWindowScrollAllowed ? invariant(false, 'Window scrolling is currently not supported for fixed lists') : void 0;
const newScroll = action.payload.newScroll;
if (isEqual$1(state.viewport.scroll.current, newScroll)) {
return removeScrollJumpRequest(state);
}
const viewport = scrollViewport(state.viewport, newScroll);
if (isSnapping(state)) {
return refreshSnap({
state,
viewport
});
}
return update({
state,
viewport
});
}
if (action.type === 'UPDATE_VIEWPORT_MAX_SCROLL') {
if (!isMovementAllowed(state)) {
return state;
}
const maxScroll = action.payload.maxScroll;
if (isEqual$1(maxScroll, state.viewport.scroll.max)) {
return state;
}
const withMaxScroll = {
...state.viewport,
scroll: {
...state.viewport.scroll,
max: maxScroll
}
};
return {
...state,
viewport: withMaxScroll
};
}
if (action.type === 'MOVE_UP' || action.type === 'MOVE_DOWN' || action.type === 'MOVE_LEFT' || action.type === 'MOVE_RIGHT') {
if (state.phase === 'COLLECTING' || state.phase === 'DROP_PENDING') {
return state;
}
!(state.phase === 'DRAGGING') ? invariant(false, `${action.type} received while not in DRAGGING phase`) : void 0;
const result = moveInDirection({
state,
type: action.type
});
if (!result) {
return state;
}
return update({
state,
impact: result.impact,
clientSelection: result.clientSelection,
scrollJumpRequest: result.scrollJumpRequest
});
}
if (action.type === 'DROP_PENDING') {
const reason = action.payload.reason;
!(state.phase === 'COLLECTING') ? invariant(false, 'Can only move into the DROP_PENDING phase from the COLLECTING phase') : void 0;
const newState = {
...state,
phase: 'DROP_PENDING',
isWaiting: true,
reason
};
return newState;
}
if (action.type === 'DROP_ANIMATE') {
const {
completed,
dropDuration,
newHomeClientOffset
} = action.payload;
!(state.phase === 'DRAGGING' || state.phase === 'DROP_PENDING') ? invariant(false, `Cannot animate drop from phase ${state.phase}`) : void 0;
const result = {
phase: 'DROP_ANIMATING',
completed,
dropDuration,
newHomeClientOffset,
dimensions: state.dimensions
};
return result;
}
if (action.type === 'DROP_COMPLETE') {
const {
completed
} = action.payload;
return {
phase: 'IDLE',
completed,
shouldFlush: false
};
}
return state;
});
const beforeInitialCapture = args => ({
type: 'BEFORE_INITIAL_CAPTURE',
payload: args
});
const lift$1 = args => ({
type: 'LIFT',
payload: args
});
const initialPublish = args => ({
type: 'INITIAL_PUBLISH',
payload: args
});
const publishWhileDragging = args => ({
type: 'PUBLISH_WHILE_DRAGGING',
payload: args
});
const collectionStarting = () => ({
type: 'COLLECTION_STARTING',
payload: null
});
const updateDroppableScroll = args => ({
type: 'UPDATE_DROPPABLE_SCROLL',
payload: args
});
const updateDroppableIsEnabled = args => ({
type: 'UPDATE_DROPPABLE_IS_ENABLED',
payload: args
});
const updateDroppableIsCombineEnabled = args => ({
type: 'UPDATE_DROPPABLE_IS_COMBINE_ENABLED',
payload: args
});
const move = args => ({
type: 'MOVE',
payload: args
});
const moveByWindowScroll = args => ({
type: 'MOVE_BY_WINDOW_SCROLL',
payload: args
});
const updateViewportMaxScroll = args => ({
type: 'UPDATE_VIEWPORT_MAX_SCROLL',
payload: args
});
const moveUp = () => ({
type: 'MOVE_UP',
payload: null
});
const moveDown = () => ({
type: 'MOVE_DOWN',
payload: null
});
const moveRight = () => ({
type: 'MOVE_RIGHT',
payload: null
});
const moveLeft = () => ({
type: 'MOVE_LEFT',
payload: null
});
const flush = () => ({
type: 'FLUSH',
payload: null
});
const animateDrop = args => ({
type: 'DROP_ANIMATE',
payload: args
});
const completeDrop = args => ({
type: 'DROP_COMPLETE',
payload: args
});
const drop$1 = args => ({
type: 'DROP',
payload: args
});
const dropPending = args => ({
type: 'DROP_PENDING',
payload: args
});
const dropAnimationFinished = () => ({
type: 'DROP_ANIMATION_FINISHED',
payload: null
});
function checkIndexes(insideDestination) {
if (insideDestination.length <= 1) {
return;
}
const indexes = insideDestination.map(d => d.descriptor.index);
const errors = {};
for (let i = 1; i < indexes.length; i++) {
const current = indexes[i];
const previous = indexes[i - 1];
if (current !== previous + 1) {
errors[current] = true;
}
}
if (!Object.keys(errors).length) {
return;
}
const formatted = indexes.map(index => {
const hasError = Boolean(errors[index]);
return hasError ? `[🔥${index}]` : `${index}`;
}).join(', ');
warning(`
Detected non-consecutive <Draggable /> indexes.
(This can cause unexpected bugs)
${formatted}
`) ;
}
function validateDimensions(critical, dimensions) {
{
const insideDestination = getDraggablesInsideDroppable(critical.droppable.id, dimensions.draggables);
checkIndexes(insideDestination);
}
}
var lift = (marshal => _ref => {
let {
getState,
dispatch
} = _ref;
return next => action => {
if (action.type !== 'LIFT') {
next(action);
return;
}
const {
id,
clientSelection,
movementMode
} = action.payload;
const initial = getState();
if (initial.phase === 'DROP_ANIMATING') {
dispatch(completeDrop({
completed: initial.completed
}));
}
!(getState().phase === 'IDLE') ? invariant(false, 'Unexpected phase to start a drag') : void 0;
dispatch(flush());
dispatch(beforeInitialCapture({
draggableId: id,
movementMode
}));
const scrollOptions = {
shouldPublishImmediately: movementMode === 'SNAP'
};
const request = {
draggableId: id,
scrollOptions
};
const {
critical,
dimensions,
viewport
} = marshal.startPublishing(request);
validateDimensions(critical, dimensions);
dispatch(initialPublish({
critical,
dimensions,
clientSelection,
movementMode,
viewport
}));
};
});
var style = (marshal => () => next => action => {
if (action.type === 'INITIAL_PUBLISH') {
marshal.dragging();
}
if (action.type === 'DROP_ANIMATE') {
marshal.dropping(action.payload.completed.result.reason);
}
if (action.type === 'FLUSH' || action.type === 'DROP_COMPLETE') {
marshal.resting();
}
next(action);
});
const curves = {
outOfTheWay: 'cubic-bezier(0.2, 0, 0, 1)',
drop: 'cubic-bezier(.2,1,.1,1)'
};
const combine = {
opacity: {
drop: 0,
combining: 0.7
},
scale: {
drop: 0.75
}
};
const timings = {
outOfTheWay: 0.2,
minDropTime: 0.33,
maxDropTime: 0.55
};
const outOfTheWayTiming = `${timings.outOfTheWay}s ${curves.outOfTheWay}`;
const transitions = {
fluid: `opacity ${outOfTheWayTiming}`,
snap: `transform ${outOfTheWayTiming}, opacity ${outOfTheWayTiming}`,
drop: duration => {
const timing = `${duration}s ${curves.drop}`;
return `transform ${timing}, opacity ${timing}`;
},
outOfTheWay: `transform ${outOfTheWayTiming}`,
placeholder: `height ${outOfTheWayTiming}, width ${outOfTheWayTiming}, margin ${outOfTheWayTiming}`
};
const moveTo = offset => isEqual$1(offset, origin) ? undefined : `translate(${offset.x}px, ${offset.y}px)`;
const transforms = {
moveTo,
drop: (offset, isCombining) => {
const translate = moveTo(offset);
if (!translate) {
return undefined;
}
if (!isCombining) {
return translate;
}
return `${translate} scale(${combine.scale.drop})`;
}
};
const {
minDropTime,
maxDropTime
} = timings;
const dropTimeRange = maxDropTime - minDropTime;
const maxDropTimeAtDistance = 1500;
const cancelDropModifier = 0.6;
var getDropDuration = (_ref => {
let {
current,
destination,
reason
} = _ref;
const distance$1 = distance(current, destination);
if (distance$1 <= 0) {
return minDropTime;
}
if (distance$1 >= maxDropTimeAtDistance) {
return maxDropTime;
}
const percentage = distance$1 / maxDropTimeAtDistance;
const duration = minDropTime + dropTimeRange * percentage;
const withDuration = reason === 'CANCEL' ? duration * cancelDropModifier : duration;
return Number(withDuration.toFixed(2));
});
var getNewHomeClientOffset = (_ref => {
let {
impact,
draggable,
dimensions,
viewport,
afterCritical
} = _ref;
const {
draggables,
droppables
} = dimensions;
const droppableId = whatIsDraggedOver(impact);
const destination = droppableId ? droppables[droppableId] : null;
const home = droppables[draggable.descriptor.droppableId];
const newClientCenter = getClientBorderBoxCenter({
impact,
draggable,
draggables,
afterCritical,
droppable: destination || home,
viewport
});
const offset = subtract(newClientCenter, draggable.client.borderBox.center);
return offset;
});
var getDropImpact = (_ref => {
let {
draggables,
reason,
lastImpact,
home,
viewport,
onLiftImpact
} = _ref;
if (!lastImpact.at || reason !== 'DROP') {
const recomputedHomeImpact = recompute({
draggables,
impact: onLiftImpact,
destination: home,
viewport,
forceShouldAnimate: true
});
return {
impact: recomputedHomeImpact,
didDropInsideDroppable: false
};
}
if (lastImpact.at.type === 'REORDER') {
return {
impact: lastImpact,
didDropInsideDroppable: true
};
}
const withoutMovement = {
...lastImpact,
displaced: emptyGroups
};
return {
impact: withoutMovement,
didDropInsideDroppable: true
};
});
const dropMiddleware = _ref => {
let {
getState,
dispatch
} = _ref;
return next => action => {
if (action.type !== 'DROP') {
next(action);
return;
}
const state = getState();
const reason = action.payload.reason;
if (state.phase === 'COLLECTING') {
dispatch(dropPending({
reason
}));
return;
}
if (state.phase === 'IDLE') {
return;
}
const isWaitingForDrop = state.phase === 'DROP_PENDING' && state.isWaiting;
!!isWaitingForDrop ? invariant(false, 'A DROP action occurred while DROP_PENDING and still waiting') : void 0;
!(state.phase === 'DRAGGING' || state.phase === 'DROP_PENDING') ? invariant(false, `Cannot drop in phase: ${state.phase}`) : void 0;
const critical = state.critical;
const dimensions = state.dimensions;
const draggable = dimensions.draggables[state.critical.draggable.id];
const {
impact,
didDropInsideDroppable
} = getDropImpact({
reason,
lastImpact: state.impact,
afterCritical: state.afterCritical,
onLiftImpact: state.onLiftImpact,
home: state.dimensions.droppables[state.critical.droppable.id],
viewport: state.viewport,
draggables: state.dimensions.draggables
});
const destination = didDropInsideDroppable ? tryGetDestination(impact) : null;
const combine = didDropInsideDroppable ? tryGetCombine(impact) : null;
const source = {
index: critical.draggable.index,
droppableId: critical.droppable.id
};
const result = {
draggableId: draggable.descriptor.id,
type: draggable.descriptor.type,
source,
reason,
mode: state.movementMode,
destination,
combine
};
const newHomeClientOffset = getNewHomeClientOffset({
impact,
draggable,
dimensions,
viewport: state.viewport,
afterCritical: state.afterCritical
});
const completed = {
critical: state.critical,
afterCritical: state.afterCritical,
result,
impact
};
const isAnimationRequired =
!isEqual$1(state.current.client.offset, newHomeClientOffset) ||
Boolean(result.combine);
if (!isAnimationRequired) {
dispatch(completeDrop({
completed
}));
return;
}
const dropDuration = getDropDuration({
current: state.current.client.offset,
destination: newHomeClientOffset,
reason
});
const args = {
newHomeClientOffset,
dropDuration,
completed
};
dispatch(animateDrop(args));
};
};
var drop = dropMiddleware;
var getWindowScroll = (() => ({
x: window.pageXOffset,
y: window.pageYOffset
}));
function getWindowScrollBinding(update) {
return {
eventName: 'scroll',
options: {
passive: true,
capture: false
},
fn: event => {
if (event.target !== window && event.target !== window.document) {
return;
}
update();
}
};
}
function getScrollListener(_ref) {
let {
onWindowScroll
} = _ref;
function updateScroll() {
onWindowScroll(getWindowScroll());
}
const scheduled = rafSchd__default["default"](updateScroll);
const binding = getWindowScrollBinding(scheduled);
let unbind = noop$2;
function isActive() {
return unbind !== noop$2;
}
function start() {
!!isActive() ? invariant(false, 'Cannot start scroll listener when already active') : void 0;
unbind = bindEvents(window, [binding]);
}
function stop() {
!isActive() ? invariant(false, 'Cannot stop scroll listener when not active') : void 0;
scheduled.cancel();
unbind();
unbind = noop$2;
}
return {
start,
stop,
isActive
};
}
const shouldEnd = action => action.type === 'DROP_COMPLETE' || action.type === 'DROP_ANIMATE' || action.type === 'FLUSH';
const scrollListener = store => {
const listener = getScrollListener({
onWindowScroll: newScroll => {
store.dispatch(moveByWindowScroll({
newScroll
}));
}
});
return next => action => {
if (!listener.isActive() && action.type === 'INITIAL_PUBLISH') {
listener.start();
}
if (listener.isActive() && shouldEnd(action)) {
listener.stop();
}
next(action);
};
};
var scrollListener$1 = scrollListener;
var getExpiringAnnounce = (announce => {
let wasCalled = false;
let isExpired = false;
const timeoutId = setTimeout(() => {
isExpired = true;
});
const result = message => {
if (wasCalled) {
warning('Announcement already made. Not making a second announcement') ;
return;
}
if (isExpired) {
warning(`
Announcements cannot be made asynchronously.
Default message has already been announced.
`) ;
return;
}
wasCalled = true;
announce(message);
clearTimeout(timeoutId);
};
result.wasCalled = () => wasCalled;
return result;
});
var getAsyncMarshal = (() => {
const entries = [];
const execute = timerId => {
const index = entries.findIndex(item => item.timerId === timerId);
!(index !== -1) ? invariant(false, 'Could not find timer') : void 0;
const [entry] = entries.splice(index, 1);
entry.callback();
};
const add = fn => {
const timerId = setTimeout(() => execute(timerId));
const entry = {
timerId,
callback: fn
};
entries.push(entry);
};
const flush = () => {
if (!entries.length) {
return;
}
const shallow = [...entries];
entries.length = 0;
shallow.forEach(entry => {
clearTimeout(entry.timerId);
entry.callback();
});
};
return {
add,
flush
};
});
const areLocationsEqual = (first, second) => {
if (first == null && second == null) {
return true;
}
if (first == null || second == null) {
return false;
}
return first.droppableId === second.droppableId && first.index === second.index;
};
const isCombineEqual = (first, second) => {
if (first == null && second == null) {
return true;
}
if (first == null || second == null) {
return false;
}
return first.draggableId === second.draggableId && first.droppableId === second.droppableId;
};
const isCriticalEqual = (first, second) => {
if (first === second) {
return true;
}
const isDraggableEqual = first.draggable.id === second.draggable.id && first.draggable.droppableId === second.draggable.droppableId && first.draggable.type === second.draggable.type && first.draggable.index === second.draggable.index;
const isDroppableEqual = first.droppable.id === second.droppable.id && first.droppable.type === second.droppable.type;
return isDraggableEqual && isDroppableEqual;
};
const withTimings = (key, fn) => {
fn();
};
const getDragStart = (critical, mode) => ({
draggableId: critical.draggable.id,
type: critical.droppable.type,
source: {
droppableId: critical.droppable.id,
index: critical.draggable.index
},
mode
});
function execute(responder, data, announce,
getDefaultMessage) {
if (!responder) {
announce(getDefaultMessage(data));
return;
}
const willExpire = getExpiringAnnounce(announce);
const provided = {
announce: willExpire
};
responder(data, provided);
if (!willExpire.wasCalled()) {
announce(getDefaultMessage(data));
}
}
var getPublisher = ((getResponders, announce) => {
const asyncMarshal = getAsyncMarshal();
let dragging = null;
const beforeCapture = (draggableId, mode) => {
!!dragging ? invariant(false, 'Cannot fire onBeforeCapture as a drag start has already been published') : void 0;
withTimings('onBeforeCapture', () => {
const fn = getResponders().onBeforeCapture;
if (fn) {
const before = {
draggableId,
mode
};
fn(before);
}
});
};
const beforeStart = (critical, mode) => {
!!dragging ? invariant(false, 'Cannot fire onBeforeDragStart as a drag start has already been published') : void 0;
withTimings('onBeforeDragStart', () => {
const fn = getResponders().onBeforeDragStart;
if (fn) {
fn(getDragStart(critical, mode));
}
});
};
const start = (critical, mode) => {
!!dragging ? invariant(false, 'Cannot fire onBeforeDragStart as a drag start has already been published') : void 0;
const data = getDragStart(critical, mode);
dragging = {
mode,
lastCritical: critical,
lastLocation: data.source,
lastCombine: null
};
asyncMarshal.add(() => {
withTimings('onDragStart', () => execute(getResponders().onDragStart, data, announce, preset$1.onDragStart));
});
};
const update = (critical, impact) => {
const location = tryGetDestination(impact);
const combine = tryGetCombine(impact);
!dragging ? invariant(false, 'Cannot fire onDragMove when onDragStart has not been called') : void 0;
const hasCriticalChanged = !isCriticalEqual(critical, dragging.lastCritical);
if (hasCriticalChanged) {
dragging.lastCritical = critical;
}
const hasLocationChanged = !areLocationsEqual(dragging.lastLocation, location);
if (hasLocationChanged) {
dragging.lastLocation = location;
}
const hasGroupingChanged = !isCombineEqual(dragging.lastCombine, combine);
if (hasGroupingChanged) {
dragging.lastCombine = combine;
}
if (!hasCriticalChanged && !hasLocationChanged && !hasGroupingChanged) {
return;
}
const data = {
...getDragStart(critical, dragging.mode),
combine,
destination: location
};
asyncMarshal.add(() => {
withTimings('onDragUpdate', () => execute(getResponders().onDragUpdate, data, announce, preset$1.onDragUpdate));
});
};
const flush = () => {
!dragging ? invariant(false, 'Can only flush responders while dragging') : void 0;
asyncMarshal.flush();
};
const drop = result => {
!dragging ? invariant(false, 'Cannot fire onDragEnd when there is no matching onDragStart') : void 0;
dragging = null;
withTimings('onDragEnd', () => execute(getResponders().onDragEnd, result, announce, preset$1.onDragEnd));
};
const abort = () => {
if (!dragging) {
return;
}
const result = {
...getDragStart(dragging.lastCritical, dragging.mode),
combine: null,
destination: null,
reason: 'CANCEL'
};
drop(result);
};
return {
beforeCapture,
beforeStart,
start,
update,
flush,
drop,
abort
};
});
var responders = ((getResponders, announce) => {
const publisher = getPublisher(getResponders, announce);
return store => next => action => {
if (action.type === 'BEFORE_INITIAL_CAPTURE') {
publisher.beforeCapture(action.payload.draggableId, action.payload.movementMode);
return;
}
if (action.type === 'INITIAL_PUBLISH') {
const critical = action.payload.critical;
publisher.beforeStart(critical, action.payload.movementMode);
next(action);
publisher.start(critical, action.payload.movementMode);
return;
}
if (action.type === 'DROP_COMPLETE') {
const result = action.payload.completed.result;
publisher.flush();
next(action);
publisher.drop(result);
return;
}
next(action);
if (action.type === 'FLUSH') {
publisher.abort();
return;
}
const state = store.getState();
if (state.phase === 'DRAGGING') {
publisher.update(state.critical, state.impact);
}
};
});
const dropAnimationFinishMiddleware = store => next => action => {
if (action.type !== 'DROP_ANIMATION_FINISHED') {
next(action);
return;
}
const state = store.getState();
!(state.phase === 'DROP_ANIMATING') ? invariant(false, 'Cannot finish a drop animating when no drop is occurring') : void 0;
store.dispatch(completeDrop({
completed: state.completed
}));
};
var dropAnimationFinish = dropAnimationFinishMiddleware;
const dropAnimationFlushOnScrollMiddleware = store => {
let unbind = null;
let frameId = null;
function clear() {
if (frameId) {
cancelAnimationFrame(frameId);
frameId = null;
}
if (unbind) {
unbind();
unbind = null;
}
}
return next => action => {
if (action.type === 'FLUSH' || action.type === 'DROP_COMPLETE' || action.type === 'DROP_ANIMATION_FINISHED') {
clear();
}
next(action);
if (action.type !== 'DROP_ANIMATE') {
return;
}
const binding = {
eventName: 'scroll',
options: {
capture: true,
passive: false,
once: true
},
fn: function flushDropAnimation() {
const state = store.getState();
if (state.phase === 'DROP_ANIMATING') {
store.dispatch(dropAnimationFinished());
}
}
};
frameId = requestAnimationFrame(() => {
frameId = null;
unbind = bindEvents(window, [binding]);
});
};
};
var dropAnimationFlushOnScroll = dropAnimationFlushOnScrollMiddleware;
var dimensionMarshalStopper = (marshal => () => next => action => {
if (
action.type === 'DROP_COMPLETE' || action.type === 'FLUSH' ||
action.type === 'DROP_ANIMATE') {
marshal.stopPublishing();
}
next(action);
});
var focus = (marshal => {
let isWatching = false;
return () => next => action => {
if (action.type === 'INITIAL_PUBLISH') {
isWatching = true;
marshal.tryRecordFocus(action.payload.critical.draggable.id);
next(action);
marshal.tryRestoreFocusRecorded();
return;
}
next(action);
if (!isWatching) {
return;
}
if (action.type === 'FLUSH') {
isWatching = false;
marshal.tryRestoreFocusRecorded();
return;
}
if (action.type === 'DROP_COMPLETE') {
isWatching = false;
const result = action.payload.completed.result;
if (result.combine) {
marshal.tryShiftRecord(result.draggableId, result.combine.draggableId);
}
marshal.tryRestoreFocusRecorded();
}
};
});
const shouldStop = action => action.type === 'DROP_COMPLETE' || action.type === 'DROP_ANIMATE' || action.type === 'FLUSH';
var autoScroll = (autoScroller => store => next => action => {
if (shouldStop(action)) {
autoScroller.stop();
next(action);
return;
}
if (action.type === 'INITIAL_PUBLISH') {
next(action);
const state = store.getState();
!(state.phase === 'DRAGGING') ? invariant(false, 'Expected phase to be DRAGGING after INITIAL_PUBLISH') : void 0;
autoScroller.start(state);
return;
}
next(action);
autoScroller.scroll(store.getState());
});
const pendingDrop = store => next => action => {
next(action);
if (action.type !== 'PUBLISH_WHILE_DRAGGING') {
return;
}
const postActionState = store.getState();
if (postActionState.phase !== 'DROP_PENDING') {
return;
}
if (postActionState.isWaiting) {
return;
}
store.dispatch(drop$1({
reason: postActionState.reason
}));
};
var pendingDrop$1 = pendingDrop;
const composeEnhancers = typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
name: '@hello-pangea/dnd'
}) : redux.compose;
var createStore$1 = (_ref => {
let {
dimensionMarshal,
focusMarshal,
styleMarshal,
getResponders,
announce,
autoScroller
} = _ref;
return redux.createStore(reducer$1, composeEnhancers(redux.applyMiddleware(
style(styleMarshal),
dimensionMarshalStopper(dimensionMarshal),
lift(dimensionMarshal), drop,
dropAnimationFinish, dropAnimationFlushOnScroll, pendingDrop$1, autoScroll(autoScroller), scrollListener$1, focus(focusMarshal),
responders(getResponders, announce))));
});
const clean$1 = () => ({
additions: {},
removals: {},
modified: {}
});
function createPublisher(_ref) {
let {
registry,
callbacks
} = _ref;
let staging = clean$1();
let frameId = null;
const collect = () => {
if (frameId) {
return;
}
callbacks.collectionStarting();
frameId = requestAnimationFrame(() => {
frameId = null;
const {
additions,
removals,
modified
} = staging;
const added = Object.keys(additions).map(
id => registry.draggable.getById(id).getDimension(origin))
.sort((a, b) => a.descriptor.index - b.descriptor.index);
const updated = Object.keys(modified).map(id => {
const entry = registry.droppable.getById(id);
const scroll = entry.callbacks.getScrollWhileDragging();
return {
droppableId: id,
scroll
};
});
const result = {
additions: added,
removals: Object.keys(removals),
modified: updated
};
staging = clean$1();
callbacks.publish(result);
});
};
const add = entry => {
const id = entry.descriptor.id;
staging.additions[id] = entry;
staging.modified[entry.descriptor.droppableId] = true;
if (staging.removals[id]) {
delete staging.removals[id];
}
collect();
};
const remove = entry => {
const descriptor = entry.descriptor;
staging.removals[descriptor.id] = true;
staging.modified[descriptor.droppableId] = true;
if (staging.additions[descriptor.id]) {
delete staging.additions[descriptor.id];
}
collect();
};
const stop = () => {
if (!frameId) {
return;
}
cancelAnimationFrame(frameId);
frameId = null;
staging = clean$1();
};
return {
add,
remove,
stop
};
}
var getMaxScroll = (_ref => {
let {
scrollHeight,
scrollWidth,
height,
width
} = _ref;
const maxScroll = subtract(
{
x: scrollWidth,
y: scrollHeight
},
{
x: width,
y: height
});
const adjustedMaxScroll = {
x: Math.max(0, maxScroll.x),
y: Math.max(0, maxScroll.y)
};
return adjustedMaxScroll;
});
var getDocumentElement = (() => {
const doc = document.documentElement;
!doc ? invariant(false, 'Cannot find document.documentElement') : void 0;
return doc;
});
var getMaxWindowScroll = (() => {
const doc = getDocumentElement();
const maxScroll = getMaxScroll({
scrollHeight: doc.scrollHeight,
scrollWidth: doc.scrollWidth,
width: doc.clientWidth,
height: doc.clientHeight
});
return maxScroll;
});
var getViewport = (() => {
const scroll = getWindowScroll();
const maxScroll = getMaxWindowScroll();
const top = scroll.y;
const left = scroll.x;
const doc = getDocumentElement();
const width = doc.clientWidth;
const height = doc.clientHeight;
const right = left + width;
const bottom = top + height;
const frame = cssBoxModel.getRect({
top,
left,
right,
bottom
});
const viewport = {
frame,
scroll: {
initial: scroll,
current: scroll,
max: maxScroll,
diff: {
value: origin,
displacement: origin
}
}
};
return viewport;
});
var getInitialPublish = (_ref => {
let {
critical,
scrollOptions,
registry
} = _ref;
const viewport = getViewport();
const windowScroll = viewport.scroll.current;
const home = critical.droppable;
const droppables = registry.droppable.getAllByType(home.type).map(entry => entry.callbacks.getDimensionAndWatchScroll(windowScroll, scrollOptions));
const draggables = registry.draggable.getAllByType(critical.draggable.type).map(entry => entry.getDimension(windowScroll));
const dimensions = {
draggables: toDraggableMap(draggables),
droppables: toDroppableMap(droppables)
};
const result = {
dimensions,
critical,
viewport
};
return result;
});
function shouldPublishUpdate(registry, dragging, entry) {
if (entry.descriptor.id === dragging.id) {
return false;
}
if (entry.descriptor.type !== dragging.type) {
return false;
}
const home = registry.droppable.getById(entry.descriptor.droppableId);
if (home.descriptor.mode !== 'virtual') {
warning(`
You are attempting to add or remove a Draggable [id: ${entry.descriptor.id}]
while a drag is occurring. This is only supported for virtual lists.
See https://github.com/hello-pangea/dnd/blob/main/docs/patterns/virtual-lists.md
`) ;
return false;
}
return true;
}
var createDimensionMarshal = ((registry, callbacks) => {
let collection = null;
const publisher = createPublisher({
callbacks: {
publish: callbacks.publishWhileDragging,
collectionStarting: callbacks.collectionStarting
},
registry
});
const updateDroppableIsEnabled = (id, isEnabled) => {
!registry.droppable.exists(id) ? invariant(false, `Cannot update is enabled flag of Droppable ${id} as it is not registered`) : void 0;
if (!collection) {
return;
}
callbacks.updateDroppableIsEnabled({
id,
isEnabled
});
};
const updateDroppableIsCombineEnabled = (id, isCombineEnabled) => {
if (!collection) {
return;
}
!registry.droppable.exists(id) ? invariant(false, `Cannot update isCombineEnabled flag of Droppable ${id} as it is not registered`) : void 0;
callbacks.updateDroppableIsCombineEnabled({
id,
isCombineEnabled
});
};
const updateDroppableScroll = (id, newScroll) => {
if (!collection) {
return;
}
!registry.droppable.exists(id) ? invariant(false, `Cannot update the scroll on Droppable ${id} as it is not registered`) : void 0;
callbacks.updateDroppableScroll({
id,
newScroll
});
};
const scrollDroppable = (id, change) => {
if (!collection) {
return;
}
registry.droppable.getById(id).callbacks.scroll(change);
};
const stopPublishing = () => {
if (!collection) {
return;
}
publisher.stop();
const home = collection.critical.droppable;
registry.droppable.getAllByType(home.type).forEach(entry => entry.callbacks.dragStopped());
collection.unsubscribe();
collection = null;
};
const subscriber = event => {
!collection ? invariant(false, 'Should only be subscribed when a collection is occurring') : void 0;
const dragging = collection.critical.draggable;
if (event.type === 'ADDITION') {
if (shouldPublishUpdate(registry, dragging, event.value)) {
publisher.add(event.value);
}
}
if (event.type === 'REMOVAL') {
if (shouldPublishUpdate(registry, dragging, event.value)) {
publisher.remove(event.value);
}
}
};
const startPublishing = request => {
!!collection ? invariant(false, 'Cannot start capturing critical dimensions as there is already a collection') : void 0;
const entry = registry.draggable.getById(request.draggableId);
const home = registry.droppable.getById(entry.descriptor.droppableId);
const critical = {
draggable: entry.descriptor,
droppable: home.descriptor
};
const unsubscribe = registry.subscribe(subscriber);
collection = {
critical,
unsubscribe
};
return getInitialPublish({
critical,
registry,
scrollOptions: request.scrollOptions
});
};
const marshal = {
updateDroppableIsEnabled,
updateDroppableIsCombineEnabled,
scrollDroppable,
updateDroppableScroll,
startPublishing,
stopPublishing
};
return marshal;
});
var canStartDrag = ((state, id) => {
if (state.phase === 'IDLE') {
return true;
}
if (state.phase !== 'DROP_ANIMATING') {
return false;
}
if (state.completed.result.draggableId === id) {
return false;
}
return state.completed.result.reason === 'DROP';
});
var scrollWindow = (change => {
window.scrollBy(change.x, change.y);
});
const getScrollableDroppables = memoizeOne__default["default"](droppables => toDroppableList(droppables).filter(droppable => {
if (!droppable.isEnabled) {
return false;
}
if (!droppable.frame) {
return false;
}
return true;
}));
const getScrollableDroppableOver = (target, droppables) => {
const maybe = getScrollableDroppables(droppables).find(droppable => {
!droppable.frame ? invariant(false, 'Invalid result') : void 0;
return isPositionInFrame(droppable.frame.pageMarginBox)(target);
}) || null;
return maybe;
};
var getBestScrollableDroppable = (_ref => {
let {
center,
destination,
droppables
} = _ref;
if (destination) {
const dimension = droppables[destination];
if (!dimension.frame) {
return null;
}
return dimension;
}
const dimension = getScrollableDroppableOver(center, droppables);
return dimension;
});
const defaultAutoScrollerOptions = {
startFromPercentage: 0.25,
maxScrollAtPercentage: 0.05,
maxPixelScroll: 28,
ease: percentage => percentage ** 2,
durationDampening: {
stopDampeningAt: 1200,
accelerateAt: 360
},
disabled: false
};
var getDistanceThresholds = (function (container, axis, getAutoScrollerOptions) {
if (getAutoScrollerOptions === void 0) {
getAutoScrollerOptions = () => defaultAutoScrollerOptions;
}
const autoScrollerOptions = getAutoScrollerOptions();
const startScrollingFrom = container[axis.size] * autoScrollerOptions.startFromPercentage;
const maxScrollValueAt = container[axis.size] * autoScrollerOptions.maxScrollAtPercentage;
const thresholds = {
startScrollingFrom,
maxScrollValueAt
};
return thresholds;
});
var getPercentage = (_ref => {
let {
startOfRange,
endOfRange,
current
} = _ref;
const range = endOfRange - startOfRange;
if (range === 0) {
warning(`
Detected distance range of 0 in the fluid auto scroller
This is unexpected and would cause a divide by 0 issue.
Not allowing an auto scroll
`) ;
return 0;
}
const currentInRange = current - startOfRange;
const percentage = currentInRange / range;
return percentage;
});
var minScroll = 1;
var getValueFromDistance = (function (distanceToEdge, thresholds, getAutoScrollerOptions) {
if (getAutoScrollerOptions === void 0) {
getAutoScrollerOptions = () => defaultAutoScrollerOptions;
}
const autoScrollerOptions = getAutoScrollerOptions();
if (distanceToEdge > thresholds.startScrollingFrom) {
return 0;
}
if (distanceToEdge <= thresholds.maxScrollValueAt) {
return autoScrollerOptions.maxPixelScroll;
}
if (distanceToEdge === thresholds.startScrollingFrom) {
return minScroll;
}
const percentageFromMaxScrollValueAt = getPercentage({
startOfRange: thresholds.maxScrollValueAt,
endOfRange: thresholds.startScrollingFrom,
current: distanceToEdge
});
const percentageFromStartScrollingFrom = 1 - percentageFromMaxScrollValueAt;
const scroll = autoScrollerOptions.maxPixelScroll * autoScrollerOptions.ease(percentageFromStartScrollingFrom);
return Math.ceil(scroll);
});
var dampenValueByTime = ((proposedScroll, dragStartTime, getAutoScrollerOptions) => {
const autoScrollerOptions = getAutoScrollerOptions();
const accelerateAt = autoScrollerOptions.durationDampening.accelerateAt;
const stopAt = autoScrollerOptions.durationDampening.stopDampeningAt;
const startOfRange = dragStartTime;
const endOfRange = stopAt;
const now = Date.now();
const runTime = now - startOfRange;
if (runTime >= stopAt) {
return proposedScroll;
}
if (runTime < accelerateAt) {
return minScroll;
}
const betweenAccelerateAtAndStopAtPercentage = getPercentage({
startOfRange: accelerateAt,
endOfRange,
current: runTime
});
const scroll = proposedScroll * autoScrollerOptions.ease(betweenAccelerateAtAndStopAtPercentage);
return Math.ceil(scroll);
});
var getValue = (_ref => {
let {
distanceToEdge,
thresholds,
dragStartTime,
shouldUseTimeDampening,
getAutoScrollerOptions
} = _ref;
const scroll = getValueFromDistance(distanceToEdge, thresholds, getAutoScrollerOptions);
if (scroll === 0) {
return 0;
}
if (!shouldUseTimeDampening) {
return scroll;
}
return Math.max(dampenValueByTime(scroll, dragStartTime, getAutoScrollerOptions), minScroll);
});
var getScrollOnAxis = (_ref => {
let {
container,
distanceToEdges,
dragStartTime,
axis,
shouldUseTimeDampening,
getAutoScrollerOptions
} = _ref;
const thresholds = getDistanceThresholds(container, axis, getAutoScrollerOptions);
const isCloserToEnd = distanceToEdges[axis.end] < distanceToEdges[axis.start];
if (isCloserToEnd) {
return getValue({
distanceToEdge: distanceToEdges[axis.end],
thresholds,
dragStartTime,
shouldUseTimeDampening,
getAutoScrollerOptions
});
}
return -1 * getValue({
distanceToEdge: distanceToEdges[axis.start],
thresholds,
dragStartTime,
shouldUseTimeDampening,
getAutoScrollerOptions
});
});
var adjustForSizeLimits = (_ref => {
let {
container,
subject,
proposedScroll
} = _ref;
const isTooBigVertically = subject.height > container.height;
const isTooBigHorizontally = subject.width > container.width;
if (!isTooBigHorizontally && !isTooBigVertically) {
return proposedScroll;
}
if (isTooBigHorizontally && isTooBigVertically) {
return null;
}
return {
x: isTooBigHorizontally ? 0 : proposedScroll.x,
y: isTooBigVertically ? 0 : proposedScroll.y
};
});
const clean = apply(value => value === 0 ? 0 : value);
var getScroll$1 = (_ref => {
let {
dragStartTime,
container,
subject,
center,
shouldUseTimeDampening,
getAutoScrollerOptions
} = _ref;
const distanceToEdges = {
top: center.y - container.top,
right: container.right - center.x,
bottom: container.bottom - center.y,
left: center.x - container.left
};
const y = getScrollOnAxis({
container,
distanceToEdges,
dragStartTime,
axis: vertical,
shouldUseTimeDampening,
getAutoScrollerOptions
});
const x = getScrollOnAxis({
container,
distanceToEdges,
dragStartTime,
axis: horizontal,
shouldUseTimeDampening,
getAutoScrollerOptions
});
const required = clean({
x,
y
});
if (isEqual$1(required, origin)) {
return null;
}
const limited = adjustForSizeLimits({
container,
subject,
proposedScroll: required
});
if (!limited) {
return null;
}
return isEqual$1(limited, origin) ? null : limited;
});
const smallestSigned = apply(value => {
if (value === 0) {
return 0;
}
return value > 0 ? 1 : -1;
});
const getOverlap = (() => {
const getRemainder = (target, max) => {
if (target < 0) {
return target;
}
if (target > max) {
return target - max;
}
return 0;
};
return _ref => {
let {
current,
max,
change
} = _ref;
const targetScroll = add(current, change);
const overlap = {
x: getRemainder(targetScroll.x, max.x),
y: getRemainder(targetScroll.y, max.y)
};
if (isEqual$1(overlap, origin)) {
return null;
}
return overlap;
};
})();
const canPartiallyScroll = _ref2 => {
let {
max: rawMax,
current,
change
} = _ref2;
const max = {
x: Math.max(current.x, rawMax.x),
y: Math.max(current.y, rawMax.y)
};
const smallestChange = smallestSigned(change);
const overlap = getOverlap({
max,
current,
change: smallestChange
});
if (!overlap) {
return true;
}
if (smallestChange.x !== 0 && overlap.x === 0) {
return true;
}
if (smallestChange.y !== 0 && overlap.y === 0) {
return true;
}
return false;
};
const canScrollWindow = (viewport, change) => canPartiallyScroll({
current: viewport.scroll.current,
max: viewport.scroll.max,
change
});
const getWindowOverlap = (viewport, change) => {
if (!canScrollWindow(viewport, change)) {
return null;
}
const max = viewport.scroll.max;
const current = viewport.scroll.current;
return getOverlap({
current,
max,
change
});
};
const canScrollDroppable = (droppable, change) => {
const frame = droppable.frame;
if (!frame) {
return false;
}
return canPartiallyScroll({
current: frame.scroll.current,
max: frame.scroll.max,
change
});
};
const getDroppableOverlap = (droppable, change) => {
const frame = droppable.frame;
if (!frame) {
return null;
}
if (!canScrollDroppable(droppable, change)) {
return null;
}
return getOverlap({
current: frame.scroll.current,
max: frame.scroll.max,
change
});
};
var getWindowScrollChange = (_ref => {
let {
viewport,
subject,
center,
dragStartTime,
shouldUseTimeDampening,
getAutoScrollerOptions
} = _ref;
const scroll = getScroll$1({
dragStartTime,
container: viewport.frame,
subject,
center,
shouldUseTimeDampening,
getAutoScrollerOptions
});
return scroll && canScrollWindow(viewport, scroll) ? scroll : null;
});
var getDroppableScrollChange = (_ref => {
let {
droppable,
subject,
center,
dragStartTime,
shouldUseTimeDampening,
getAutoScrollerOptions
} = _ref;
const frame = droppable.frame;
if (!frame) {
return null;
}
const scroll = getScroll$1({
dragStartTime,
container: frame.pageMarginBox,
subject,
center,
shouldUseTimeDampening,
getAutoScrollerOptions
});
return scroll && canScrollDroppable(droppable, scroll) ? scroll : null;
});
var scroll = (_ref => {
let {
state,
dragStartTime,
shouldUseTimeDampening,
scrollWindow,
scrollDroppable,
getAutoScrollerOptions
} = _ref;
const center = state.current.page.borderBoxCenter;
const draggable = state.dimensions.draggables[state.critical.draggable.id];
const subject = draggable.page.marginBox;
if (state.isWindowScrollAllowed) {
const viewport = state.viewport;
const change = getWindowScrollChange({
dragStartTime,
viewport,
subject,
center,
shouldUseTimeDampening,
getAutoScrollerOptions
});
if (change) {
scrollWindow(change);
return;
}
}
const droppable = getBestScrollableDroppable({
center,
destination: whatIsDraggedOver(state.impact),
droppables: state.dimensions.droppables
});
if (!droppable) {
return;
}
const change = getDroppableScrollChange({
dragStartTime,
droppable,
subject,
center,
shouldUseTimeDampening,
getAutoScrollerOptions
});
if (change) {
scrollDroppable(droppable.descriptor.id, change);
}
});
var createFluidScroller = (_ref => {
let {
scrollWindow,
scrollDroppable,
getAutoScrollerOptions = () => defaultAutoScrollerOptions
} = _ref;
const scheduleWindowScroll = rafSchd__default["default"](scrollWindow);
const scheduleDroppableScroll = rafSchd__default["default"](scrollDroppable);
let dragging = null;
const tryScroll = state => {
!dragging ? invariant(false, 'Cannot fluid scroll if not dragging') : void 0;
const {
shouldUseTimeDampening,
dragStartTime
} = dragging;
scroll({
state,
scrollWindow: scheduleWindowScroll,
scrollDroppable: scheduleDroppableScroll,
dragStartTime,
shouldUseTimeDampening,
getAutoScrollerOptions
});
};
const start$1 = state => {
!!dragging ? invariant(false, 'Cannot start auto scrolling when already started') : void 0;
const dragStartTime = Date.now();
let wasScrollNeeded = false;
const fakeScrollCallback = () => {
wasScrollNeeded = true;
};
scroll({
state,
dragStartTime: 0,
shouldUseTimeDampening: false,
scrollWindow: fakeScrollCallback,
scrollDroppable: fakeScrollCallback,
getAutoScrollerOptions
});
dragging = {
dragStartTime,
shouldUseTimeDampening: wasScrollNeeded
};
if (wasScrollNeeded) {
tryScroll(state);
}
};
const stop = () => {
if (!dragging) {
return;
}
scheduleWindowScroll.cancel();
scheduleDroppableScroll.cancel();
dragging = null;
};
return {
start: start$1,
stop,
scroll: tryScroll
};
});
var createJumpScroller = (_ref => {
let {
move,
scrollDroppable,
scrollWindow
} = _ref;
const moveByOffset = (state, offset) => {
const client = add(state.current.client.selection, offset);
move({
client
});
};
const scrollDroppableAsMuchAsItCan = (droppable, change) => {
if (!canScrollDroppable(droppable, change)) {
return change;
}
const overlap = getDroppableOverlap(droppable, change);
if (!overlap) {
scrollDroppable(droppable.descriptor.id, change);
return null;
}
const whatTheDroppableCanScroll = subtract(change, overlap);
scrollDroppable(droppable.descriptor.id, whatTheDroppableCanScroll);
const remainder = subtract(change, whatTheDroppableCanScroll);
return remainder;
};
const scrollWindowAsMuchAsItCan = (isWindowScrollAllowed, viewport, change) => {
if (!isWindowScrollAllowed) {
return change;
}
if (!canScrollWindow(viewport, change)) {
return change;
}
const overlap = getWindowOverlap(viewport, change);
if (!overlap) {
scrollWindow(change);
return null;
}
const whatTheWindowCanScroll = subtract(change, overlap);
scrollWindow(whatTheWindowCanScroll);
const remainder = subtract(change, whatTheWindowCanScroll);
return remainder;
};
const jumpScroller = state => {
const request = state.scrollJumpRequest;
if (!request) {
return;
}
const destination = whatIsDraggedOver(state.impact);
!destination ? invariant(false, 'Cannot perform a jump scroll when there is no destination') : void 0;
const droppableRemainder = scrollDroppableAsMuchAsItCan(state.dimensions.droppables[destination], request);
if (!droppableRemainder) {
return;
}
const viewport = state.viewport;
const windowRemainder = scrollWindowAsMuchAsItCan(state.isWindowScrollAllowed, viewport, droppableRemainder);
if (!windowRemainder) {
return;
}
moveByOffset(state, windowRemainder);
};
return jumpScroller;
});
var createAutoScroller = (_ref => {
let {
scrollDroppable,
scrollWindow,
move,
getAutoScrollerOptions
} = _ref;
const fluidScroller = createFluidScroller({
scrollWindow,
scrollDroppable,
getAutoScrollerOptions
});
const jumpScroll = createJumpScroller({
move,
scrollWindow,
scrollDroppable
});
const scroll = state => {
const autoScrollerOptions = getAutoScrollerOptions();
if (autoScrollerOptions.disabled || state.phase !== 'DRAGGING') {
return;
}
if (state.movementMode === 'FLUID') {
fluidScroller.scroll(state);
return;
}
if (!state.scrollJumpRequest) {
return;
}
jumpScroll(state);
};
const scroller = {
scroll,
start: fluidScroller.start,
stop: fluidScroller.stop
};
return scroller;
});
const prefix = 'data-rfd';
const dragHandle = (() => {
const base = `${prefix}-drag-handle`;
return {
base,
draggableId: `${base}-draggable-id`,
contextId: `${base}-context-id`
};
})();
const draggable = (() => {
const base = `${prefix}-draggable`;
return {
base,
contextId: `${base}-context-id`,
id: `${base}-id`
};
})();
const droppable = (() => {
const base = `${prefix}-droppable`;
return {
base,
contextId: `${base}-context-id`,
id: `${base}-id`
};
})();
const scrollContainer = {
contextId: `${prefix}-scroll-container-context-id`
};
const makeGetSelector = context => attribute => `[${attribute}="${context}"]`;
const getStyles = (rules, property) => rules.map(rule => {
const value = rule.styles[property];
if (!value) {
return '';
}
return `${rule.selector} { ${value} }`;
}).join(' ');
const noPointerEvents = 'pointer-events: none;';
var getStyles$1 = (contextId => {
const getSelector = makeGetSelector(contextId);
const dragHandle$1 = (() => {
const grabCursor = `
cursor: -webkit-grab;
cursor: grab;
`;
return {
selector: getSelector(dragHandle.contextId),
styles: {
always: `
-webkit-touch-callout: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
touch-action: manipulation;
`,
resting: grabCursor,
dragging: noPointerEvents,
dropAnimating: grabCursor
}
};
})();
const draggable$1 = (() => {
const transition = `
transition: ${transitions.outOfTheWay};
`;
return {
selector: getSelector(draggable.contextId),
styles: {
dragging: transition,
dropAnimating: transition,
userCancel: transition
}
};
})();
const droppable$1 = {
selector: getSelector(droppable.contextId),
styles: {
always: `overflow-anchor: none;`
}
};
const body = {
selector: 'body',
styles: {
dragging: `
cursor: grabbing;
cursor: -webkit-grabbing;
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
overflow-anchor: none;
`
}
};
const rules = [draggable$1, dragHandle$1, droppable$1, body];
return {
always: getStyles(rules, 'always'),
resting: getStyles(rules, 'resting'),
dragging: getStyles(rules, 'dragging'),
dropAnimating: getStyles(rules, 'dropAnimating'),
userCancel: getStyles(rules, 'userCancel')
};
});
const useIsomorphicLayoutEffect = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? React.useLayoutEffect : React.useEffect;
var useLayoutEffect = useIsomorphicLayoutEffect;
const getHead = () => {
const head = document.querySelector('head');
!head ? invariant(false, 'Cannot find the head to append a style to') : void 0;
return head;
};
const createStyleEl = nonce => {
const el = document.createElement('style');
if (nonce) {
el.setAttribute('nonce', nonce);
}
el.type = 'text/css';
return el;
};
function useStyleMarshal(contextId, nonce) {
const styles = useMemoOne.useMemo(() => getStyles$1(contextId), [contextId]);
const alwaysRef = React.useRef(null);
const dynamicRef = React.useRef(null);
const setDynamicStyle = useMemoOne.useCallback(
memoizeOne__default["default"](proposed => {
const el = dynamicRef.current;
!el ? invariant(false, 'Cannot set dynamic style element if it is not set') : void 0;
el.textContent = proposed;
}), []);
const setAlwaysStyle = useMemoOne.useCallback(proposed => {
const el = alwaysRef.current;
!el ? invariant(false, 'Cannot set dynamic style element if it is not set') : void 0;
el.textContent = proposed;
}, []);
useLayoutEffect(() => {
!(!alwaysRef.current && !dynamicRef.current) ? invariant(false, 'style elements already mounted') : void 0;
const always = createStyleEl(nonce);
const dynamic = createStyleEl(nonce);
alwaysRef.current = always;
dynamicRef.current = dynamic;
always.setAttribute(`${prefix}-always`, contextId);
dynamic.setAttribute(`${prefix}-dynamic`, contextId);
getHead().appendChild(always);
getHead().appendChild(dynamic);
setAlwaysStyle(styles.always);
setDynamicStyle(styles.resting);
return () => {
const remove = ref => {
const current = ref.current;
!current ? invariant(false, 'Cannot unmount ref as it is not set') : void 0;
getHead().removeChild(current);
ref.current = null;
};
remove(alwaysRef);
remove(dynamicRef);
};
}, [nonce, setAlwaysStyle, setDynamicStyle, styles.always, styles.resting, contextId]);
const dragging = useMemoOne.useCallback(() => setDynamicStyle(styles.dragging), [setDynamicStyle, styles.dragging]);
const dropping = useMemoOne.useCallback(reason => {
if (reason === 'DROP') {
setDynamicStyle(styles.dropAnimating);
return;
}
setDynamicStyle(styles.userCancel);
}, [setDynamicStyle, styles.dropAnimating, styles.userCancel]);
const resting = useMemoOne.useCallback(() => {
if (!dynamicRef.current) {
return;
}
setDynamicStyle(styles.resting);
}, [setDynamicStyle, styles.resting]);
const marshal = useMemoOne.useMemo(() => ({
dragging,
dropping,
resting
}), [dragging, dropping, resting]);
return marshal;
}
function querySelectorAll(parentNode, selector) {
return Array.from(parentNode.querySelectorAll(selector));
}
var getWindowFromEl = (el => {
var _el$ownerDocument;
return (el == null ? void 0 : (_el$ownerDocument = el.ownerDocument) == null ? void 0 : _el$ownerDocument.defaultView) || window;
});
function isHtmlElement(el) {
return el instanceof getWindowFromEl(el).HTMLElement;
}
function findDragHandle(contextId, draggableId) {
const selector = `[${dragHandle.contextId}="${contextId}"]`;
const possible = querySelectorAll(document, selector);
if (!possible.length) {
warning(`Unable to find any drag handles in the context "${contextId}"`) ;
return null;
}
const handle = possible.find(el => {
return el.getAttribute(dragHandle.draggableId) === draggableId;
});
if (!handle) {
warning(`Unable to find drag handle with id "${draggableId}" as no handle with a matching id was found`) ;
return null;
}
if (!isHtmlElement(handle)) {
warning('drag handle needs to be a HTMLElement') ;
return null;
}
return handle;
}
function useFocusMarshal(contextId) {
const entriesRef = React.useRef({});
const recordRef = React.useRef(null);
const restoreFocusFrameRef = React.useRef(null);
const isMountedRef = React.useRef(false);
const register = useMemoOne.useCallback(function register(id, focus) {
const entry = {
id,
focus
};
entriesRef.current[id] = entry;
return function unregister() {
const entries = entriesRef.current;
const current = entries[id];
if (current !== entry) {
delete entries[id];
}
};
}, []);
const tryGiveFocus = useMemoOne.useCallback(function tryGiveFocus(tryGiveFocusTo) {
const handle = findDragHandle(contextId, tryGiveFocusTo);
if (handle && handle !== document.activeElement) {
handle.focus();
}
}, [contextId]);
const tryShiftRecord = useMemoOne.useCallback(function tryShiftRecord(previous, redirectTo) {
if (recordRef.current === previous) {
recordRef.current = redirectTo;
}
}, []);
const tryRestoreFocusRecorded = useMemoOne.useCallback(function tryRestoreFocusRecorded() {
if (restoreFocusFrameRef.current) {
return;
}
if (!isMountedRef.current) {
return;
}
restoreFocusFrameRef.current = requestAnimationFrame(() => {
restoreFocusFrameRef.current = null;
const record = recordRef.current;
if (record) {
tryGiveFocus(record);
}
});
}, [tryGiveFocus]);
const tryRecordFocus = useMemoOne.useCallback(function tryRecordFocus(id) {
recordRef.current = null;
const focused = document.activeElement;
if (!focused) {
return;
}
if (focused.getAttribute(dragHandle.draggableId) !== id) {
return;
}
recordRef.current = id;
}, []);
useLayoutEffect(() => {
isMountedRef.current = true;
return function clearFrameOnUnmount() {
isMountedRef.current = false;
const frameId = restoreFocusFrameRef.current;
if (frameId) {
cancelAnimationFrame(frameId);
}
};
}, []);
const marshal = useMemoOne.useMemo(() => ({
register,
tryRecordFocus,
tryRestoreFocusRecorded,
tryShiftRecord
}), [register, tryRecordFocus, tryRestoreFocusRecorded, tryShiftRecord]);
return marshal;
}
function createRegistry() {
const entries = {
draggables: {},
droppables: {}
};
const subscribers = [];
function subscribe(cb) {
subscribers.push(cb);
return function unsubscribe() {
const index = subscribers.indexOf(cb);
if (index === -1) {
return;
}
subscribers.splice(index, 1);
};
}
function notify(event) {
if (subscribers.length) {
subscribers.forEach(cb => cb(event));
}
}
function findDraggableById(id) {
return entries.draggables[id] || null;
}
function getDraggableById(id) {
const entry = findDraggableById(id);
!entry ? invariant(false, `Cannot find draggable entry with id [${id}]`) : void 0;
return entry;
}
const draggableAPI = {
register: entry => {
entries.draggables[entry.descriptor.id] = entry;
notify({
type: 'ADDITION',
value: entry
});
},
update: (entry, last) => {
const current = entries.draggables[last.descriptor.id];
if (!current) {
return;
}
if (current.uniqueId !== entry.uniqueId) {
return;
}
delete entries.draggables[last.descriptor.id];
entries.draggables[entry.descriptor.id] = entry;
},
unregister: entry => {
const draggableId = entry.descriptor.id;
const current = findDraggableById(draggableId);
if (!current) {
return;
}
if (entry.uniqueId !== current.uniqueId) {
return;
}
delete entries.draggables[draggableId];
if (entries.droppables[entry.descriptor.droppableId]) {
notify({
type: 'REMOVAL',
value: entry
});
}
},
getById: getDraggableById,
findById: findDraggableById,
exists: id => Boolean(findDraggableById(id)),
getAllByType: type => Object.values(entries.draggables).filter(entry => entry.descriptor.type === type)
};
function findDroppableById(id) {
return entries.droppables[id] || null;
}
function getDroppableById(id) {
const entry = findDroppableById(id);
!entry ? invariant(false, `Cannot find droppable entry with id [${id}]`) : void 0;
return entry;
}
const droppableAPI = {
register: entry => {
entries.droppables[entry.descriptor.id] = entry;
},
unregister: entry => {
const current = findDroppableById(entry.descriptor.id);
if (!current) {
return;
}
if (entry.uniqueId !== current.uniqueId) {
return;
}
delete entries.droppables[entry.descriptor.id];
},
getById: getDroppableById,
findById: findDroppableById,
exists: id => Boolean(findDroppableById(id)),
getAllByType: type => Object.values(entries.droppables).filter(entry => entry.descriptor.type === type)
};
function clean() {
entries.draggables = {};
entries.droppables = {};
subscribers.length = 0;
}
return {
draggable: draggableAPI,
droppable: droppableAPI,
subscribe,
clean
};
}
function useRegistry() {
const registry = useMemoOne.useMemo(createRegistry, []);
React.useEffect(() => {
return function unmount() {
if (React__default["default"].version.startsWith('16') || React__default["default"].version.startsWith('17')) {
requestAnimationFrame(registry.clean);
} else {
registry.clean();
}
};
}, [registry]);
return registry;
}
var StoreContext = React__default["default"].createContext(null);
var getBodyElement = (() => {
const body = document.body;
!body ? invariant(false, 'Cannot find document.body') : void 0;
return body;
});
const visuallyHidden = {
position: 'absolute',
width: '1px',
height: '1px',
margin: '-1px',
border: '0',
padding: '0',
overflow: 'hidden',
clip: 'rect(0 0 0 0)',
'clip-path': 'inset(100%)'
};
var visuallyHidden$1 = visuallyHidden;
const getId = contextId => `rfd-announcement-${contextId}`;
function useAnnouncer(contextId) {
const id = useMemoOne.useMemo(() => getId(contextId), [contextId]);
const ref = React.useRef(null);
React.useEffect(function setup() {
const el = document.createElement('div');
ref.current = el;
el.id = id;
el.setAttribute('aria-live', 'assertive');
el.setAttribute('aria-atomic', 'true');
_extends__default["default"](el.style, visuallyHidden$1);
getBodyElement().appendChild(el);
return function cleanup() {
setTimeout(function remove() {
const body = getBodyElement();
if (body.contains(el)) {
body.removeChild(el);
}
if (el === ref.current) {
ref.current = null;
}
});
};
}, [id]);
const announce = useMemoOne.useCallback(message => {
const el = ref.current;
if (el) {
el.textContent = message;
return;
}
warning(`
A screen reader message was trying to be announced but it was unable to do so.
This can occur if you unmount your <DragDropContext /> in your onDragEnd.
Consider calling provided.announce() before the unmount so that the instruction will
not be lost for users relying on a screen reader.
Message not passed to screen reader:
"${message}"
`) ;
}, []);
return announce;
}
let count$1 = 0;
const defaults$2 = {
separator: '::'
};
function resetDeprecatedUniqueId() {
count$1 = 0;
}
function useDeprecatedUniqueId(prefix, options) {
if (options === void 0) {
options = defaults$2;
}
return useMemoOne.useMemo(() => `${prefix}${options.separator}${count$1++}`, [options.separator, prefix]);
}
function useUniqueId(prefix, options) {
if (options === void 0) {
options = defaults$2;
}
const id = React__default["default"].useId();
return useMemoOne.useMemo(() => `${prefix}${options.separator}${id}`, [options.separator, prefix, id]);
}
var useUniqueId$1 = 'useId' in React__default["default"] ? useUniqueId : useDeprecatedUniqueId;
function getElementId(_ref) {
let {
contextId,
uniqueId
} = _ref;
return `rfd-hidden-text-${contextId}-${uniqueId}`;
}
function useHiddenTextElement(_ref2) {
let {
contextId,
text
} = _ref2;
const uniqueId = useUniqueId$1('hidden-text', {
separator: '-'
});
const id = useMemoOne.useMemo(() => getElementId({
contextId,
uniqueId
}), [uniqueId, contextId]);
React.useEffect(function mount() {
const el = document.createElement('div');
el.id = id;
el.textContent = text;
el.style.display = 'none';
getBodyElement().appendChild(el);
return function unmount() {
const body = getBodyElement();
if (body.contains(el)) {
body.removeChild(el);
}
};
}, [id, text]);
return id;
}
var AppContext = React__default["default"].createContext(null);
var peerDependencies = {
react: "^16.8.5 || ^17.0.0 || ^18.0.0",
"react-dom": "^16.8.5 || ^17.0.0 || ^18.0.0"
};
const semver = /(\d+)\.(\d+)\.(\d+)/;
const getVersion = value => {
const result = semver.exec(value);
!(result != null) ? invariant(false, `Unable to parse React version ${value}`) : void 0;
const major = Number(result[1]);
const minor = Number(result[2]);
const patch = Number(result[3]);
return {
major,
minor,
patch,
raw: value
};
};
const isSatisfied = (expected, actual) => {
if (actual.major > expected.major) {
return true;
}
if (actual.major < expected.major) {
return false;
}
if (actual.minor > expected.minor) {
return true;
}
if (actual.minor < expected.minor) {
return false;
}
return actual.patch >= expected.patch;
};
var checkReactVersion = ((peerDepValue, actualValue) => {
const peerDep = getVersion(peerDepValue);
const actual = getVersion(actualValue);
if (isSatisfied(peerDep, actual)) {
return;
}
warning(`
React version: [${actual.raw}]
does not satisfy expected peer dependency version: [${peerDep.raw}]
This can result in run time bugs, and even fatal crashes
`) ;
});
const suffix = `
We expect a html5 doctype: <!doctype html>
This is to ensure consistent browser layout and measurement
More information: https://github.com/hello-pangea/dnd/blob/main/docs/guides/doctype.md
`;
var checkDoctype = (doc => {
const doctype = doc.doctype;
if (!doctype) {
warning(`
No <!doctype html> found.
${suffix}
`) ;
return;
}
if (doctype.name.toLowerCase() !== 'html') {
warning(`
Unexpected <!doctype> found: (${doctype.name})
${suffix}
`) ;
}
if (doctype.publicId !== '') {
warning(`
Unexpected <!doctype> publicId found: (${doctype.publicId})
A html5 doctype does not have a publicId
${suffix}
`) ;
}
});
function useDev(useHook) {
{
useHook();
}
}
function useDevSetupWarning(fn, inputs) {
useDev(() => {
React.useEffect(() => {
try {
fn();
} catch (e) {
error(`
A setup problem was encountered.
> ${e.message}
`);
}
}, inputs);
});
}
function useStartupValidation() {
useDevSetupWarning(() => {
checkReactVersion(peerDependencies.react, React__default["default"].version);
checkDoctype(document);
}, []);
}
function usePrevious(current) {
const ref = React.useRef(current);
React.useEffect(() => {
ref.current = current;
});
return ref;
}
function create() {
let lock = null;
function isClaimed() {
return Boolean(lock);
}
function isActive(value) {
return value === lock;
}
function claim(abandon) {
!!lock ? invariant(false, 'Cannot claim lock as it is already claimed') : void 0;
const newLock = {
abandon
};
lock = newLock;
return newLock;
}
function release() {
!lock ? invariant(false, 'Cannot release lock when there is no lock') : void 0;
lock = null;
}
function tryAbandon() {
if (lock) {
lock.abandon();
release();
}
}
return {
isClaimed,
isActive,
claim,
release,
tryAbandon
};
}
function isDragging(state) {
if (state.phase === 'IDLE' || state.phase === 'DROP_ANIMATING') {
return false;
}
return state.isDragging;
}
const tab = 9;
const enter = 13;
const escape$2 = 27;
const space = 32;
const pageUp = 33;
const pageDown = 34;
const end = 35;
const home = 36;
const arrowLeft = 37;
const arrowUp = 38;
const arrowRight = 39;
const arrowDown = 40;
const preventedKeys = {
[enter]: true,
[tab]: true
};
var preventStandardKeyEvents = (event => {
if (preventedKeys[event.keyCode]) {
event.preventDefault();
}
});
const supportedEventName = (() => {
const base = 'visibilitychange';
if (typeof document === 'undefined') {
return base;
}
const candidates = [base, `ms${base}`, `webkit${base}`, `moz${base}`, `o${base}`];
const supported = candidates.find(eventName => `on${eventName}` in document);
return supported || base;
})();
var supportedPageVisibilityEventName = supportedEventName;
const primaryButton = 0;
const sloppyClickThreshold = 5;
function isSloppyClickThresholdExceeded(original, current) {
return Math.abs(current.x - original.x) >= sloppyClickThreshold || Math.abs(current.y - original.y) >= sloppyClickThreshold;
}
const idle$1 = {
type: 'IDLE'
};
function getCaptureBindings(_ref) {
let {
cancel,
completed,
getPhase,
setPhase
} = _ref;
return [{
eventName: 'mousemove',
fn: event => {
const {
button,
clientX,
clientY
} = event;
if (button !== primaryButton) {
return;
}
const point = {
x: clientX,
y: clientY
};
const phase = getPhase();
if (phase.type === 'DRAGGING') {
event.preventDefault();
phase.actions.move(point);
return;
}
!(phase.type === 'PENDING') ? invariant(false, 'Cannot be IDLE') : void 0;
const pending = phase.point;
if (!isSloppyClickThresholdExceeded(pending, point)) {
return;
}
event.preventDefault();
const actions = phase.actions.fluidLift(point);
setPhase({
type: 'DRAGGING',
actions
});
}
}, {
eventName: 'mouseup',
fn: event => {
const phase = getPhase();
if (phase.type !== 'DRAGGING') {
cancel();
return;
}
event.preventDefault();
phase.actions.drop({
shouldBlockNextClick: true
});
completed();
}
}, {
eventName: 'mousedown',
fn: event => {
if (getPhase().type === 'DRAGGING') {
event.preventDefault();
}
cancel();
}
}, {
eventName: 'keydown',
fn: event => {
const phase = getPhase();
if (phase.type === 'PENDING') {
cancel();
return;
}
if (event.keyCode === escape$2) {
event.preventDefault();
cancel();
return;
}
preventStandardKeyEvents(event);
}
}, {
eventName: 'resize',
fn: cancel
}, {
eventName: 'scroll',
options: {
passive: true,
capture: false
},
fn: () => {
if (getPhase().type === 'PENDING') {
cancel();
}
}
},
{
eventName: 'webkitmouseforcedown',
fn: event => {
const phase = getPhase();
!(phase.type !== 'IDLE') ? invariant(false, 'Unexpected phase') : void 0;
if (phase.actions.shouldRespectForcePress()) {
cancel();
return;
}
event.preventDefault();
}
},
{
eventName: supportedPageVisibilityEventName,
fn: cancel
}];
}
function useMouseSensor(api) {
const phaseRef = React.useRef(idle$1);
const unbindEventsRef = React.useRef(noop$2);
const startCaptureBinding = useMemoOne.useMemo(() => ({
eventName: 'mousedown',
fn: function onMouseDown(event) {
if (event.defaultPrevented) {
return;
}
if (event.button !== primaryButton) {
return;
}
if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) {
return;
}
const draggableId = api.findClosestDraggableId(event);
if (!draggableId) {
return;
}
const actions = api.tryGetLock(draggableId,
stop, {
sourceEvent: event
});
if (!actions) {
return;
}
event.preventDefault();
const point = {
x: event.clientX,
y: event.clientY
};
unbindEventsRef.current();
startPendingDrag(actions, point);
}
}),
[api]);
const preventForcePressBinding = useMemoOne.useMemo(() => ({
eventName: 'webkitmouseforcewillbegin',
fn: event => {
if (event.defaultPrevented) {
return;
}
const id = api.findClosestDraggableId(event);
if (!id) {
return;
}
const options = api.findOptionsForDraggable(id);
if (!options) {
return;
}
if (options.shouldRespectForcePress) {
return;
}
if (!api.canGetLock(id)) {
return;
}
event.preventDefault();
}
}), [api]);
const listenForCapture = useMemoOne.useCallback(function listenForCapture() {
const options = {
passive: false,
capture: true
};
unbindEventsRef.current = bindEvents(window, [preventForcePressBinding, startCaptureBinding], options);
}, [preventForcePressBinding, startCaptureBinding]);
const stop = useMemoOne.useCallback(() => {
const current = phaseRef.current;
if (current.type === 'IDLE') {
return;
}
phaseRef.current = idle$1;
unbindEventsRef.current();
listenForCapture();
}, [listenForCapture]);
const cancel = useMemoOne.useCallback(() => {
const phase = phaseRef.current;
stop();
if (phase.type === 'DRAGGING') {
phase.actions.cancel({
shouldBlockNextClick: true
});
}
if (phase.type === 'PENDING') {
phase.actions.abort();
}
}, [stop]);
const bindCapturingEvents = useMemoOne.useCallback(function bindCapturingEvents() {
const options = {
capture: true,
passive: false
};
const bindings = getCaptureBindings({
cancel,
completed: stop,
getPhase: () => phaseRef.current,
setPhase: phase => {
phaseRef.current = phase;
}
});
unbindEventsRef.current = bindEvents(window, bindings, options);
}, [cancel, stop]);
const startPendingDrag = useMemoOne.useCallback(function startPendingDrag(actions, point) {
!(phaseRef.current.type === 'IDLE') ? invariant(false, 'Expected to move from IDLE to PENDING drag') : void 0;
phaseRef.current = {
type: 'PENDING',
point,
actions
};
bindCapturingEvents();
}, [bindCapturingEvents]);
useLayoutEffect(function mount() {
listenForCapture();
return function unmount() {
unbindEventsRef.current();
};
}, [listenForCapture]);
}
function noop$1() {}
const scrollJumpKeys = {
[pageDown]: true,
[pageUp]: true,
[home]: true,
[end]: true
};
function getDraggingBindings(actions, stop) {
function cancel() {
stop();
actions.cancel();
}
function drop() {
stop();
actions.drop();
}
return [{
eventName: 'keydown',
fn: event => {
if (event.keyCode === escape$2) {
event.preventDefault();
cancel();
return;
}
if (event.keyCode === space) {
event.preventDefault();
drop();
return;
}
if (event.keyCode === arrowDown) {
event.preventDefault();
actions.moveDown();
return;
}
if (event.keyCode === arrowUp) {
event.preventDefault();
actions.moveUp();
return;
}
if (event.keyCode === arrowRight) {
event.preventDefault();
actions.moveRight();
return;
}
if (event.keyCode === arrowLeft) {
event.preventDefault();
actions.moveLeft();
return;
}
if (scrollJumpKeys[event.keyCode]) {
event.preventDefault();
return;
}
preventStandardKeyEvents(event);
}
},
{
eventName: 'mousedown',
fn: cancel
}, {
eventName: 'mouseup',
fn: cancel
}, {
eventName: 'click',
fn: cancel
}, {
eventName: 'touchstart',
fn: cancel
},
{
eventName: 'resize',
fn: cancel
},
{
eventName: 'wheel',
fn: cancel,
options: {
passive: true
}
},
{
eventName: supportedPageVisibilityEventName,
fn: cancel
}];
}
function useKeyboardSensor(api) {
const unbindEventsRef = React.useRef(noop$1);
const startCaptureBinding = useMemoOne.useMemo(() => ({
eventName: 'keydown',
fn: function onKeyDown(event) {
if (event.defaultPrevented) {
return;
}
if (event.keyCode !== space) {
return;
}
const draggableId = api.findClosestDraggableId(event);
if (!draggableId) {
return;
}
const preDrag = api.tryGetLock(draggableId,
stop, {
sourceEvent: event
});
if (!preDrag) {
return;
}
event.preventDefault();
let isCapturing = true;
const actions = preDrag.snapLift();
unbindEventsRef.current();
function stop() {
!isCapturing ? invariant(false, 'Cannot stop capturing a keyboard drag when not capturing') : void 0;
isCapturing = false;
unbindEventsRef.current();
listenForCapture();
}
unbindEventsRef.current = bindEvents(window, getDraggingBindings(actions, stop), {
capture: true,
passive: false
});
}
}),
[api]);
const listenForCapture = useMemoOne.useCallback(function tryStartCapture() {
const options = {
passive: false,
capture: true
};
unbindEventsRef.current = bindEvents(window, [startCaptureBinding], options);
}, [startCaptureBinding]);
useLayoutEffect(function mount() {
listenForCapture();
return function unmount() {
unbindEventsRef.current();
};
}, [listenForCapture]);
}
const idle = {
type: 'IDLE'
};
const timeForLongPress = 120;
const forcePressThreshold = 0.15;
function getWindowBindings(_ref) {
let {
cancel,
getPhase
} = _ref;
return [
{
eventName: 'orientationchange',
fn: cancel
},
{
eventName: 'resize',
fn: cancel
},
{
eventName: 'contextmenu',
fn: event => {
event.preventDefault();
}
},
{
eventName: 'keydown',
fn: event => {
if (getPhase().type !== 'DRAGGING') {
cancel();
return;
}
if (event.keyCode === escape$2) {
event.preventDefault();
}
cancel();
}
},
{
eventName: supportedPageVisibilityEventName,
fn: cancel
}];
}
function getHandleBindings(_ref2) {
let {
cancel,
completed,
getPhase
} = _ref2;
return [{
eventName: 'touchmove',
options: {
capture: false
},
fn: event => {
const phase = getPhase();
if (phase.type !== 'DRAGGING') {
cancel();
return;
}
phase.hasMoved = true;
const {
clientX,
clientY
} = event.touches[0];
const point = {
x: clientX,
y: clientY
};
event.preventDefault();
phase.actions.move(point);
}
}, {
eventName: 'touchend',
fn: event => {
const phase = getPhase();
if (phase.type !== 'DRAGGING') {
cancel();
return;
}
event.preventDefault();
phase.actions.drop({
shouldBlockNextClick: true
});
completed();
}
}, {
eventName: 'touchcancel',
fn: event => {
if (getPhase().type !== 'DRAGGING') {
cancel();
return;
}
event.preventDefault();
cancel();
}
},
{
eventName: 'touchforcechange',
fn: event => {
const phase = getPhase();
!(phase.type !== 'IDLE') ? invariant(false) : void 0;
const touch = event.touches[0];
if (!touch) {
return;
}
const isForcePress = touch.force >= forcePressThreshold;
if (!isForcePress) {
return;
}
const shouldRespect = phase.actions.shouldRespectForcePress();
if (phase.type === 'PENDING') {
if (shouldRespect) {
cancel();
}
return;
}
if (shouldRespect) {
if (phase.hasMoved) {
event.preventDefault();
return;
}
cancel();
return;
}
event.preventDefault();
}
},
{
eventName: supportedPageVisibilityEventName,
fn: cancel
}
];
}
function useTouchSensor(api) {
const phaseRef = React.useRef(idle);
const unbindEventsRef = React.useRef(noop$2);
const getPhase = useMemoOne.useCallback(function getPhase() {
return phaseRef.current;
}, []);
const setPhase = useMemoOne.useCallback(function setPhase(phase) {
phaseRef.current = phase;
}, []);
const startCaptureBinding = useMemoOne.useMemo(() => ({
eventName: 'touchstart',
fn: function onTouchStart(event) {
if (event.defaultPrevented) {
return;
}
const draggableId = api.findClosestDraggableId(event);
if (!draggableId) {
return;
}
const actions = api.tryGetLock(draggableId,
stop, {
sourceEvent: event
});
if (!actions) {
return;
}
const touch = event.touches[0];
const {
clientX,
clientY
} = touch;
const point = {
x: clientX,
y: clientY
};
unbindEventsRef.current();
startPendingDrag(actions, point);
}
}),
[api]);
const listenForCapture = useMemoOne.useCallback(function listenForCapture() {
const options = {
capture: true,
passive: false
};
unbindEventsRef.current = bindEvents(window, [startCaptureBinding], options);
}, [startCaptureBinding]);
const stop = useMemoOne.useCallback(() => {
const current = phaseRef.current;
if (current.type === 'IDLE') {
return;
}
if (current.type === 'PENDING') {
clearTimeout(current.longPressTimerId);
}
setPhase(idle);
unbindEventsRef.current();
listenForCapture();
}, [listenForCapture, setPhase]);
const cancel = useMemoOne.useCallback(() => {
const phase = phaseRef.current;
stop();
if (phase.type === 'DRAGGING') {
phase.actions.cancel({
shouldBlockNextClick: true
});
}
if (phase.type === 'PENDING') {
phase.actions.abort();
}
}, [stop]);
const bindCapturingEvents = useMemoOne.useCallback(function bindCapturingEvents() {
const options = {
capture: true,
passive: false
};
const args = {
cancel,
completed: stop,
getPhase
};
const unbindTarget = bindEvents(window, getHandleBindings(args), options);
const unbindWindow = bindEvents(window, getWindowBindings(args), options);
unbindEventsRef.current = function unbindAll() {
unbindTarget();
unbindWindow();
};
}, [cancel, getPhase, stop]);
const startDragging = useMemoOne.useCallback(function startDragging() {
const phase = getPhase();
!(phase.type === 'PENDING') ? invariant(false, `Cannot start dragging from phase ${phase.type}`) : void 0;
const actions = phase.actions.fluidLift(phase.point);
setPhase({
type: 'DRAGGING',
actions,
hasMoved: false
});
}, [getPhase, setPhase]);
const startPendingDrag = useMemoOne.useCallback(function startPendingDrag(actions, point) {
!(getPhase().type === 'IDLE') ? invariant(false, 'Expected to move from IDLE to PENDING drag') : void 0;
const longPressTimerId = setTimeout(startDragging, timeForLongPress);
setPhase({
type: 'PENDING',
point,
actions,
longPressTimerId
});
bindCapturingEvents();
}, [bindCapturingEvents, getPhase, setPhase, startDragging]);
useLayoutEffect(function mount() {
listenForCapture();
return function unmount() {
unbindEv
Showing 512.00 KB of 4.39 MB. Use Edit/Download for full content.
Directory Contents
Dirs: 0 × Files: 5