projex-ui-dev
Version:
Projex' user interface
25,689 lines • 979 kB
JavaScript
import * as React from 'react';
import React__default, { createContext, useContext, useEffect, useState, useRef, useMemo as useMemo$1, useLayoutEffect as useLayoutEffect$1, useCallback, forwardRef, useImperativeHandle } from 'react';
import Link from 'next/link.js';
import ReactDOM, { createPortal, unstable_batchedUpdates, flushSync } from 'react-dom';
import { useRouter } from 'next/router.js';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest$h(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
function styleInject(css, ref) {
if (ref === void 0) ref = {};
var insertAt = ref.insertAt;
if (!css || typeof document === 'undefined') {
return;
}
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (insertAt === 'top') {
if (head.firstChild) {
head.insertBefore(style, head.firstChild);
} else {
head.appendChild(style);
}
} else {
head.appendChild(style);
}
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}
var css_248z$o = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.Button-module_button__y6Gwz {\n padding: 0.75rem 2rem;\n font-weight: 700;\n font-size: 1rem;\n text-align: center;\n background-color: #002559;\n border: 1px solid #002559;\n color: white;\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 0.625rem;\n transition: 0.3s;\n}\n.Button-module_button__y6Gwz:hover:not(:disabled) {\n cursor: pointer;\n background-color: white;\n color: #002559;\n}\n.Button-module_button__y6Gwz.Button-module_secondary__pP3kM {\n background-color: #ffffff;\n color: #002559;\n}\n.Button-module_button__y6Gwz.Button-module_secondary__pP3kM:hover:not(:disabled) {\n background-color: #002559;\n color: white;\n}\n.Button-module_button__y6Gwz.Button-module_warning__jKxPU {\n background-color: #F4971F;\n border: 1px solid #F4971F;\n color: #ffffff;\n}\n.Button-module_button__y6Gwz.Button-module_warning__jKxPU:hover:not(:disabled) {\n background-color: #ffffff;\n color: #F4971F;\n}\n.Button-module_button__y6Gwz.Button-module_alert__uxAyk {\n background-color: #B8181E;\n border: 1px solid #B8181E;\n color: #ffffff;\n}\n.Button-module_button__y6Gwz.Button-module_alert__uxAyk:hover:not(:disabled) {\n background-color: #ffffff;\n color: #B8181E;\n}\n.Button-module_button__y6Gwz.Button-module_text__Dyuvh {\n background-color: transparent;\n border: 1px solid transparent;\n color: #333333;\n font-weight: 400;\n}\n.Button-module_button__y6Gwz.Button-module_text__Dyuvh:hover:not(:disabled) {\n color: #999999;\n}\n.Button-module_button__y6Gwz.Button-module_text_gray__xKaV2 {\n background-color: transparent;\n border: 1px solid transparent;\n font-weight: 400;\n color: #999999;\n}\n.Button-module_button__y6Gwz.Button-module_textAlert__QsYSY {\n background-color: transparent;\n border: 1px solid transparent;\n color: #B8181E;\n font-weight: 400;\n}\n.Button-module_button__y6Gwz.Button-module_textAlert__QsYSY:hover:not(:disabled) {\n color: #999999;\n}\n.Button-module_button__y6Gwz.Button-module_block__nXEX2 {\n width: 100%;\n}\n.Button-module_button__y6Gwz.Button-module_right__qMoJW {\n flex-direction: row-reverse;\n}\n.Button-module_button__y6Gwz.Button-module_small__utRIp {\n padding: 0.5rem 1rem;\n}\n.Button-module_button__y6Gwz:disabled, .Button-module_button__y6Gwz.Button-module_loading__7LCMc {\n opacity: 30%;\n cursor: not-allowed;\n}\n.Button-module_button__y6Gwz.Button-module_loading__7LCMc:hover {\n cursor: wait;\n}";
var styles$o = {"button":"Button-module_button__y6Gwz","secondary":"Button-module_secondary__pP3kM","warning":"Button-module_warning__jKxPU","alert":"Button-module_alert__uxAyk","text":"Button-module_text__Dyuvh","text_gray":"Button-module_text_gray__xKaV2","textAlert":"Button-module_textAlert__QsYSY","block":"Button-module_block__nXEX2","right":"Button-module_right__qMoJW","small":"Button-module_small__utRIp","loading":"Button-module_loading__7LCMc"};
styleInject(css_248z$o);
var IconContext$1 = /*#__PURE__*/createContext({});
var Context$3 = IconContext$1;
function _extends$1() {
_extends$1 = 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$1.apply(this, arguments);
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(r, l) {
var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (null != t) {
var e,
n,
i,
u,
a = [],
f = !0,
o = !1;
try {
if (i = (t = t.call(r)).next, 0 === l) {
if (Object(t) !== t) return;
f = !1;
} else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
} catch (r) {
o = !0, n = r;
} finally {
try {
if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
} finally {
if (o) throw n;
}
}
return a;
}
}
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 _typeof$1(o) {
"@babel/helpers - typeof";
return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof$1(o);
}
function _toPrimitive(input, hint) {
if (_typeof$1(input) !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (_typeof$1(res) !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, "string");
return _typeof$1(key) === "symbol" ? key : String(key);
}
function _defineProperty$1(obj, key, value) {
key = _toPropertyKey(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;
}
var classnames = {exports: {}};
/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
(function (module) {
/* global define */
(function () {
var hasOwn = {}.hasOwnProperty;
function classNames() {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
if (arg.length) {
var inner = classNames.apply(null, arg);
if (inner) {
classes.push(inner);
}
}
} else if (argType === 'object') {
if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {
classes.push(arg.toString());
continue;
}
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else {
window.classNames = classNames;
}
})();
} (classnames));
var classnamesExports = classnames.exports;
var classNames = /*@__PURE__*/getDefaultExportFromCjs(classnamesExports);
/**
* Take input from [0, n] and return it as [0, 1]
* @hidden
*/
function bound01(n, max) {
if (isOnePointZero(n)) {
n = '100%';
}
var isPercent = isPercentage(n);
n = max === 360 ? n : Math.min(max, Math.max(0, parseFloat(n)));
// Automatically convert percentage into number
if (isPercent) {
n = parseInt(String(n * max), 10) / 100;
}
// Handle floating point rounding errors
if (Math.abs(n - max) < 0.000001) {
return 1;
}
// Convert into [0, 1] range if it isn't already
if (max === 360) {
// If n is a hue given in degrees,
// wrap around out-of-range values into [0, 360] range
// then convert into [0, 1].
n = (n < 0 ? n % max + max : n % max) / parseFloat(String(max));
} else {
// If n not a hue given in degrees
// Convert into [0, 1] range if it isn't already.
n = n % max / parseFloat(String(max));
}
return n;
}
/**
* Force a number between 0 and 1
* @hidden
*/
function clamp01(val) {
return Math.min(1, Math.max(0, val));
}
/**
* Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
* <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
* @hidden
*/
function isOnePointZero(n) {
return typeof n === 'string' && n.indexOf('.') !== -1 && parseFloat(n) === 1;
}
/**
* Check to see if string passed in is a percentage
* @hidden
*/
function isPercentage(n) {
return typeof n === 'string' && n.indexOf('%') !== -1;
}
/**
* Return a valid alpha value [0,1] with all invalid values being set to 1
* @hidden
*/
function boundAlpha(a) {
a = parseFloat(a);
if (isNaN(a) || a < 0 || a > 1) {
a = 1;
}
return a;
}
/**
* Replace a decimal with it's percentage value
* @hidden
*/
function convertToPercentage(n) {
if (n <= 1) {
return "".concat(Number(n) * 100, "%");
}
return n;
}
/**
* Force a hex value to have 2 characters
* @hidden
*/
function pad2(c) {
return c.length === 1 ? '0' + c : String(c);
}
// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
// <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
/**
* Handle bounds / percentage checking to conform to CSS color spec
* <http://www.w3.org/TR/css3-color/>
* *Assumes:* r, g, b in [0, 255] or [0, 1]
* *Returns:* { r, g, b } in [0, 255]
*/
function rgbToRgb(r, g, b) {
return {
r: bound01(r, 255) * 255,
g: bound01(g, 255) * 255,
b: bound01(b, 255) * 255
};
}
/**
* Converts an RGB color value to HSL.
* *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
* *Returns:* { h, s, l } in [0,1]
*/
function rgbToHsl(r, g, b) {
r = bound01(r, 255);
g = bound01(g, 255);
b = bound01(b, 255);
var max = Math.max(r, g, b);
var min = Math.min(r, g, b);
var h = 0;
var s = 0;
var l = (max + min) / 2;
if (max === min) {
s = 0;
h = 0; // achromatic
} else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return {
h: h,
s: s,
l: l
};
}
function hue2rgb(p, q, t) {
if (t < 0) {
t += 1;
}
if (t > 1) {
t -= 1;
}
if (t < 1 / 6) {
return p + (q - p) * (6 * t);
}
if (t < 1 / 2) {
return q;
}
if (t < 2 / 3) {
return p + (q - p) * (2 / 3 - t) * 6;
}
return p;
}
/**
* Converts an HSL color value to RGB.
*
* *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
* *Returns:* { r, g, b } in the set [0, 255]
*/
function hslToRgb(h, s, l) {
var r;
var g;
var b;
h = bound01(h, 360);
s = bound01(s, 100);
l = bound01(l, 100);
if (s === 0) {
// achromatic
g = l;
b = l;
r = l;
} else {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
}
return {
r: r * 255,
g: g * 255,
b: b * 255
};
}
/**
* Converts an RGB color value to HSV
*
* *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
* *Returns:* { h, s, v } in [0,1]
*/
function rgbToHsv(r, g, b) {
r = bound01(r, 255);
g = bound01(g, 255);
b = bound01(b, 255);
var max = Math.max(r, g, b);
var min = Math.min(r, g, b);
var h = 0;
var v = max;
var d = max - min;
var s = max === 0 ? 0 : d / max;
if (max === min) {
h = 0; // achromatic
} else {
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return {
h: h,
s: s,
v: v
};
}
/**
* Converts an HSV color value to RGB.
*
* *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
* *Returns:* { r, g, b } in the set [0, 255]
*/
function hsvToRgb(h, s, v) {
h = bound01(h, 360) * 6;
s = bound01(s, 100);
v = bound01(v, 100);
var i = Math.floor(h);
var f = h - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
var mod = i % 6;
var r = [v, q, p, p, t, v][mod];
var g = [t, v, v, q, p, p][mod];
var b = [p, p, t, v, v, q][mod];
return {
r: r * 255,
g: g * 255,
b: b * 255
};
}
/**
* Converts an RGB color to hex
*
* Assumes r, g, and b are contained in the set [0, 255]
* Returns a 3 or 6 character hex
*/
function rgbToHex(r, g, b, allow3Char) {
var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))];
// Return a 3 character hex if possible
if (allow3Char && hex[0].startsWith(hex[0].charAt(1)) && hex[1].startsWith(hex[1].charAt(1)) && hex[2].startsWith(hex[2].charAt(1))) {
return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
}
return hex.join('');
}
/**
* Converts an RGBA color plus alpha transparency to hex
*
* Assumes r, g, b are contained in the set [0, 255] and
* a in [0, 1]. Returns a 4 or 8 character rgba hex
*/
// eslint-disable-next-line max-params
function rgbaToHex(r, g, b, a, allow4Char) {
var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))];
// Return a 4 character hex if possible
if (allow4Char && hex[0].startsWith(hex[0].charAt(1)) && hex[1].startsWith(hex[1].charAt(1)) && hex[2].startsWith(hex[2].charAt(1)) && hex[3].startsWith(hex[3].charAt(1))) {
return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
}
return hex.join('');
}
/** Converts a decimal to a hex value */
function convertDecimalToHex(d) {
return Math.round(parseFloat(d) * 255).toString(16);
}
/** Converts a hex value to a decimal */
function convertHexToDecimal(h) {
return parseIntFromHex(h) / 255;
}
/** Parse a base-16 hex value into a base-10 integer */
function parseIntFromHex(val) {
return parseInt(val, 16);
}
function numberInputToObject(color) {
return {
r: color >> 16,
g: (color & 0xff00) >> 8,
b: color & 0xff
};
}
// https://github.com/bahamas10/css-color-names/blob/master/css-color-names.json
/**
* @hidden
*/
var names = {
aliceblue: '#f0f8ff',
antiquewhite: '#faebd7',
aqua: '#00ffff',
aquamarine: '#7fffd4',
azure: '#f0ffff',
beige: '#f5f5dc',
bisque: '#ffe4c4',
black: '#000000',
blanchedalmond: '#ffebcd',
blue: '#0000ff',
blueviolet: '#8a2be2',
brown: '#a52a2a',
burlywood: '#deb887',
cadetblue: '#5f9ea0',
chartreuse: '#7fff00',
chocolate: '#d2691e',
coral: '#ff7f50',
cornflowerblue: '#6495ed',
cornsilk: '#fff8dc',
crimson: '#dc143c',
cyan: '#00ffff',
darkblue: '#00008b',
darkcyan: '#008b8b',
darkgoldenrod: '#b8860b',
darkgray: '#a9a9a9',
darkgreen: '#006400',
darkgrey: '#a9a9a9',
darkkhaki: '#bdb76b',
darkmagenta: '#8b008b',
darkolivegreen: '#556b2f',
darkorange: '#ff8c00',
darkorchid: '#9932cc',
darkred: '#8b0000',
darksalmon: '#e9967a',
darkseagreen: '#8fbc8f',
darkslateblue: '#483d8b',
darkslategray: '#2f4f4f',
darkslategrey: '#2f4f4f',
darkturquoise: '#00ced1',
darkviolet: '#9400d3',
deeppink: '#ff1493',
deepskyblue: '#00bfff',
dimgray: '#696969',
dimgrey: '#696969',
dodgerblue: '#1e90ff',
firebrick: '#b22222',
floralwhite: '#fffaf0',
forestgreen: '#228b22',
fuchsia: '#ff00ff',
gainsboro: '#dcdcdc',
ghostwhite: '#f8f8ff',
goldenrod: '#daa520',
gold: '#ffd700',
gray: '#808080',
green: '#008000',
greenyellow: '#adff2f',
grey: '#808080',
honeydew: '#f0fff0',
hotpink: '#ff69b4',
indianred: '#cd5c5c',
indigo: '#4b0082',
ivory: '#fffff0',
khaki: '#f0e68c',
lavenderblush: '#fff0f5',
lavender: '#e6e6fa',
lawngreen: '#7cfc00',
lemonchiffon: '#fffacd',
lightblue: '#add8e6',
lightcoral: '#f08080',
lightcyan: '#e0ffff',
lightgoldenrodyellow: '#fafad2',
lightgray: '#d3d3d3',
lightgreen: '#90ee90',
lightgrey: '#d3d3d3',
lightpink: '#ffb6c1',
lightsalmon: '#ffa07a',
lightseagreen: '#20b2aa',
lightskyblue: '#87cefa',
lightslategray: '#778899',
lightslategrey: '#778899',
lightsteelblue: '#b0c4de',
lightyellow: '#ffffe0',
lime: '#00ff00',
limegreen: '#32cd32',
linen: '#faf0e6',
magenta: '#ff00ff',
maroon: '#800000',
mediumaquamarine: '#66cdaa',
mediumblue: '#0000cd',
mediumorchid: '#ba55d3',
mediumpurple: '#9370db',
mediumseagreen: '#3cb371',
mediumslateblue: '#7b68ee',
mediumspringgreen: '#00fa9a',
mediumturquoise: '#48d1cc',
mediumvioletred: '#c71585',
midnightblue: '#191970',
mintcream: '#f5fffa',
mistyrose: '#ffe4e1',
moccasin: '#ffe4b5',
navajowhite: '#ffdead',
navy: '#000080',
oldlace: '#fdf5e6',
olive: '#808000',
olivedrab: '#6b8e23',
orange: '#ffa500',
orangered: '#ff4500',
orchid: '#da70d6',
palegoldenrod: '#eee8aa',
palegreen: '#98fb98',
paleturquoise: '#afeeee',
palevioletred: '#db7093',
papayawhip: '#ffefd5',
peachpuff: '#ffdab9',
peru: '#cd853f',
pink: '#ffc0cb',
plum: '#dda0dd',
powderblue: '#b0e0e6',
purple: '#800080',
rebeccapurple: '#663399',
red: '#ff0000',
rosybrown: '#bc8f8f',
royalblue: '#4169e1',
saddlebrown: '#8b4513',
salmon: '#fa8072',
sandybrown: '#f4a460',
seagreen: '#2e8b57',
seashell: '#fff5ee',
sienna: '#a0522d',
silver: '#c0c0c0',
skyblue: '#87ceeb',
slateblue: '#6a5acd',
slategray: '#708090',
slategrey: '#708090',
snow: '#fffafa',
springgreen: '#00ff7f',
steelblue: '#4682b4',
tan: '#d2b48c',
teal: '#008080',
thistle: '#d8bfd8',
tomato: '#ff6347',
turquoise: '#40e0d0',
violet: '#ee82ee',
wheat: '#f5deb3',
white: '#ffffff',
whitesmoke: '#f5f5f5',
yellow: '#ffff00',
yellowgreen: '#9acd32'
};
/* eslint-disable @typescript-eslint/no-redundant-type-constituents */
/**
* Given a string or object, convert that input to RGB
*
* Possible string inputs:
* ```
* "red"
* "#f00" or "f00"
* "#ff0000" or "ff0000"
* "#ff000000" or "ff000000"
* "rgb 255 0 0" or "rgb (255, 0, 0)"
* "rgb 1.0 0 0" or "rgb (1, 0, 0)"
* "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
* "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
* "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
* "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
* "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
* ```
*/
function inputToRGB(color) {
var rgb = {
r: 0,
g: 0,
b: 0
};
var a = 1;
var s = null;
var v = null;
var l = null;
var ok = false;
var format = false;
if (typeof color === 'string') {
color = stringInputToObject(color);
}
if (typeof color === 'object') {
if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
rgb = rgbToRgb(color.r, color.g, color.b);
ok = true;
format = String(color.r).substr(-1) === '%' ? 'prgb' : 'rgb';
} else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
s = convertToPercentage(color.s);
v = convertToPercentage(color.v);
rgb = hsvToRgb(color.h, s, v);
ok = true;
format = 'hsv';
} else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
s = convertToPercentage(color.s);
l = convertToPercentage(color.l);
rgb = hslToRgb(color.h, s, l);
ok = true;
format = 'hsl';
}
if (Object.prototype.hasOwnProperty.call(color, 'a')) {
a = color.a;
}
}
a = boundAlpha(a);
return {
ok: ok,
format: color.format || format,
r: Math.min(255, Math.max(rgb.r, 0)),
g: Math.min(255, Math.max(rgb.g, 0)),
b: Math.min(255, Math.max(rgb.b, 0)),
a: a
};
}
// <http://www.w3.org/TR/css3-values/#integers>
var CSS_INTEGER = '[-\\+]?\\d+%?';
// <http://www.w3.org/TR/css3-values/#number-value>
var CSS_NUMBER = '[-\\+]?\\d*\\.\\d+%?';
// Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
var CSS_UNIT = "(?:".concat(CSS_NUMBER, ")|(?:").concat(CSS_INTEGER, ")");
// Actual matching.
// Parentheses and commas are optional, but not required.
// Whitespace can take the place of commas or opening paren
var PERMISSIVE_MATCH3 = "[\\s|\\(]+(".concat(CSS_UNIT, ")[,|\\s]+(").concat(CSS_UNIT, ")[,|\\s]+(").concat(CSS_UNIT, ")\\s*\\)?");
var PERMISSIVE_MATCH4 = "[\\s|\\(]+(".concat(CSS_UNIT, ")[,|\\s]+(").concat(CSS_UNIT, ")[,|\\s]+(").concat(CSS_UNIT, ")[,|\\s]+(").concat(CSS_UNIT, ")\\s*\\)?");
var matchers = {
CSS_UNIT: new RegExp(CSS_UNIT),
rgb: new RegExp('rgb' + PERMISSIVE_MATCH3),
rgba: new RegExp('rgba' + PERMISSIVE_MATCH4),
hsl: new RegExp('hsl' + PERMISSIVE_MATCH3),
hsla: new RegExp('hsla' + PERMISSIVE_MATCH4),
hsv: new RegExp('hsv' + PERMISSIVE_MATCH3),
hsva: new RegExp('hsva' + PERMISSIVE_MATCH4),
hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
};
/**
* Permissive string parsing. Take in a number of formats, and output an object
* based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
*/
function stringInputToObject(color) {
color = color.trim().toLowerCase();
if (color.length === 0) {
return false;
}
var named = false;
if (names[color]) {
color = names[color];
named = true;
} else if (color === 'transparent') {
return {
r: 0,
g: 0,
b: 0,
a: 0,
format: 'name'
};
}
// Try to match string input using regular expressions.
// Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
// Just return an object and let the conversion functions handle that.
// This way the result will be the same whether the tinycolor is initialized with string or object.
var match = matchers.rgb.exec(color);
if (match) {
return {
r: match[1],
g: match[2],
b: match[3]
};
}
match = matchers.rgba.exec(color);
if (match) {
return {
r: match[1],
g: match[2],
b: match[3],
a: match[4]
};
}
match = matchers.hsl.exec(color);
if (match) {
return {
h: match[1],
s: match[2],
l: match[3]
};
}
match = matchers.hsla.exec(color);
if (match) {
return {
h: match[1],
s: match[2],
l: match[3],
a: match[4]
};
}
match = matchers.hsv.exec(color);
if (match) {
return {
h: match[1],
s: match[2],
v: match[3]
};
}
match = matchers.hsva.exec(color);
if (match) {
return {
h: match[1],
s: match[2],
v: match[3],
a: match[4]
};
}
match = matchers.hex8.exec(color);
if (match) {
return {
r: parseIntFromHex(match[1]),
g: parseIntFromHex(match[2]),
b: parseIntFromHex(match[3]),
a: convertHexToDecimal(match[4]),
format: named ? 'name' : 'hex8'
};
}
match = matchers.hex6.exec(color);
if (match) {
return {
r: parseIntFromHex(match[1]),
g: parseIntFromHex(match[2]),
b: parseIntFromHex(match[3]),
format: named ? 'name' : 'hex'
};
}
match = matchers.hex4.exec(color);
if (match) {
return {
r: parseIntFromHex(match[1] + match[1]),
g: parseIntFromHex(match[2] + match[2]),
b: parseIntFromHex(match[3] + match[3]),
a: convertHexToDecimal(match[4] + match[4]),
format: named ? 'name' : 'hex8'
};
}
match = matchers.hex3.exec(color);
if (match) {
return {
r: parseIntFromHex(match[1] + match[1]),
g: parseIntFromHex(match[2] + match[2]),
b: parseIntFromHex(match[3] + match[3]),
format: named ? 'name' : 'hex'
};
}
return false;
}
/**
* Check to see if it looks like a CSS unit
* (see `matchers` above for definition).
*/
function isValidCSSUnit(color) {
return Boolean(matchers.CSS_UNIT.exec(String(color)));
}
var TinyColor = /** @class */function () {
function TinyColor(color, opts) {
if (color === void 0) {
color = '';
}
if (opts === void 0) {
opts = {};
}
var _a;
// If input is already a tinycolor, return itself
if (color instanceof TinyColor) {
// eslint-disable-next-line no-constructor-return
return color;
}
if (typeof color === 'number') {
color = numberInputToObject(color);
}
this.originalInput = color;
var rgb = inputToRGB(color);
this.originalInput = color;
this.r = rgb.r;
this.g = rgb.g;
this.b = rgb.b;
this.a = rgb.a;
this.roundA = Math.round(100 * this.a) / 100;
this.format = (_a = opts.format) !== null && _a !== void 0 ? _a : rgb.format;
this.gradientType = opts.gradientType;
// Don't let the range of [0,255] come back in [0,1].
// Potentially lose a little bit of precision here, but will fix issues where
// .5 gets interpreted as half of the total, instead of half of 1
// If it was supposed to be 128, this was already taken care of by `inputToRgb`
if (this.r < 1) {
this.r = Math.round(this.r);
}
if (this.g < 1) {
this.g = Math.round(this.g);
}
if (this.b < 1) {
this.b = Math.round(this.b);
}
this.isValid = rgb.ok;
}
TinyColor.prototype.isDark = function () {
return this.getBrightness() < 128;
};
TinyColor.prototype.isLight = function () {
return !this.isDark();
};
/**
* Returns the perceived brightness of the color, from 0-255.
*/
TinyColor.prototype.getBrightness = function () {
// http://www.w3.org/TR/AERT#color-contrast
var rgb = this.toRgb();
return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
};
/**
* Returns the perceived luminance of a color, from 0-1.
*/
TinyColor.prototype.getLuminance = function () {
// http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
var rgb = this.toRgb();
var R;
var G;
var B;
var RsRGB = rgb.r / 255;
var GsRGB = rgb.g / 255;
var BsRGB = rgb.b / 255;
if (RsRGB <= 0.03928) {
R = RsRGB / 12.92;
} else {
// eslint-disable-next-line prefer-exponentiation-operator
R = Math.pow((RsRGB + 0.055) / 1.055, 2.4);
}
if (GsRGB <= 0.03928) {
G = GsRGB / 12.92;
} else {
// eslint-disable-next-line prefer-exponentiation-operator
G = Math.pow((GsRGB + 0.055) / 1.055, 2.4);
}
if (BsRGB <= 0.03928) {
B = BsRGB / 12.92;
} else {
// eslint-disable-next-line prefer-exponentiation-operator
B = Math.pow((BsRGB + 0.055) / 1.055, 2.4);
}
return 0.2126 * R + 0.7152 * G + 0.0722 * B;
};
/**
* Returns the alpha value of a color, from 0-1.
*/
TinyColor.prototype.getAlpha = function () {
return this.a;
};
/**
* Sets the alpha value on the current color.
*
* @param alpha - The new alpha value. The accepted range is 0-1.
*/
TinyColor.prototype.setAlpha = function (alpha) {
this.a = boundAlpha(alpha);
this.roundA = Math.round(100 * this.a) / 100;
return this;
};
/**
* Returns whether the color is monochrome.
*/
TinyColor.prototype.isMonochrome = function () {
var s = this.toHsl().s;
return s === 0;
};
/**
* Returns the object as a HSVA object.
*/
TinyColor.prototype.toHsv = function () {
var hsv = rgbToHsv(this.r, this.g, this.b);
return {
h: hsv.h * 360,
s: hsv.s,
v: hsv.v,
a: this.a
};
};
/**
* Returns the hsva values interpolated into a string with the following format:
* "hsva(xxx, xxx, xxx, xx)".
*/
TinyColor.prototype.toHsvString = function () {
var hsv = rgbToHsv(this.r, this.g, this.b);
var h = Math.round(hsv.h * 360);
var s = Math.round(hsv.s * 100);
var v = Math.round(hsv.v * 100);
return this.a === 1 ? "hsv(".concat(h, ", ").concat(s, "%, ").concat(v, "%)") : "hsva(".concat(h, ", ").concat(s, "%, ").concat(v, "%, ").concat(this.roundA, ")");
};
/**
* Returns the object as a HSLA object.
*/
TinyColor.prototype.toHsl = function () {
var hsl = rgbToHsl(this.r, this.g, this.b);
return {
h: hsl.h * 360,
s: hsl.s,
l: hsl.l,
a: this.a
};
};
/**
* Returns the hsla values interpolated into a string with the following format:
* "hsla(xxx, xxx, xxx, xx)".
*/
TinyColor.prototype.toHslString = function () {
var hsl = rgbToHsl(this.r, this.g, this.b);
var h = Math.round(hsl.h * 360);
var s = Math.round(hsl.s * 100);
var l = Math.round(hsl.l * 100);
return this.a === 1 ? "hsl(".concat(h, ", ").concat(s, "%, ").concat(l, "%)") : "hsla(".concat(h, ", ").concat(s, "%, ").concat(l, "%, ").concat(this.roundA, ")");
};
/**
* Returns the hex value of the color.
* @param allow3Char will shorten hex value to 3 char if possible
*/
TinyColor.prototype.toHex = function (allow3Char) {
if (allow3Char === void 0) {
allow3Char = false;
}
return rgbToHex(this.r, this.g, this.b, allow3Char);
};
/**
* Returns the hex value of the color -with a # prefixed.
* @param allow3Char will shorten hex value to 3 char if possible
*/
TinyColor.prototype.toHexString = function (allow3Char) {
if (allow3Char === void 0) {
allow3Char = false;
}
return '#' + this.toHex(allow3Char);
};
/**
* Returns the hex 8 value of the color.
* @param allow4Char will shorten hex value to 4 char if possible
*/
TinyColor.prototype.toHex8 = function (allow4Char) {
if (allow4Char === void 0) {
allow4Char = false;
}
return rgbaToHex(this.r, this.g, this.b, this.a, allow4Char);
};
/**
* Returns the hex 8 value of the color -with a # prefixed.
* @param allow4Char will shorten hex value to 4 char if possible
*/
TinyColor.prototype.toHex8String = function (allow4Char) {
if (allow4Char === void 0) {
allow4Char = false;
}
return '#' + this.toHex8(allow4Char);
};
/**
* Returns the shorter hex value of the color depends on its alpha -with a # prefixed.
* @param allowShortChar will shorten hex value to 3 or 4 char if possible
*/
TinyColor.prototype.toHexShortString = function (allowShortChar) {
if (allowShortChar === void 0) {
allowShortChar = false;
}
return this.a === 1 ? this.toHexString(allowShortChar) : this.toHex8String(allowShortChar);
};
/**
* Returns the object as a RGBA object.
*/
TinyColor.prototype.toRgb = function () {
return {
r: Math.round(this.r),
g: Math.round(this.g),
b: Math.round(this.b),
a: this.a
};
};
/**
* Returns the RGBA values interpolated into a string with the following format:
* "RGBA(xxx, xxx, xxx, xx)".
*/
TinyColor.prototype.toRgbString = function () {
var r = Math.round(this.r);
var g = Math.round(this.g);
var b = Math.round(this.b);
return this.a === 1 ? "rgb(".concat(r, ", ").concat(g, ", ").concat(b, ")") : "rgba(".concat(r, ", ").concat(g, ", ").concat(b, ", ").concat(this.roundA, ")");
};
/**
* Returns the object as a RGBA object.
*/
TinyColor.prototype.toPercentageRgb = function () {
var fmt = function (x) {
return "".concat(Math.round(bound01(x, 255) * 100), "%");
};
return {
r: fmt(this.r),
g: fmt(this.g),
b: fmt(this.b),
a: this.a
};
};
/**
* Returns the RGBA relative values interpolated into a string
*/
TinyColor.prototype.toPercentageRgbString = function () {
var rnd = function (x) {
return Math.round(bound01(x, 255) * 100);
};
return this.a === 1 ? "rgb(".concat(rnd(this.r), "%, ").concat(rnd(this.g), "%, ").concat(rnd(this.b), "%)") : "rgba(".concat(rnd(this.r), "%, ").concat(rnd(this.g), "%, ").concat(rnd(this.b), "%, ").concat(this.roundA, ")");
};
/**
* The 'real' name of the color -if there is one.
*/
TinyColor.prototype.toName = function () {
if (this.a === 0) {
return 'transparent';
}
if (this.a < 1) {
return false;
}
var hex = '#' + rgbToHex(this.r, this.g, this.b, false);
for (var _i = 0, _a = Object.entries(names); _i < _a.length; _i++) {
var _b = _a[_i],
key = _b[0],
value = _b[1];
if (hex === value) {
return key;
}
}
return false;
};
TinyColor.prototype.toString = function (format) {
var formatSet = Boolean(format);
format = format !== null && format !== void 0 ? format : this.format;
var formattedString = false;
var hasAlpha = this.a < 1 && this.a >= 0;
var needsAlphaFormat = !formatSet && hasAlpha && (format.startsWith('hex') || format === 'name');
if (needsAlphaFormat) {
// Special case for "transparent", all other non-alpha formats
// will return rgba when there is transparency.
if (format === 'name' && this.a === 0) {
return this.toName();
}
return this.toRgbString();
}
if (format === 'rgb') {
formattedString = this.toRgbString();
}
if (format === 'prgb') {
formattedString = this.toPercentageRgbString();
}
if (format === 'hex' || format === 'hex6') {
formattedString = this.toHexString();
}
if (format === 'hex3') {
formattedString = this.toHexString(true);
}
if (format === 'hex4') {
formattedString = this.toHex8String(true);
}
if (format === 'hex8') {
formattedString = this.toHex8String();
}
if (format === 'name') {
formattedString = this.toName();
}
if (format === 'hsl') {
formattedString = this.toHslString();
}
if (format === 'hsv') {
formattedString = this.toHsvString();
}
return formattedString || this.toHexString();
};
TinyColor.prototype.toNumber = function () {
return (Math.round(this.r) << 16) + (Math.round(this.g) << 8) + Math.round(this.b);
};
TinyColor.prototype.clone = function () {
return new TinyColor(this.toString());
};
/**
* Lighten the color a given amount. Providing 100 will always return white.
* @param amount - valid between 1-100
*/
TinyColor.prototype.lighten = function (amount) {
if (amount === void 0) {
amount = 10;
}
var hsl = this.toHsl();
hsl.l += amount / 100;
hsl.l = clamp01(hsl.l);
return new TinyColor(hsl);
};
/**
* Brighten the color a given amount, from 0 to 100.
* @param amount - valid between 1-100
*/
TinyColor.prototype.brighten = function (amount) {
if (amount === void 0) {
amount = 10;
}
var rgb = this.toRgb();
rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100))));
rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100))));
rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100))));
return new TinyColor(rgb);
};
/**
* Darken the color a given amount, from 0 to 100.
* Providing 100 will always return black.
* @param amount - valid between 1-100
*/
TinyColor.prototype.darken = function (amount) {
if (amount === void 0) {
amount = 10;
}
var hsl = this.toHsl();
hsl.l -= amount / 100;
hsl.l = clamp01(hsl.l);
return new TinyColor(hsl);
};
/**
* Mix the color with pure white, from 0 to 100.
* Providing 0 will do nothing, providing 100 will always return white.
* @param amount - valid between 1-100
*/
TinyColor.prototype.tint = function (amount) {
if (amount === void 0) {
amount = 10;
}
return this.mix('white', amount);
};
/**
* Mix the color with pure black, from 0 to 100.
* Providing 0 will do nothing, providing 100 will always return black.
* @param amount - valid between 1-100
*/
TinyColor.prototype.shade = function (amount) {
if (amount === void 0) {
amount = 10;
}
return this.mix('black', amount);
};
/**
* Desaturate the color a given amount, from 0 to 100.
* Providing 100 will is the same as calling greyscale
* @param amount - valid between 1-100
*/
TinyColor.prototype.desaturate = function (amount) {
if (amount === void 0) {
amount = 10;
}
var hsl = this.toHsl();
hsl.s -= amount / 100;
hsl.s = clamp01(hsl.s);
return new TinyColor(hsl);
};
/**
* Saturate the color a given amount, from 0 to 100.
* @param amount - valid between 1-100
*/
TinyColor.prototype.saturate = function (amount) {
if (amount === void 0) {
amount = 10;
}
var hsl = this.toHsl();
hsl.s += amount / 100;
hsl.s = clamp01(hsl.s);
return new TinyColor(hsl);
};
/**
* Completely desaturates a color into greyscale.
* Same as calling `desaturate(100)`
*/
TinyColor.prototype.greyscale = function () {
return this.desaturate(100);
};
/**
* Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
* Values outside of this range will be wrapped into this range.
*/
TinyColor.prototype.spin = function (amount) {
var hsl = this.toHsl();
var hue = (hsl.h + amount) % 360;
hsl.h = hue < 0 ? 360 + hue : hue;
return new TinyColor(hsl);
};
/**
* Mix the current color a given amount with another color, from 0 to 100.
* 0 means no mixing (return current color).
*/
TinyColor.prototype.mix = function (color, amount) {
if (amount === void 0) {
amount = 50;
}
var rgb1 = this.toRgb();
var rgb2 = new TinyColor(color).toRgb();
var p = amount / 100;
var rgba = {
r: (rgb2.r - rgb1.r) * p + rgb1.r,
g: (rgb2.g - rgb1.g) * p + rgb1.g,
b: (rgb2.b - rgb1.b) * p + rgb1.b,
a: (rgb2.a - rgb1.a) * p + rgb1.a
};
return new TinyColor(rgba);
};
TinyColor.prototype.analogous = function (results, slices) {
if (results === void 0) {
results = 6;
}
if (slices === void 0) {
slices = 30;
}
var hsl = this.toHsl();
var part = 360 / slices;
var ret = [this];
for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360; --results;) {
hsl.h = (hsl.h + part) % 360;
ret.push(new TinyColor(hsl));
}
return ret;
};
/**
* taken from https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js
*/
TinyColor.prototype.complement = function () {
var hsl = this.toHsl();
hsl.h = (hsl.h + 180) % 360;
return new TinyColor(hsl);
};
TinyColor.prototype.monochromatic = function (results) {
if (results === void 0) {
results = 6;
}
var hsv = this.toHsv();
var h = hsv.h;
var s = hsv.s;
var v = hsv.v;
var res = [];
var modification = 1 / results;
while (results--) {
res.push(new TinyColor({
h: h,
s: s,
v: v
}));
v = (v + modification) % 1;
}
return res;
};
TinyColor.prototype.splitcomplement = function () {
var hsl = this.toHsl();
var h = hsl.h;
return [this, new TinyColor({
h: (h + 72) % 360,
s: hsl.s,
l: hsl.l
}), new TinyColor({
h: (h + 216) % 360,
s: hsl.s,
l: hsl.l
})];
};
/**
* Compute how the color would appear on a background
*/
TinyColor.prototype.onBackground = function (background) {
var fg = this.toRgb();
var bg = new TinyColor(background).toRgb();
var alpha = fg.a + bg.a * (1 - fg.a);
return new TinyColor({
r: (fg.r * fg.a + bg.r * bg.a * (1 - fg.a)) / alpha,
g: (fg.g * fg.a + bg.g * bg.a * (1 - fg.a)) / alpha,
b: (fg.b * fg.a + bg.b * bg.a * (1 - fg.a)) / alpha,
a: alpha
});
};
/**
* Alias for `polyad(3)`
*/
TinyColor.prototype.triad = function () {
return this.polyad(3);
};
/**
* Alias for `polyad(4)`
*/
TinyColor.prototype.tetrad = function () {
return this.polyad(4);
};
/**
* Get polyad colors, like (for 1, 2, 3, 4, 5, 6, 7, 8, etc...)
* monad, dyad, triad, tetrad, pentad, hexad, heptad, octad, etc...
*/
TinyColor.prototype.polyad = function (n) {
var hsl = this.toHsl();
var h = hsl.h;
var result = [this];
var increment = 360 / n;
for (var i = 1; i < n; i++) {
result.push(new TinyColor({
h: (h + i * increment) % 360,
s: hsl.s,
l: hsl.l
}));
}
return result;
};
/**
* compare color vs current color
*/
TinyColor.prototype.equals = function (color) {
return this.toRgbString() === new TinyColor(color).toRgbString();
};
return TinyColor;
}();
var hueStep$1 = 2; // 色相阶梯
var saturationStep$1 = 0.16; // 饱和度阶梯,浅色部分
var saturationStep2$1 = 0.05; // 饱和度阶梯,深色部分
var brightnessStep1$1 = 0.05; // 亮度阶梯,浅色部分
var brightnessStep2$1 = 0.15; // 亮度阶梯,深色部分
var lightColorCount$1 = 5; // 浅色数量,主色上
var darkColorCount$1 = 4; // 深色数量,主色下
// 暗色主题颜色映射关系表
var darkColorMap$1 = [{
index: 7,
opacity: 0.15
}, {
index: 6,
opacity: 0.25
}, {
index: 5,
opacity: 0.3
}, {
index: 5,
opacity: 0.45
}, {
index: 5,
opacity: 0.65
}, {
index: 5,
opacity: 0.85
}, {
index: 4,
opacity: 0.9
}, {
index: 3,
opacity: 0.95
}, {
index: 2,
opacity: 0.97
}, {
index: 1,
opacity: 0.98
}];
// Wrapper function ported from TinyColor.prototype.toHsv
// Keep it here because of `hsv.h * 360`
function toHsv$1(_ref) {
var r = _ref.r,
g = _ref.g,
b = _ref.b;
var hsv = rgbToHsv(r, g, b);
return {
h: hsv.h * 360,
s: hsv.s,
v: hsv.v
};
}
// Wrapper function ported from TinyColor.prototype.toHexString
// Keep it here because of the prefix `#`
function toHex$1(_ref2) {
var r = _ref2.r,
g = _ref2.g,
b = _ref2.b;
return "#".concat(rgbToHex(r, g, b, false));
}
// Wrapper function ported from TinyColor.prototype.mix, not treeshakable.
// Amount in range [0, 1]
// Assume color1 & color2 has no alpha, since the following src code did so.
function mix$2(rgb1, rgb2, amount) {
var p = amount / 100;
var rgb = {
r: (rgb2.r - rgb1.r) * p + rgb1.r,
g: (rgb2.g - rgb1.g) * p + rgb1.g,
b: (rgb2.b - rgb1.b) * p + rgb1.b
};
return rgb;
}
function getHue$1(hsv, i, light) {
var hue;
// 根据色相不同,色相转向不同
if (Math.round(hsv.h) >= 60 && Math.round(hsv.h) <= 240) {
hue = light ? Math.round(hsv.h) - hueStep$1 * i : Math.round(hsv.h) + hueStep$1 * i;
} else {
hue = light ? Math.round(hsv.h) + hueStep$1 * i : Math.round(hsv.h) - hueStep$1 * i;
}
if (hue < 0) {
hue += 360;
} else if (hue >= 360) {
hue -= 360;
}
return hue;
}
function getSaturation$1(hsv, i, light) {
// grey color don't change saturation
if (hsv.h === 0 && hsv.s === 0) {
return hsv.s;
}
var saturation;
if (light) {
saturation = hsv.s - saturationStep$1 * i;
} else if (i === darkColorCount$1) {
saturation = hsv.s + saturationStep$1;
} else {
saturation = hsv.s + saturationStep2$1 * i;
}
// 边界值修正
if (saturation > 1) {
saturation = 1;
}
// 第一格的 s 限制在 0.06-0.1 之间
if (light && i === lightColorCount$1 && saturation > 0.1) {
saturation = 0.1;
}
if (saturation < 0.06) {
saturation = 0.06;
}
return Number(saturation.toFixed(2));
}
function getValue$3(hsv, i, light) {
var value;
if (light) {
value = hsv.v + brightnessStep1$1 * i;
} else {
value = hsv.v - brightnessStep2$1 * i;
}
if (value > 1) {
value = 1;
}
return Number(value.toFixed(2));
}
function generate$3(color) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var patterns = [];
var pColor = inputToRGB(color);
for (var i = lightColorCount$1; i > 0; i -= 1) {
var hsv = toHsv$1(pColor);
var colorString = toHex$1(inputToRGB({
h: getHue$1(hsv, i, true),
s: getSaturation$1(hsv, i, true),
v: getValue$3(hsv, i, true)
}));
patterns.push(colorString);
}
patterns.push(toHex$1(pColor));
for (var _i = 1; _i <= darkColorCount$1; _i += 1) {
var _hsv = toHsv$1(pColor);
var _colorString = toHex$1(inputToRGB({
h: getHue$1(_hsv, _i),
s: getSaturation$1(_hsv, _i),
v: getValue$3(_hsv, _i)
}));
patterns.push(_colorString);
}
// dark theme patterns
if (opts.theme === 'dark') {
return darkColorMap$1.map(function (_ref3) {
var index = _ref3.index,
opacity = _ref3.opacity;
var darkColorString = toHex$1(mix$2(inputToRGB(opts.backgroundColor || '#141414'), inputToRGB(patterns[index]), opacity * 100));
return darkColorString;
});
}
return patterns;
}
var presetPrimaryColors$1 = {
red: '#F5222D',
volcano: '#FA541C',
orange: '#FA8C16',
gold: '#FAAD14',
yellow: '#FADB14',
lime: '#A0D911',
green: '#52C41A',
cyan: '#13C2C2',
blue: '#1677FF',
geekblue: '#2F54EB',
purple: '#722ED1',
magenta: '#EB2F96',
grey: '#666666'
};
var presetPalettes$1 = {};
var presetDarkPalettes$1 = {};
Object.keys(presetPrimaryColors$1).forEach(function (key) {
presetPalettes$1[key] = generate$3(presetPrimaryColors$1[key]);
presetPalettes$1[key].primary = presetPalettes$1[key][5];
// dark presetPalettes
presetDarkPalettes$1[key] = generate$3(presetPrimaryColors$1[key], {
theme: 'dark',
backgroundColor: '#141414'
});
presetDarkPalettes$1[key].primary = presetDarkPalettes$1[key][5];
});
var blue = presetPalettes$1.blue;
function ownKeys$1(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function (r) {
return Object.getOwnPropertyDescriptor(e, r).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function _objectSpread2$1(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) {
_defineProperty$1(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
function canUseDom() {
return !!(typeof window !== 'undefined' && window.document && window.document.createElement);
}
function contains(root, n) {
if (!root) {
return false;
}
// Use native if support
if (root.contains) {
return root.contains(n);
}
// `document.contains` not support with IE11
var node = n;
while (node) {
if (node === root) {
return true;
}
node = node.parentNode;
}
return false;
}
var APPEND_ORDER = 'data-rc-order';
var APPEND_PRIORITY = 'data-rc-priority';
var MARK_KEY = "rc-util-key";
var containerCache = new Map();
function getMark() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
mark = _ref.mark;
if (mark) {
return mark.startsWith('data-') ? mark : "data-".concat(mark);
}
return MARK_KEY;
}
function getContainer(option) {
if (option.attachTo) {
return option.attachTo;
}
var head = document.querySelector('head');
return head || document.body;
}
function getOrder(prepend) {
if (prepend === 'queue') {
return 'prependQueue';
}
return prepend ? 'prepend' : 'append';
}
/**
* Find style which inject by rc-util
*/
function findStyles(container) {
return Array.from((containerCache.get(container) || container).children).filter(function (node) {
return node.tagName === 'STYLE';
});
}
function injectCSS(css) {
var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!canUseDom()) {
return null;
}
var csp = option.csp,
prepend = option.prepend,
_option$priority = option.priority,
priority = _option$priority === void 0 ? 0 : _option$priority;
var mergedOrder = getOrder(prepend);
var isPrependQueue = mergedOrder === 'prependQueue';
var styleNode = document.createElement('style');
styleNode.setAttribute(APPEND_ORDER, mergedOrder);
if (isPrependQueue && priority) {
styleNode.setAttribute(APPEND_PRIORITY, "".concat(priority));
}
if (csp !== null && csp !== void 0 && csp.nonce) {
styleNode.nonce = csp === null || csp === void 0 ? void 0 : csp.nonce;
}
styleNode.innerHTML = css;
var container = getContainer(option);
var firstChild = container.firstChild;
if (prepend) {
// If is queue `prepend`, it will prepend first style and then append rest style
if (isPrependQueue) {
var existStyle = findStyles(container).filter(function (node) {
// Ignore style which not injected by rc-util with prepend
if (!['prepend', 'prependQueue'].includes(node.getAttribute(APPEND_ORDER))) {
return false;
}
// Ignore style which priority less then new style
var nodePriority = Number(node.getAttribute(APPEND_PRIORITY) || 0);
return priority >= nodePriority;
});
if (existStyle.length) {
container.insertBefore(styleNode, existStyle[existStyle.length - 1].nextSibling);
return styleNode;
}
}
// Use `insertBefore` as `prepend`
container.insertBefore(styleNode, firstChild);
} else {
container.appendChild(styleNode);
}
return styleNode;
}
function findExistNode(key) {
var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var container = getContainer(option);
return findStyles(container).find(function (node) {
return node.getAttribute(getMark(option)) === key;
});
}
function removeCSS(key) {
var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var existNode = findExistNode(key, option);
if (existNode) {
var container = getContainer(option);
container.removeChild(existNode);
}
}
/**
* qiankun will inject `appendChild` to insert into other
*/
function syncRealContainer(container, option) {
var cachedRealContainer = containerCache.get(container);
// Find real container when not cached or cached container removed
if (!cachedRealContainer || !contains(document, cachedRealContainer)) {
var placeholderStyle = injectCSS('', option);
var parentNode = placeholderStyle.parentNode;
containerCache.set(container, parentNode);
container.removeChild(placeholderStyle);
}
}
function updateCSS(css, key) {
var option = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var container = getContainer(option);
// Sync real parent
syncRealContainer(container, option);
var existNode = findExistNode(key, option);
if (existNode) {
var _option$csp, _option$csp2;
if ((_option$csp = option.csp) !== null && _option$csp !== void 0 && _option$csp.nonce && existNode.nonce !== ((_option$csp2 = option.csp) === null || _option$csp2 === void 0 ? void 0 : _option$csp2.nonce)) {
var _option$csp3;
existNode.nonce = (_option$csp3 = option.csp) === null || _option$csp3 === void 0 ? void 0 : _option$csp3.nonce;
}
if (existNode.innerHTML !== css) {
existNode.innerHTML = css;
}
return existNode;
}
var newNode = injectCSS(css, option);
newNode.setAttribute(getMark(option), key);
return newNode;
}
function getRoot(ele) {
var _ele$getRootNode;
return ele === null || ele === void 0 || (_ele$getRootNode = ele.getRootNode) === null || _ele$getRootNode === void 0 ? void 0 : _ele$getRootNode.call(ele);
}
/**
* Check if is in shadowRoot
*/
function inShadow(ele) {
return getRoot(ele) instanceof ShadowRoot;
}
/**
* Return shadowRoot if possible
*/
function getShadowRoot(ele) {
return inShadow(ele) ? getRoot(ele) : null;
}
/* eslint-disable no-console */
var warned = {};
var preWarningFns = [];
/**
* Pre warning enable you to parse content before console.error.
* Modify to null will prevent warning.
*/
var preMessage = function preMessage(fn) {
preWarningFns.push(fn);
};
function warning$5(valid, message) {
// Support uglify
if (process.env.NODE_ENV !== 'production' && !valid && console !== undefined) {
var finalMessage = preWarningFns.reduce(function (msg, preMessageFn) {
return preMessageFn(msg !== null && msg !== void 0 ? msg : '', 'warning');
}, message);
if (finalMessage) {
console.error("Warning: ".concat(finalMessage));
}
}
}
function note(valid, message) {
// Support uglify
if (process.env.NODE_ENV !== 'production' && !valid && console !== undefined) {
var finalMessage = preWarningFns.reduce(function (msg, preMessageFn) {
return preMessageFn(msg !== null && msg !== void 0 ? msg : '', 'note');
}, message);
if (finalMessage) {
console.warn("Note: ".concat(finalMessage));
}
}
}
function resetWarned() {
warned = {};
}
function call(method, valid, message) {
if (!valid && !warned[message]) {
method(false, message);
warned[message] = true;
}
}
function warningOnce(valid, message) {
call(warning$5, valid, message);
}
function noteOnce(valid, message) {
call(note, valid, message);
}
warningOnce.preMessage = preMessage;
warningOnce.resetWarned = resetWarned;
warningOnce.noteOnce = noteOnce;
/* eslint-enable */
function camelCase$2(input) {
return input.replace(/-(.)/g, function (match, g) {
return g.toUpperCase();
});
}
function warning$4(valid, message) {
warningOnce(valid, "[@ant-design/icons] ".concat(message));
}
function isIconDefinition$1(target) {
return _typeof$1(target) === 'object' && typeof target.name === 'string' && typeof target.theme === 'string' && (_typeof$1(target.icon) === 'object' || typeof target.icon === 'function');
}
function normalizeAttrs$1() {
var attrs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return Object.keys(attrs).reduce(function (acc, key) {
var val = attrs[key];
switch (key) {
case 'class':
acc.className = val;
delete acc.class;
break;
default:
delete acc[key];
acc[camelCase$2(key)] = val;
}
return acc;
}, {});
}
function generate$2(node, key, rootProps) {
if (!rootProps) {
return /*#__PURE__*/React__default.createElement(node.tag, _objectSpread2$1({
key: key
}, normalizeAttrs$1(node.attrs)), (node.children || []).map(function (child, index) {
return generate$2(child, "".concat(key, "-").concat(node.tag, "-").concat(index));
}));
}
return /*#__PURE__*/React__default.createElement(node.tag, _objectSpread2$1(_objectSpread2$1({
key: key
}, normalizeAttrs$1(node.attrs)), rootProps), (node.children || []).map(function (child, index) {
return generate$2(child, "".concat(key, "-").concat(node.tag, "-").concat(index));
}));
}
function getSecondaryColor$1(primaryColor) {
// choose the second color
return generate$3(primaryColor)[0];
}
function normalizeTwoToneColors$1(twoToneColor) {
if (!twoToneColor) {
return [];
}
return Array.isArray(twoToneColor) ? twoToneColor : [twoToneColor];
}
var iconStyles$1 = "\n.anticon {\n display: inline-block;\n color: inherit;\n font-style: normal;\n line-height: 0;\n text-align: center;\n text-transform: none;\n vertical-align: -0.125em;\n text-rendering: optimizeLegibility;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n.anticon > * {\n line-height: 1;\n}\n\n.anticon svg {\n display: inline-block;\n}\n\n.anticon::before {\n display: none;\n}\n\n.anticon .anticon-icon {\n display: block;\n}\n\n.anticon[tabindex] {\n cursor: pointer;\n}\n\n.anticon-spin::before,\n.anticon-spin {\n display: inline-block;\n -webkit-animation: loadingCircle 1s infinite linear;\n animation: loadingCircle 1s infinite linear;\n}\n\n@-webkit-keyframes loadingCircle {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n@keyframes loadingCircle {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n";
var useInsertStyles$1 = function useInsertStyles(eleRef) {
var _useContext = useContext(Context$3),
csp = _useContext.csp,
prefixCls = _useContext.prefixCls;
var mergedStyleStr = iconStyles$1;
if (prefixCls) {
mergedStyleStr = mergedStyleStr.replace(/anticon/g, prefixCls);
}
useEffect(function () {
var ele = eleRef.current;
var shadowRoot = getShadowRoot(ele);
updateCSS(mergedStyleStr, '@ant-design-icons', {
prepend: true,
csp: csp,
attachTo: shadowRoot
});
}, []);
};
var _excluded$k = ["icon", "className", "onClick", "style", "primaryColor", "secondaryColor"];
var twoToneColorPalette$1 = {
primaryColor: '#333',
secondaryColor: '#E6E6E6',
calculated: false
};
function setTwoToneColors$1(_ref) {
var primaryColor = _ref.primaryColor,
secondaryColor = _ref.secondaryColor;
twoToneColorPalette$1.primaryColor = primaryColor;
twoToneColorPalette$1.secondaryColor = secondaryColor || getSecondaryColor$1(primaryColor);
twoToneColorPalette$1.calculated = !!secondaryColor;
}
function getTwoToneColors$1() {
return _objectSpread2$1({}, twoToneColorPalette$1);
}
var IconBase$1 = function IconBase(props) {
var icon = props.icon,
className = props.className,
onClick = props.onClick,
style = props.style,
primaryColor = props.primaryColor,
secondaryColor = props.secondaryColor,
restProps = _objectWithoutProperties(props, _excluded$k);
var svgRef = React.useRef();
var colors = twoToneColorPalette$1;
if (primaryColor) {
colors = {
primaryColor: primaryColor,
secondaryColor: secondaryColor || getSecondaryColor$1(primaryColor)
};
}
useInsertStyles$1(svgRef);
warning$4(isIconDefinition$1(icon), "icon should be icon definiton, but got ".concat(icon));
if (!isIconDefinition$1(icon)) {
return null;
}
var target = icon;
if (target && typeof target.icon === 'function') {
target = _objectSpread2$1(_objectSpread2$1({}, target), {}, {
icon: target.icon(colors.primaryColor, colors.secondaryColor)
});
}
return generate$2(target.icon, "svg-".concat(target.name), _objectSpread2$1(_objectSpread2$1({
className: className,
onClick: onClick,
style: style,
'data-icon': target.name,
width: '1em',
height: '1em',
fill: 'currentColor',
'aria-hidden': 'true'
}, restProps), {}, {
ref: svgRef
}));
};
IconBase$1.displayName = 'IconReact';
IconBase$1.getTwoToneColors = getTwoToneColors$1;
IconBase$1.setTwoToneColors = setTwoToneColors$1;
var ReactIcon$1 = IconBase$1;
function setTwoToneColor$1(twoToneColor) {
var _normalizeTwoToneColo = normalizeTwoToneColors$1(twoToneColor),
_normalizeTwoToneColo2 = _slicedToArray(_normalizeTwoToneColo, 2),
primaryColor = _normalizeTwoToneColo2[0],
secondaryColor = _normalizeTwoToneColo2[1];
return ReactIcon$1.setTwoToneColors({
primaryColor: primaryColor,
secondaryColor: secondaryColor
});
}
function getTwoToneColor$1() {
var colors = ReactIcon$1.getTwoToneColors();
if (!colors.calculated) {
return colors.primaryColor;
}
return [colors.primaryColor, colors.secondaryColor];
}
var _excluded$j = ["className", "icon", "spin", "rotate", "tabIndex", "onClick", "twoToneColor"];
// Initial setting
// should move it to antd main repo?
setTwoToneColor$1(blue.primary);
// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/34757#issuecomment-488848720
var Icon$2 = /*#__PURE__*/React.forwardRef(function (props, ref) {
var _classNames;
var className = props.className,
icon = props.icon,
spin = props.spin,
rotate = props.rotate,
tabIndex = props.tabIndex,
onClick = props.onClick,
twoToneColor = props.twoToneColor,
restProps = _objectWithoutProperties(props, _excluded$j);
var _React$useContext = React.useContext(Context$3),
_React$useContext$pre = _React$useContext.prefixCls,
prefixCls = _React$useContext$pre === void 0 ? 'anticon' : _React$useContext$pre,
rootClassName = _React$useContext.rootClassName;
var classString = classNames(rootClassName, prefixCls, (_classNames = {}, _defineProperty$1(_classNames, "".concat(prefixCls, "-").concat(icon.name), !!icon.name), _defineProperty$1(_classNames, "".concat(prefixCls, "-spin"), !!spin || icon.name === 'loading'), _classNames), className);
var iconTabIndex = tabIndex;
if (iconTabIndex === undefined && onClick) {
iconTabIndex = -1;
}
var svgStyle = rotate ? {
msTransform: "rotate(".concat(rotate, "deg)"),
transform: "rotate(".concat(rotate, "deg)")
} : undefined;
var _normalizeTwoToneColo = normalizeTwoToneColors$1(twoToneColor),
_normalizeTwoToneColo2 = _slicedToArray(_normalizeTwoToneColo, 2),
primaryColor = _normalizeTwoToneColo2[0],
secondaryColor = _normalizeTwoToneColo2[1];
return /*#__PURE__*/React.createElement("span", _extends$1({
role: "img",
"aria-label": icon.name
}, restProps, {
ref: ref,
tabIndex: iconTabIndex,
onClick: onClick,
className: classString
}), /*#__PURE__*/React.createElement(ReactIcon$1, {
icon: icon,
primaryColor: primaryColor,
secondaryColor: secondaryColor,
style: svgStyle
}));
});
Icon$2.displayName = 'AntdIcon';
Icon$2.getTwoToneColor = getTwoToneColor$1;
Icon$2.setTwoToneColor = setTwoToneColor$1;
var AntdIcon$1 = Icon$2;
// This icon file is generated automatically.
var BarsOutlined$2 = {
"icon": {
"tag": "svg",
"attrs": {
"viewBox": "0 0 1024 1024",
"focusable": "false"
},
"children": [{
"tag": "path",
"attrs": {
"d": "M912 192H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 284H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 284H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM104 228a56 56 0 10112 0 56 56 0 10-112 0zm0 284a56 56 0 10112 0 56 56 0 10-112 0zm0 284a56 56 0 10112 0 56 56 0 10-112 0z"
}
}]
},
"name": "bars",
"theme": "outlined"
};
var BarsOutlinedSvg = BarsOutlined$2;
// This icon file is generated automatically.
var BellOutlined$2 = {
"icon": {
"tag": "svg",
"attrs": {
"viewBox": "64 64 896 896",
"focusable": "false"
},
"children": [{
"tag": "path",
"attrs": {
"d": "M816 768h-24V428c0-141.1-104.3-257.7-240-277.1V112c0-22.1-17.9-40-40-40s-40 17.9-40 40v38.9c-135.7 19.4-240 136-240 277.1v340h-24c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h216c0 61.8 50.2 112 112 112s112-50.2 112-112h216c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM512 888c-26.5 0-48-21.5-48-48h96c0 26.5-21.5 48-48 48zM304 768V428c0-55.6 21.6-107.8 60.9-147.1S456.4 220 512 220c55.6 0 107.8 21.6 147.1 60.9S720 372.4 720 428v340H304z"
}
}]
},
"name": "bell",
"theme": "outlined"
};
var BellOutlinedSvg = BellOutlined$2;
var BellOutlined = function BellOutlined(props, ref) {
return /*#__PURE__*/React.createElement(AntdIcon$1, _extends$1({}, props, {
ref: ref,
icon: BellOutlinedSvg
}));
};
if (process.env.NODE_ENV !== 'production') {
BellOutlined.displayName = 'BellOutlined';
}
var BellOutlined$1 = /*#__PURE__*/React.forwardRef(BellOutlined);
// This icon file is generated automatically.
var DownOutlined$2 = {
"icon": {
"tag": "svg",
"attrs": {
"viewBox": "64 64 896 896",
"focusable": "false"
},
"children": [{
"tag": "path",
"attrs": {
"d": "M884 256h-75c-5.1 0-9.9 2.5-12.9 6.6L512 654.2 227.9 262.6c-3-4.1-7.8-6.6-12.9-6.6h-75c-6.5 0-10.3 7.4-6.5 12.7l352.6 486.1c12.8 17.6 39 17.6 51.7 0l352.6-486.1c3.9-5.3.1-12.7-6.4-12.7z"
}
}]
},
"name": "down",
"theme": "outlined"
};
var DownOutlinedSvg = DownOutlined$2;
var DownOutlined = function DownOutlined(props, ref) {
return /*#__PURE__*/React.createElement(AntdIcon$1, _extends$1({}, props, {
ref: ref,
icon: DownOutlinedSvg
}));
};
if (process.env.NODE_ENV !== 'production') {
DownOutlined.displayName = 'DownOutlined';
}
var DownOutlined$1 = /*#__PURE__*/React.forwardRef(DownOutlined);
// This icon file is generated automatically.
var EllipsisOutlined$2 = {
"icon": {
"tag": "svg",
"attrs": {
"viewBox": "64 64 896 896",
"focusable": "false"
},
"children": [{
"tag": "path",
"attrs": {
"d": "M176 511a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0z"
}
}]
},
"name": "ellipsis",
"theme": "outlined"
};
var EllipsisOutlinedSvg = EllipsisOutlined$2;
// This icon file is generated automatically.
var HomeOutlined$2 = {
"icon": {
"tag": "svg",
"attrs": {
"viewBox": "64 64 896 896",
"focusable": "false"
},
"children": [{
"tag": "path",
"attrs": {
"d": "M946.5 505L560.1 118.8l-25.9-25.9a31.5 31.5 0 00-44.4 0L77.5 505a63.9 63.9 0 00-18.8 46c.4 35.2 29.7 63.3 64.9 63.3h42.5V940h691.8V614.3h43.4c17.1 0 33.2-6.7 45.3-18.8a63.6 63.6 0 0018.7-45.3c0-17-6.7-33.1-18.8-45.2zM568 868H456V664h112v204zm217.9-325.7V868H632V640c0-22.1-17.9-40-40-40H432c-22.1 0-40 17.9-40 40v228H238.1V542.3h-96l370-369.7 23.1 23.1L882 542.3h-96.1z"
}
}]
},
"name": "home",
"theme": "outlined"
};
var HomeOutlinedSvg = HomeOutlined$2;
var HomeOutlined = function HomeOutlined(props, ref) {
return /*#__PURE__*/React.createElement(AntdIcon$1, _extends$1({}, props, {
ref: ref,
icon: HomeOutlinedSvg
}));
};
if (process.env.NODE_ENV !== 'production') {
HomeOutlined.displayName = 'HomeOutlined';
}
var HomeOutlined$1 = /*#__PURE__*/React.forwardRef(HomeOutlined);
// This icon file is generated automatically.
var LeftOutlined$2 = {
"icon": {
"tag": "svg",
"attrs": {
"viewBox": "64 64 896 896",
"focusable": "false"
},
"children": [{
"tag": "path",
"attrs": {
"d": "M724 218.3V141c0-6.7-7.7-10.4-12.9-6.3L260.3 486.8a31.86 31.86 0 000 50.3l450.8 352.1c5.3 4.1 12.9.4 12.9-6.3v-77.3c0-4.9-2.3-9.6-6.1-12.6l-360-281 360-281.1c3.8-3 6.1-7.7 6.1-12.6z"
}
}]
},
"name": "left",
"theme": "outlined"
};
var LeftOutlinedSvg = LeftOutlined$2;
// This icon file is generated automatically.
var LoadingOutlined$4 = {
"icon": {
"tag": "svg",
"attrs": {
"viewBox": "0 0 1024 1024",
"focusable": "false"
},
"children": [{
"tag": "path",
"attrs": {
"d": "M988 548c-19.9 0-36-16.1-36-36 0-59.4-11.6-117-34.6-171.3a440.45 440.45 0 00-94.3-139.9 437.71 437.71 0 00-139.9-94.3C629 83.6 571.4 72 512 72c-19.9 0-36-16.1-36-36s16.1-36 36-36c69.1 0 136.2 13.5 199.3 40.3C772.3 66 827 103 874 150c47 47 83.9 101.8 109.7 162.7 26.7 63.1 40.2 130.2 40.2 199.3.1 19.9-16 36-35.9 36z"
}
}]
},
"name": "loading",
"theme": "outlined"
};
var LoadingOutlinedSvg = LoadingOutlined$4;
var LoadingOutlined$2 = function LoadingOutlined(props, ref) {
return /*#__PURE__*/React.createElement(AntdIcon$1, _extends$1({}, props, {
ref: ref,
icon: LoadingOutlinedSvg
}));
};
if (process.env.NODE_ENV !== 'production') {
LoadingOutlined$2.displayName = 'LoadingOutlined';
}
var LoadingOutlined$3 = /*#__PURE__*/React.forwardRef(LoadingOutlined$2);
// This icon file is generated automatically.
var RightOutlined$2 = {
"icon": {
"tag": "svg",
"attrs": {
"viewBox": "64 64 896 896",
"focusable": "false"
},
"children": [{
"tag": "path",
"attrs": {
"d": "M765.7 486.8L314.9 134.7A7.97 7.97 0 00302 141v77.3c0 4.9 2.3 9.6 6.1 12.6l360 281.1-360 281.1c-3.9 3-6.1 7.7-6.1 12.6V883c0 6.7 7.7 10.4 12.9 6.3l450.8-352.1a31.96 31.96 0 000-50.4z"
}
}]
},
"name": "right",
"theme": "outlined"
};
var RightOutlinedSvg = RightOutlined$2;
var reactIs = {exports: {}};
var reactIs_production_min = {};
/**
* @license React
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var hasRequiredReactIs_production_min;
function requireReactIs_production_min () {
if (hasRequiredReactIs_production_min) return reactIs_production_min;
hasRequiredReactIs_production_min = 1;
var b = Symbol.for("react.element"),
c = Symbol.for("react.portal"),
d = Symbol.for("react.fragment"),
e = Symbol.for("react.strict_mode"),
f = Symbol.for("react.profiler"),
g = Symbol.for("react.provider"),
h = Symbol.for("react.context"),
k = Symbol.for("react.server_context"),
l = Symbol.for("react.forward_ref"),
m = Symbol.for("react.suspense"),
n = Symbol.for("react.suspense_list"),
p = Symbol.for("react.memo"),
q = Symbol.for("react.lazy"),
t = Symbol.for("react.offscreen"),
u;
u = Symbol.for("react.module.reference");
function v(a) {
if ("object" === typeof a && null !== a) {
var r = a.$$typeof;
switch (r) {
case b:
switch (a = a.type, a) {
case d:
case f:
case e:
case m:
case n:
return a;
default:
switch (a = a && a.$$typeof, a) {
case k:
case h:
case l:
case q:
case p:
case g:
return a;
default:
return r;
}
}
case c:
return r;
}
}
}
reactIs_production_min.ContextConsumer = h;
reactIs_production_min.ContextProvider = g;
reactIs_production_min.Element = b;
reactIs_production_min.ForwardRef = l;
reactIs_production_min.Fragment = d;
reactIs_production_min.Lazy = q;
reactIs_production_min.Memo = p;
reactIs_production_min.Portal = c;
reactIs_production_min.Profiler = f;
reactIs_production_min.StrictMode = e;
reactIs_production_min.Suspense = m;
reactIs_production_min.SuspenseList = n;
reactIs_production_min.isAsyncMode = function () {
return !1;
};
reactIs_production_min.isConcurrentMode = function () {
return !1;
};
reactIs_production_min.isContextConsumer = function (a) {
return v(a) === h;
};
reactIs_production_min.isContextProvider = function (a) {
return v(a) === g;
};
reactIs_production_min.isElement = function (a) {
return "object" === typeof a && null !== a && a.$$typeof === b;
};
reactIs_production_min.isForwardRef = function (a) {
return v(a) === l;
};
reactIs_production_min.isFragment = function (a) {
return v(a) === d;
};
reactIs_production_min.isLazy = function (a) {
return v(a) === q;
};
reactIs_production_min.isMemo = function (a) {
return v(a) === p;
};
reactIs_production_min.isPortal = function (a) {
return v(a) === c;
};
reactIs_production_min.isProfiler = function (a) {
return v(a) === f;
};
reactIs_production_min.isStrictMode = function (a) {
return v(a) === e;
};
reactIs_production_min.isSuspense = function (a) {
return v(a) === m;
};
reactIs_production_min.isSuspenseList = function (a) {
return v(a) === n;
};
reactIs_production_min.isValidElementType = function (a) {
return "string" === typeof a || "function" === typeof a || a === d || a === f || a === e || a === m || a === n || a === t || "object" === typeof a && null !== a && (a.$$typeof === q || a.$$typeof === p || a.$$typeof === g || a.$$typeof === h || a.$$typeof === l || a.$$typeof === u || void 0 !== a.getModuleId) ? !0 : !1;
};
reactIs_production_min.typeOf = v;
return reactIs_production_min;
}
var reactIs_development = {};
/**
* @license React
* react-is.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var hasRequiredReactIs_development;
function requireReactIs_development () {
if (hasRequiredReactIs_development) return reactIs_development;
hasRequiredReactIs_development = 1;
if (process.env.NODE_ENV !== "production") {
(function () {
// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types.
var REACT_ELEMENT_TYPE = Symbol.for('react.element');
var REACT_PORTAL_TYPE = Symbol.for('react.portal');
var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
var REACT_CONTEXT_TYPE = Symbol.for('react.context');
var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context');
var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
var REACT_MEMO_TYPE = Symbol.for('react.memo');
var REACT_LAZY_TYPE = Symbol.for('react.lazy');
var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
// -----------------------------------------------------------------------------
var enableScopeAPI = false; // Experimental Create Event Handle API.
var enableCacheElement = false;
var enableTransitionTracing = false; // No known bugs, but needs performance testing
var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
// stuff. Intended to enable React core members to more easily debug scheduling
// issues in DEV builds.
var enableDebugTracing = false; // Track which Fiber(s) schedule render work.
var REACT_MODULE_REFERENCE;
{
REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
}
function isValidElementType(type) {
if (typeof type === 'string' || typeof type === 'function') {
return true;
} // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) {
return true;
}
if (typeof type === 'object' && type !== null) {
if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE ||
// This needs to include all possible module reference object
// types supported by any Flight configuration anywhere since
// we don't know which Flight build this will end up being used
// with.
type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
return true;
}
}
return false;
}
function typeOf(object) {
if (typeof object === 'object' && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
case REACT_SUSPENSE_LIST_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_SERVER_CONTEXT_TYPE:
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return undefined;
}
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var SuspenseList = REACT_SUSPENSE_LIST_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false;
var hasWarnedAboutDeprecatedIsConcurrentMode = false; // AsyncMode should be deprecated
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint
console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 18+.');
}
}
return false;
}
function isConcurrentMode(object) {
{
if (!hasWarnedAboutDeprecatedIsConcurrentMode) {
hasWarnedAboutDeprecatedIsConcurrentMode = true; // Using console['warn'] to evade Babel and ESLint
console['warn']('The ReactIs.isConcurrentMode() alias has been deprecated, ' + 'and will be removed in React 18+.');
}
}
return false;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
function isSuspenseList(object) {
return typeOf(object) === REACT_SUSPENSE_LIST_TYPE;
}
reactIs_development.ContextConsumer = ContextConsumer;
reactIs_development.ContextProvider = ContextProvider;
reactIs_development.Element = Element;
reactIs_development.ForwardRef = ForwardRef;
reactIs_development.Fragment = Fragment;
reactIs_development.Lazy = Lazy;
reactIs_development.Memo = Memo;
reactIs_development.Portal = Portal;
reactIs_development.Profiler = Profiler;
reactIs_development.StrictMode = StrictMode;
reactIs_development.Suspense = Suspense;
reactIs_development.SuspenseList = SuspenseList;
reactIs_development.isAsyncMode = isAsyncMode;
reactIs_development.isConcurrentMode = isConcurrentMode;
reactIs_development.isContextConsumer = isContextConsumer;
reactIs_development.isContextProvider = isContextProvider;
reactIs_development.isElement = isElement;
reactIs_development.isForwardRef = isForwardRef;
reactIs_development.isFragment = isFragment;
reactIs_development.isLazy = isLazy;
reactIs_development.isMemo = isMemo;
reactIs_development.isPortal = isPortal;
reactIs_development.isProfiler = isProfiler;
reactIs_development.isStrictMode = isStrictMode;
reactIs_development.isSuspense = isSuspense;
reactIs_development.isSuspenseList = isSuspenseList;
reactIs_development.isValidElementType = isValidElementType;
reactIs_development.typeOf = typeOf;
})();
}
return reactIs_development;
}
if (process.env.NODE_ENV === 'production') {
reactIs.exports = requireReactIs_production_min();
} else {
reactIs.exports = requireReactIs_development();
}
var reactIsExports = reactIs.exports;
function useMemo(getValue, condition, shouldUpdate) {
var cacheRef = React.useRef({});
if (!('value' in cacheRef.current) || shouldUpdate(cacheRef.current.condition, condition)) {
cacheRef.current.value = getValue();
cacheRef.current.condition = condition;
}
return cacheRef.current.value;
}
function fillRef(ref, node) {
if (typeof ref === 'function') {
ref(node);
} else if (_typeof$1(ref) === 'object' && ref && 'current' in ref) {
ref.current = node;
}
}
/**
* Merge refs into one ref function to support ref passing.
*/
function composeRef() {
for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) {
refs[_key] = arguments[_key];
}
var refList = refs.filter(function (ref) {
return ref;
});
if (refList.length <= 1) {
return refList[0];
}
return function (node) {
refs.forEach(function (ref) {
fillRef(ref, node);
});
};
}
function useComposeRef() {
for (var _len2 = arguments.length, refs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
refs[_key2] = arguments[_key2];
}
return useMemo(function () {
return composeRef.apply(void 0, refs);
}, refs, function (prev, next) {
return prev.length !== next.length || prev.every(function (ref, i) {
return ref !== next[i];
});
});
}
function supportRef(nodeOrComponent) {
var _type$prototype, _nodeOrComponent$prot;
var type = reactIsExports.isMemo(nodeOrComponent) ? nodeOrComponent.type.type : nodeOrComponent.type;
// Function component node
if (typeof type === 'function' && !((_type$prototype = type.prototype) !== null && _type$prototype !== void 0 && _type$prototype.render)) {
return false;
}
// Class component
if (typeof nodeOrComponent === 'function' && !((_nodeOrComponent$prot = nodeOrComponent.prototype) !== null && _nodeOrComponent$prot !== void 0 && _nodeOrComponent$prot.render)) {
return false;
}
return true;
}
/* eslint-enable */
/**
* ## Maïa Button
*
* Different button styles can be generated by setting Button properties.
*
* The recommended order is:
* <b><u>color</u></b> ->
* <b><u>small</u></b> ->
* <b><u>loading</u></b> ->
* <b><u>disabled</u></b>.
*
* ### Usage example
*
* ```jsx
* <Button
* color="white"
* small
* loading
* disabled
* block
* htmlType="reset"
* icon={<Storybook />}
* iconPosition="right"
* onClick={() => console.log('Made with 💙 by Maïa Team!)}
* >
* {Children}
* </Button>
* ```
*/
var Button$2 = function (_a) {
var _b = _a.style, style = _b === void 0 ? 'primary' : _b, _c = _a.small, small = _c === void 0 ? false : _c, _d = _a.loading, loading = _d === void 0 ? false : _d, _e = _a.disabled, disabled = _e === void 0 ? false : _e, _f = _a.block, block = _f === void 0 ? false : _f, _g = _a.htmlType, htmlType = _g === void 0 ? 'button' : _g, icon = _a.icon, _h = _a.iconPosition, iconPosition = _h === void 0 ? 'left' : _h, children = _a.children, onClick = _a.onClick, props = __rest$h(_a, ["style", "small", "loading", "disabled", "block", "htmlType", "icon", "iconPosition", "children", "onClick"]);
var getClassByStyle = function () {
switch (style) {
case 'secondary':
return styles$o.secondary;
case 'warning':
return styles$o.warning;
case 'alert':
return styles$o.alert;
case 'text':
return styles$o.text;
case 'text_gray':
return styles$o.text_gray;
case 'textAlert':
return styles$o.textAlert;
default:
return '';
}
};
return (React__default.createElement("button", __assign({ className: [
styles$o.button,
style ? getClassByStyle() : '',
small ? 'text-small ' + styles$o.small : '',
loading ? styles$o.loading : '',
block ? styles$o.block : '',
iconPosition === 'right' ? styles$o.right : '',
].join(' '), disabled: loading || disabled, onClick: onClick, type: htmlType }, props),
loading ? React__default.createElement(LoadingOutlined$3, null) : icon,
children));
};
var css_248z$n = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.ShadowCard-module_shadowCard__TWW0n {\n background-color: white;\n box-shadow: 0px 0.25rem 1rem rgba(0, 0, 0, 0.1);\n}";
var styles$n = {"shadowCard":"ShadowCard-module_shadowCard__TWW0n"};
styleInject(css_248z$n);
var ShadowCard = function (_a) {
var _b = _a.width, width = _b === void 0 ? '100%' : _b, _c = _a.height, height = _c === void 0 ? '100%' : _c, children = _a.children;
return (React__default.createElement("div", { className: styles$n.shadowCard, style: { width: width, height: height } }, children));
};
var css_248z$m = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.ProgressBar-module_progressBar__gt9o5 {\n height: 1.4375rem;\n width: 100%;\n background-color: #DDE3EB;\n position: relative;\n}\n.ProgressBar-module_progressBar__gt9o5 > .ProgressBar-module_percentage__i76tx {\n line-height: 1em;\n font-weight: 700;\n color: #002559;\n position: absolute;\n z-index: 2;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n}\n.ProgressBar-module_progressBar__gt9o5 > .ProgressBar-module_percentage__i76tx.ProgressBar-module_white__odsbw {\n color: white;\n}\n.ProgressBar-module_progressBar__gt9o5 > .ProgressBar-module_progress__jOOZO {\n position: absolute;\n inset: 0;\n z-index: 1;\n background-color: #002559;\n transform-origin: left;\n transition: transform 0.1s ease-in-out;\n transform: scaleX(0%);\n}\n.ProgressBar-module_progressBar__gt9o5 > .ProgressBar-module_progress__jOOZO.ProgressBar-module_ok__-ZINd {\n background-color: #039C3D;\n}\n.ProgressBar-module_progressBar__gt9o5 > .ProgressBar-module_progress__jOOZO.ProgressBar-module_warning__XUl-4 {\n background-color: #F4971F;\n}\n.ProgressBar-module_progressBar__gt9o5 > .ProgressBar-module_progress__jOOZO.ProgressBar-module_alert__XCl0B {\n background-color: #B8181E;\n}\n.ProgressBar-module_progressBar__gt9o5.ProgressBar-module_tiny__wSDIH {\n height: 0.5rem;\n}\n.ProgressBar-module_progressBar__gt9o5.ProgressBar-module_tiny__wSDIH > .ProgressBar-module_percentage__i76tx {\n display: none;\n}";
var styles$m = {"progressBar":"ProgressBar-module_progressBar__gt9o5","percentage":"ProgressBar-module_percentage__i76tx","white":"ProgressBar-module_white__odsbw","progress":"ProgressBar-module_progress__jOOZO","ok":"ProgressBar-module_ok__-ZINd","warning":"ProgressBar-module_warning__XUl-4","alert":"ProgressBar-module_alert__XCl0B","tiny":"ProgressBar-module_tiny__wSDIH"};
styleInject(css_248z$m);
var ProgressBar = function (_a) {
var percentage = _a.percentage, _b = _a.color, color = _b === void 0 ? 'primary' : _b, _c = _a.width, width = _c === void 0 ? '100%' : _c, tiny = _a.tiny;
var _d = useState(percentage), progress = _d[0], setProgress = _d[1];
useEffect(function () {
if (progress > 100)
setProgress(100);
else if (progress < 0)
setProgress(0);
}, [percentage]);
var getProgressColor = function () {
switch (color) {
case 'ok':
return styles$m.ok;
case 'warning':
return styles$m.warning;
case 'alert':
return styles$m.alert;
default:
return '';
}
};
return (React__default.createElement("div", { className: "".concat(styles$m.progressBar, " ").concat(tiny ? styles$m.tiny : ''), style: { width: width } },
!tiny ? (React__default.createElement("span", { className: "".concat(styles$m.percentage, " ").concat(percentage > 48 ? styles$m.white : '') },
percentage,
"%")) : null,
React__default.createElement("div", { className: "".concat(styles$m.progress, " ").concat(getProgressColor()), style: { transform: "scaleX(".concat(percentage, "%)") } })));
};
var css_248z$l = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.ProgressBarRounded-module_progressBarRounded__HfTXl {\n position: relative;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n.ProgressBarRounded-module_progressBarRounded__HfTXl > svg {\n transform: rotate(-90deg);\n}\n.ProgressBarRounded-module_progressBarRounded__HfTXl > svg > circle:nth-child(1) {\n stroke: #F6F9FB;\n}\n.ProgressBarRounded-module_progressBarRounded__HfTXl > svg > circle:nth-child(2).ProgressBarRounded-module_primary__kNwCN {\n stroke: #002559;\n}\n.ProgressBarRounded-module_progressBarRounded__HfTXl > svg > circle:nth-child(2).ProgressBarRounded-module_green__xXauJ {\n stroke: #039C3D;\n}\n.ProgressBarRounded-module_progressBarRounded__HfTXl > span {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n font-weight: 700;\n font-size: 1.5rem;\n line-height: 1em;\n color: #002559;\n text-align: center;\n}\n.ProgressBarRounded-module_progressBarRounded__HfTXl > span.ProgressBarRounded-module_green__xXauJ {\n color: #039C3D;\n}";
var styles$l = {"progressBarRounded":"ProgressBarRounded-module_progressBarRounded__HfTXl","primary":"ProgressBarRounded-module_primary__kNwCN","green":"ProgressBarRounded-module_green__xXauJ"};
styleInject(css_248z$l);
var ProgressBarRounded = function (_a) {
var percentage = _a.percentage, _b = _a.size, size = _b === void 0 ? 162 : _b, _c = _a.thickness, thickness = _c === void 0 ? 24 : _c, text = _a.text, color = _a.color;
var _d = useState(percentage), progress = _d[0], setProgress = _d[1];
var getStrokeColor = function () {
switch (color) {
case 'green':
return styles$l.green;
default:
return styles$l.primary;
}
};
useEffect(function () {
if (progress > 100)
setProgress(100);
else if (progress < 0)
setProgress(0);
}, [percentage]);
var radius = (size - thickness) / 2;
var circumference = 2 * Math.PI * radius;
var circleProgress = circumference - (percentage * circumference) / 100;
return (React__default.createElement("div", { className: styles$l.progressBarRounded },
React__default.createElement("svg", { width: size, height: size },
React__default.createElement("circle", { cx: size / 2, cy: size / 2, r: radius, stroke: "white", strokeWidth: thickness, fill: "none" }),
React__default.createElement("circle", { cx: size / 2, cy: size / 2, r: radius, stroke: "black", className: getStrokeColor(), strokeWidth: thickness, strokeDasharray: circumference + ' ' + circumference, style: { strokeDashoffset: circleProgress }, fill: "none" })),
React__default.createElement("span", { className: getStrokeColor() }, text !== null && text !== void 0 ? text : "".concat(progress || 0, "%"))));
};
var css_248z$k = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.ManageItemButton-module_manageItemButton__sLavO {\n background: none;\n border: none;\n padding: 1.125rem 1.625rem;\n cursor: pointer;\n font-size: 1.25rem;\n display: flex;\n align-items: center;\n gap: 0.625rem;\n}\n.ManageItemButton-module_manageItemButton__sLavO > .ManageItemButton-module_icon__t-pJy {\n aspect-ratio: 1/1;\n min-width: 2rem;\n width: 2rem;\n min-height: 2rem;\n height: 2rem;\n}\n.ManageItemButton-module_manageItemButton__sLavO > .ManageItemButton-module_icon__t-pJy path {\n fill: #A9C2D3;\n transition: fill 0.15s ease-in-out;\n}\n.ManageItemButton-module_manageItemButton__sLavO:hover > .ManageItemButton-module_icon__t-pJy path {\n fill: #002559;\n}\n.ManageItemButton-module_manageItemButton__sLavO.ManageItemButton-module_vertical__clll9 {\n flex-direction: column;\n}\n.ManageItemButton-module_manageItemButton__sLavO.ManageItemButton-module_tiny__sFXFZ {\n font-size: 1rem;\n}\n.ManageItemButton-module_manageItemButton__sLavO.ManageItemButton-module_tiny__sFXFZ > .ManageItemButton-module_icon__t-pJy {\n min-width: 1.5rem;\n width: 1.5rem;\n min-height: 1.5rem;\n height: 1.5rem;\n}";
var styles$k = {"manageItemButton":"ManageItemButton-module_manageItemButton__sLavO","icon":"ManageItemButton-module_icon__t-pJy","vertical":"ManageItemButton-module_vertical__clll9","tiny":"ManageItemButton-module_tiny__sFXFZ"};
styleInject(css_248z$k);
var ManageItemButton = function (_a) {
var label = _a.label, _b = _a.type, type = _b === void 0 ? 'add' : _b, _c = _a.direction, direction = _c === void 0 ? 'horizontal' : _c, _d = _a.tiny, tiny = _d === void 0 ? false : _d, onClick = _a.onClick;
return (React__default.createElement("button", { onClick: onClick, className: "".concat(styles$k.manageItemButton, " ").concat(direction === 'vertical' ? styles$k.vertical : '', " ").concat(tiny ? styles$k.tiny : '') },
type === 'add' ? (React__default.createElement("svg", { className: styles$k.icon, width: "64", height: "64", viewBox: "0 0 64 64", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
React__default.createElement("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M32 64C49.6731 64 64 49.6731 64 32C64 14.3269 49.6731 0 32 0C14.3269 0 0 14.3269 0 32C0 49.6731 14.3269 64 32 64ZM35.7 35.56H49.7V28.21H35.7V14H27.93V28.21H14V35.56H27.93V49.7H35.7V35.56Z", fill: "#A9C2D3" }))) : (React__default.createElement("svg", { className: styles$k.icon, width: "64", height: "64", viewBox: "0 0 64 64", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
React__default.createElement("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M32 64C49.6731 64 64 49.6731 64 32C64 14.3269 49.6731 0 32 0C14.3269 0 0 14.3269 0 32C0 49.6731 14.3269 64 32 64ZM42.7735 18.5938C41.4063 17.2266 39.1641 17.2266 37.7969 18.5938L35.1719 21.2188L42.2813 28.3281L44.9063 25.7031C46.2735 24.3359 46.2735 22.0938 44.9063 20.7266L42.7735 18.5938ZM28.2813 42.3281L41.0235 29.5859L33.9141 22.4766L21.1719 35.2188C20.625 35.7656 20.1875 36.4766 19.9688 37.2422L18 43.8594C17.8907 44.2969 18 44.7891 18.3829 45.1172C18.711 45.5 19.2032 45.6094 19.6407 45.4453L26.2579 43.5312C27.0235 43.3125 27.7344 42.875 28.2813 42.3281Z", fill: "#A9C2D3" }))),
label));
};
var css_248z$j = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.DropdownFilter-module_filtersContainer__fmhxG {\n background-color: #FFFFFF;\n cursor: pointer;\n width: 100%;\n overflow: hidden;\n display: flex;\n padding: 0.75rem 0.875rem;\n border-radius: 0.25rem;\n border: 1px solid #dde3eb;\n height: 4rem;\n max-height: 4rem;\n transition: 0.3s ease-in-out;\n}\n.DropdownFilter-module_filtersContainer__fmhxG .DropdownFilter-module_containerFilterSelection__fj9R- {\n display: flex;\n align-items: center;\n gap: 2rem;\n width: 100%;\n}\n.DropdownFilter-module_filtersContainer__fmhxG .DropdownFilter-module_containerFilterSelection__fj9R- .DropdownFilter-module_head__IgGn7 {\n width: 100%;\n display: flex;\n flex-direction: column;\n justify-content: center;\n}\n.DropdownFilter-module_filtersContainer__fmhxG .DropdownFilter-module_containerFilterSelection__fj9R- .DropdownFilter-module_head__IgGn7 .DropdownFilter-module_title__z0POF {\n display: inline-flex;\n align-items: center;\n gap: 0.625rem;\n font-size: 1rem;\n line-height: 1em;\n}\n.DropdownFilter-module_filtersContainer__fmhxG .DropdownFilter-module_containerFilterSelection__fj9R- .DropdownFilter-module_chevronButton__IRk5j {\n border: none;\n background: none;\n padding: 0;\n height: 1rem;\n cursor: pointer;\n transform: rotate(1);\n transition: transform 0.3s ease-in-out;\n}\n.DropdownFilter-module_filtersContainer__fmhxG .DropdownFilter-module_containerFilterSelection__fj9R- .DropdownFilter-module_chevronButton__IRk5j.DropdownFilter-module_open__XxRP4 {\n transform: rotate(0.5turn);\n}\n.DropdownFilter-module_filtersContainer__fmhxG .DropdownFilter-module_containerFilterSelection__fj9R- .DropdownFilter-module_sectionFilterSelection__os8X- {\n display: flex;\n width: 100%;\n margin-top: 2px;\n}\n.DropdownFilter-module_filtersContainer__fmhxG .DropdownFilter-module_containerFilterSelection__fj9R- .DropdownFilter-module_sectionFilterSelection__os8X- .DropdownFilter-module_selectedCategories__dlKjs {\n display: flex;\n font-size: small;\n color: #999999;\n}";
var styles$j = {"filtersContainer":"DropdownFilter-module_filtersContainer__fmhxG","containerFilterSelection":"DropdownFilter-module_containerFilterSelection__fj9R-","head":"DropdownFilter-module_head__IgGn7","title":"DropdownFilter-module_title__z0POF","chevronButton":"DropdownFilter-module_chevronButton__IRk5j","open":"DropdownFilter-module_open__XxRP4","sectionFilterSelection":"DropdownFilter-module_sectionFilterSelection__os8X-","selectedCategories":"DropdownFilter-module_selectedCategories__dlKjs"};
styleInject(css_248z$j);
var DropdownFilter = function (_a) {
var _b = _a.label, label = _b === void 0 ? 'Données affichées' : _b, showFilters = _a.showFilters, setShowFilters = _a.setShowFilters, filtersSelection = _a.filtersSelection;
var renderFilterSelection = function () {
var filters = filtersSelection.map(function (fs) {
return "".concat(fs.key.length, " ").concat(fs.key.length > 1
? fs.categoryName.toLowerCase()
: fs.categoryName.toLowerCase().slice(0, fs.categoryName.length - 1));
});
return filters.join(', ');
};
return (React__default.createElement("div", { className: styles$j.filtersContainer, style: showFilters ? { height: '4rem' } : undefined, onClick: function () {
setShowFilters(function (prev) { return !prev; });
} },
React__default.createElement("div", { className: styles$j.containerFilterSelection },
React__default.createElement("div", { className: styles$j.head },
React__default.createElement("span", { className: styles$j.title }, label),
filtersSelection.length > 0 ? (React__default.createElement("section", { className: styles$j.sectionFilterSelection },
React__default.createElement("span", { className: "text-tiny ".concat(styles$j.selectedCategories) }, renderFilterSelection()))) : null),
React__default.createElement("button", { className: "".concat(styles$j.chevronButton, " ").concat(showFilters ? styles$j.open : '') },
React__default.createElement("svg", { width: "17", height: "9", viewBox: "0 0 17 9", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
React__default.createElement("path", { d: "M16.5742 7.88672C16.4688 8.02734 16.3281 8.0625 16.1875 8.0625C16.0469 8.0625 15.9062 8.02734 15.8008 7.92188L8.875 1.52344L1.91406 7.88672C1.70312 8.09766 1.35156 8.09766 1.14062 7.85156C0.929688 7.64062 0.929688 7.28906 1.17578 7.07812L8.48828 0.328125C8.69922 0.117188 9.01562 0.117188 9.22656 0.328125L16.5391 7.07812C16.7852 7.32422 16.7852 7.67578 16.5742 7.88672Z", fill: "black" }))))));
};
var css_248z$i = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n@supports (display: grid) {\n .Grid-module_grid__P7g8D {\n display: grid;\n grid-template-columns: repeat(4, 1fr);\n }\n}\n@supports (display: grid) {\n .Grid-module_grid__P7g8D {\n display: grid;\n grid-auto-rows: 1fr;\n }\n}\n@supports (display: grid) {\n .Grid-module_grid__P7g8D {\n grid-gap: 2rem 2rem;\n }\n}\n@media (max-width: 1599.98px) {\n @supports (display: grid) {\n .Grid-module_grid__P7g8D {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n }\n }\n}\n@media (max-width: 991.98px) {\n @supports (display: grid) {\n .Grid-module_grid__P7g8D {\n display: grid;\n grid-template-columns: repeat(2, 1fr);\n }\n }\n}\n@media (max-width: 575.98px) {\n @supports (display: grid) {\n .Grid-module_grid__P7g8D {\n display: grid;\n grid-template-columns: repeat(1, 1fr);\n }\n }\n}\n@supports (display: grid) {\n .Grid-module_grid__P7g8D.Grid-module_narrow__bmpgp {\n display: grid;\n grid-template-columns: repeat(2, 1fr);\n }\n}\n@media (max-width: 1599.98px) {\n @supports (display: grid) {\n .Grid-module_grid__P7g8D.Grid-module_narrow__bmpgp {\n display: grid;\n grid-template-columns: repeat(2, 1fr);\n }\n }\n}\n@media (max-width: 991.98px) {\n @supports (display: grid) {\n .Grid-module_grid__P7g8D.Grid-module_narrow__bmpgp {\n display: grid;\n grid-template-columns: repeat(1, 1fr);\n }\n }\n}\n@media (max-width: 575.98px) {\n @supports (display: grid) {\n .Grid-module_grid__P7g8D.Grid-module_narrow__bmpgp {\n display: grid;\n grid-template-columns: repeat(1, 1fr);\n }\n }\n}";
var styles$i = {"grid":"Grid-module_grid__P7g8D","narrow":"Grid-module_narrow__bmpgp"};
styleInject(css_248z$i);
var Grid = function (_a) {
var _b = _a.type, type = _b === void 0 ? 'classic' : _b, children = _a.children;
var getClassByType = function () {
switch (type) {
case 'narrow':
return styles$i.narrow;
default:
return '';
}
};
return React__default.createElement("div", { className: "".concat(styles$i.grid, " ").concat(getClassByType()) }, children);
};
var css_248z$h = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.QuickActionCard-module_quickActionCard__juLlJ {\n width: 100%;\n height: 100%;\n padding: 1rem 4rem;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n gap: 1.25rem;\n}\n.QuickActionCard-module_quickActionCard__juLlJ .QuickActionCard-module_body__tvlO1 .QuickActionCard-module_title__iD-1g {\n font-size: 1.25rem;\n color: #002559;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n.QuickActionCard-module_quickActionCard__juLlJ .QuickActionCard-module_body__tvlO1 .QuickActionCard-module_text__uEy5A {\n margin: 0.5rem 0;\n}";
var styles$h = {"quickActionCard":"QuickActionCard-module_quickActionCard__juLlJ","body":"QuickActionCard-module_body__tvlO1","title":"QuickActionCard-module_title__iD-1g","text":"QuickActionCard-module_text__uEy5A"};
styleInject(css_248z$h);
var QuickActionCard = function (_a) {
var title = _a.title, children = _a.children, progress = _a.progress, button = _a.button;
return (React__default.createElement(ShadowCard, null,
React__default.createElement("div", { className: styles$h.quickActionCard },
React__default.createElement("div", { className: styles$h.body },
React__default.createElement("h3", { className: styles$h.title }, title),
React__default.createElement("p", { className: "text-small ".concat(styles$h.text) }, children),
progress ? React__default.createElement(ProgressBar, { percentage: progress }) : null),
button ? (React__default.createElement("div", { className: styles$h.footer }, button.href && !button.onClick ? (React__default.createElement(Link, { href: button.href },
React__default.createElement(Button$2, { block: true, icon: button.icon }, button.label))) : (React__default.createElement(Button$2, { block: true, icon: button.icon, onClick: button.onClick }, button.label)))) : null)));
};
var css_248z$g = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.ManageItemCard-module_manageItemCard__2PrU- {\n height: 100%;\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n}";
var styles$g = {"manageItemCard":"ManageItemCard-module_manageItemCard__2PrU-"};
styleInject(css_248z$g);
var NewItemCard = function (props) {
return (React__default.createElement(ShadowCard, { width: "auto" },
React__default.createElement("div", { className: styles$g.manageItemCard },
React__default.createElement(ManageItemButton, __assign({}, props)))));
};
var css_248z$f = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.FormItem-module_formItem__yGGZj {\n display: flex;\n flex-direction: column;\n gap: 0.375rem;\n}\n.FormItem-module_formItem__yGGZj .FormItem-module_label__O7k1M {\n font-weight: 700;\n font-size: 0.875rem;\n}\n.FormItem-module_formItem__yGGZj .FormItem-module_itemContainer__G-vYT {\n background-color: #ffffff;\n border: 1px solid #DDE3EB;\n display: flex;\n align-items: center;\n position: relative;\n}\n.FormItem-module_formItem__yGGZj.FormItem-module_isFocus__L4BRz .FormItem-module_itemContainer__G-vYT {\n border-color: #333333;\n}\n.FormItem-module_formItem__yGGZj.FormItem-module_disabled__cSITz .FormItem-module_itemContainer__G-vYT {\n border-color: #FAFAFA;\n}";
var styles$f = {"formItem":"FormItem-module_formItem__yGGZj","label":"FormItem-module_label__O7k1M","itemContainer":"FormItem-module_itemContainer__G-vYT","isFocus":"FormItem-module_isFocus__L4BRz","disabled":"FormItem-module_disabled__cSITz"};
styleInject(css_248z$f);
var FormItem = function (_a) {
var label = _a.label, _b = _a.disabled, disabled = _b === void 0 ? false : _b, _c = _a.isFocus, isFocus = _c === void 0 ? false : _c, children = _a.children;
return (React__default.createElement("div", { className: "".concat(styles$f.formItem, " ").concat(disabled ? styles$f.disabled : '', " ").concat(isFocus ? styles$f.isFocus : '') },
label ? (React__default.createElement("label", { className: styles$f.label, htmlFor: label }, label)) : null,
React__default.createElement("div", { className: styles$f.itemContainer }, children)));
};
var css_248z$e = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.Input-module_input__G0ar9 {\n color: #333333;\n padding: 0.5rem;\n width: 100%;\n background: none;\n border: none;\n outline: none;\n font-size: 1rem;\n line-height: 1.375em;\n}\n.Input-module_input__G0ar9[type=search]::-webkit-search-decoration, .Input-module_input__G0ar9[type=search]::-webkit-search-cancel-button, .Input-module_input__G0ar9[type=search]::-webkit-search-results-button, .Input-module_input__G0ar9[type=search]::-webkit-search-results-decoration {\n display: none;\n}\n.Input-module_input__G0ar9:disabled {\n background-color: #FAFAFA;\n color: #999999;\n cursor: not-allowed;\n}\n.Input-module_input__G0ar9:disabled ~ .Input-module_button__7UGjk {\n pointer-events: none;\n}\n.Input-module_input__G0ar9:disabled ~ .Input-module_button__7UGjk path {\n fill: #DDE3EB;\n}\n.Input-module_input__G0ar9.Input-module_large__rsjNO {\n font-size: 1.125rem;\n}\n\n.Input-module_button__7UGjk {\n padding: 0;\n background: none;\n border: none;\n margin-right: 0.5rem;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n position: absolute;\n right: 0;\n}\n.Input-module_button__7UGjk path {\n fill: #333333;\n}";
var styles$e = {"input":"Input-module_input__G0ar9","button":"Input-module_button__7UGjk","large":"Input-module_large__rsjNO"};
styleInject(css_248z$e);
var Input = function (_a) {
var label = _a.label, _b = _a.disabled, disabled = _b === void 0 ? false : _b, name = _a.name, _c = _a.type, type = _c === void 0 ? 'text' : _c, onIconClick = _a.onIconClick, placeholder = _a.placeholder, large = _a.large, value = _a.value, setValue = _a.setValue;
var _d = useState(false), isFocus = _d[0], setIsFocus = _d[1];
return (React__default.createElement(FormItem, { label: label, disabled: disabled, isFocus: isFocus },
React__default.createElement("input", { className: "".concat(styles$e.input, " ").concat(large ? styles$e.large : ''), id: label, name: name, type: type, placeholder: placeholder, value: value, onChange: function (e) { return setValue(e.target.value); }, onFocus: function () { return setIsFocus(true); }, onBlur: function () { return setIsFocus(false); }, disabled: disabled }),
type === 'search' ? (React__default.createElement("button", { className: styles$e.button, onClick: onIconClick },
React__default.createElement("svg", { width: "15", height: "15", viewBox: "0 0 15 15", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
React__default.createElement("path", { d: "M13.8633 13.5117L9.98047 9.65625C10.8555 8.64453 11.3477 7.35938 11.3477 5.9375C11.3477 2.82031 8.77734 0.25 5.66016 0.25C2.51562 0.25 0 2.82031 0 5.9375C0 9.08203 2.54297 11.625 5.66016 11.625C7.05469 11.625 8.33984 11.1328 9.35156 10.2578L13.207 14.1406C13.3164 14.2227 13.4258 14.25 13.5625 14.25C13.6719 14.25 13.7812 14.2227 13.8633 14.1406C14.0273 13.9766 14.0273 13.6758 13.8633 13.5117ZM5.6875 10.75C3.00781 10.75 0.875 8.58984 0.875 5.9375C0.875 3.28516 3.00781 1.125 5.6875 1.125C8.33984 1.125 10.5 3.28516 10.5 5.9375C10.5 8.61719 8.33984 10.75 5.6875 10.75Z" })))) : null));
};
var css_248z$d = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.Select-module_select__sbUrw {\n color: #333333;\n padding: 0.5rem;\n width: 100%;\n background: none;\n border: none;\n outline: none;\n font-size: 1rem;\n line-height: 1.375em;\n appearance: none;\n -webkit-appearance: none;\n -moz-appearance: none;\n text-indent: 1px;\n text-overflow: \"\";\n position: relative;\n}\n.Select-module_select__sbUrw:disabled {\n background-color: #FAFAFA;\n color: #999999;\n cursor: not-allowed;\n}\n.Select-module_select__sbUrw:disabled ~ .Select-module_arrow__2c8Gw > path {\n fill: #DDE3EB;\n}\n.Select-module_select__sbUrw.Select-module_large__QwQa7 {\n font-size: 1.125rem;\n}\n\n.Select-module_arrow__2c8Gw {\n pointer-events: none;\n position: absolute;\n height: 100%;\n right: 0.5rem;\n top: 0;\n bottom: 0;\n}";
var styles$d = {"select":"Select-module_select__sbUrw","arrow":"Select-module_arrow__2c8Gw","large":"Select-module_large__QwQa7"};
styleInject(css_248z$d);
var Select = function (_a) {
var label = _a.label, _b = _a.disabled, disabled = _b === void 0 ? false : _b, name = _a.name, options = _a.options, _c = _a.displayNullOption, displayNullOption = _c === void 0 ? true : _c, nullOptionText = _a.nullOptionText, _d = _a.large, large = _d === void 0 ? false : _d, value = _a.value, setValue = _a.setValue;
var _e = useState(false), isFocus = _e[0], setIsFocus = _e[1];
var capitalize = function (str) { return str.charAt(0).toUpperCase() + str.slice(1); };
return (React__default.createElement(FormItem, { label: label, disabled: disabled, isFocus: isFocus },
React__default.createElement("select", { className: "".concat(styles$d.select, " ").concat(large ? styles$d.large : ''), name: name, id: label, disabled: disabled, value: value, onChange: function (e) { return setValue(e.target.value); }, onFocus: function () { return setIsFocus(true); }, onBlur: function () { return setIsFocus(false); } },
displayNullOption && (React__default.createElement("option", { key: '', value: '' }, nullOptionText)),
options.map(function (option) { return (React__default.createElement("option", { key: option.value, value: option.value }, capitalize(option.text))); })),
React__default.createElement("svg", { className: styles$d.arrow, width: "17", height: "9", viewBox: "0 0 17 9", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
React__default.createElement("path", { d: "M1.14062 0.648438C1.24609 0.507812 1.38672 0.4375 1.5625 0.4375C1.66797 0.4375 1.80859 0.472656 1.91406 0.578125L8.83984 6.94141L15.8008 0.578125C16.0117 0.367188 16.3633 0.367188 16.5742 0.613281C16.7852 0.824219 16.7852 1.17578 16.5391 1.38672L9.22656 8.13672C9.01562 8.34766 8.69922 8.34766 8.48828 8.13672L1.17578 1.38672C0.929688 1.21094 0.929688 0.859375 1.14062 0.648438Z", fill: "black" }))));
};
var css_248z$c = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.Textarea-module_textarea__CAdDc {\n font-family: \"Open Sans\", sans-serif;\n font-style: normal;\n font-weight: 400;\n resize: none;\n height: 4.125rem;\n color: #333333;\n padding: 0.5rem;\n width: 100%;\n background: none;\n border: none;\n outline: none;\n font-size: 1rem;\n line-height: 1.375em;\n}\n.Textarea-module_textarea__CAdDc:disabled {\n background-color: #FAFAFA;\n color: #999999;\n cursor: not-allowed;\n}\n.Textarea-module_textarea__CAdDc.Textarea-module_large__wYcx8 {\n font-size: 1.125rem;\n}";
var styles$c = {"textarea":"Textarea-module_textarea__CAdDc","large":"Textarea-module_large__wYcx8"};
styleInject(css_248z$c);
var Textarea = function (_a) {
var label = _a.label, _b = _a.disabled, disabled = _b === void 0 ? false : _b, name = _a.name, placeholder = _a.placeholder, large = _a.large, value = _a.value, setValue = _a.setValue;
var _c = useState(false), isFocus = _c[0], setIsFocus = _c[1];
return (React__default.createElement(FormItem, { label: label, disabled: disabled, isFocus: isFocus },
React__default.createElement("textarea", { className: "".concat(styles$c.textarea, " ").concat(large ? styles$c.large : ''), id: label, name: name, placeholder: placeholder, value: value, onChange: function (e) { return setValue(e.target.value); }, onFocus: function () { return setIsFocus(true); }, onBlur: function () { return setIsFocus(false); }, disabled: disabled })));
};
var css_248z$b = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.Modal-module_modal__b2VqT.Modal-module_overlay__cyEkn {\n position: absolute;\n z-index: 999;\n inset: 0;\n background-color: rgba(0, 0, 0, 0.25);\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n animation: Modal-module_fadeOpacity__u08Rg forwards 0.3s;\n}\n.Modal-module_modal__b2VqT.Modal-module_overlay__cyEkn .Modal-module_modalCard__oLfyx {\n background-color: #FFFFFF;\n padding: 1.5rem;\n margin: 1rem;\n border-radius: 0.25rem;\n width: 40rem;\n max-width: 100vw;\n overflow: hidden;\n opacity: 0;\n transform: translateY(150%);\n animation: Modal-module_emergeFromBottom__EM6fk forwards 0.3s ease-out;\n}\n\n@keyframes Modal-module_fadeOpacity__u08Rg {\n to {\n opacity: 1;\n }\n}\n@keyframes Modal-module_emergeFromBottom__EM6fk {\n to {\n opacity: 1;\n transform: translateY(0);\n }\n}";
var styles$b = {"modal":"Modal-module_modal__b2VqT","overlay":"Modal-module_overlay__cyEkn","fadeOpacity":"Modal-module_fadeOpacity__u08Rg","modalCard":"Modal-module_modalCard__oLfyx","emergeFromBottom":"Modal-module_emergeFromBottom__EM6fk"};
styleInject(css_248z$b);
var Modal = function (_a) {
var isOpen = _a.isOpen, setIsOpen = _a.setIsOpen, children = _a.children;
var modalPortalRef = useRef();
useEffect(function () {
var modalPortal = document.createElement('div');
modalPortal.setAttribute('id', 'modal-portal');
document.body.appendChild(modalPortal);
modalPortalRef.current = modalPortal;
return function () {
modalPortal.remove();
modalPortalRef.current = undefined;
};
}, []);
var renderModal = function () { return (React__default.createElement("div", { className: "".concat(styles$b.modal, " ").concat(styles$b.overlay), onClick: function () { return setIsOpen(false); } },
React__default.createElement("section", { onClick: function (e) { return e.stopPropagation(); }, className: styles$b.modalCard }, children))); };
return React__default.createElement(React__default.Fragment, null, isOpen && modalPortalRef.current ? createPortal(renderModal(), modalPortalRef.current) : null);
};
var css_248z$a = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.RecentActivities-module_recentActivities__4xf4d {\n background-color: #FFFFFF;\n width: 100%;\n min-height: 100%;\n list-style: none;\n margin: 0;\n padding: 0;\n}\n.RecentActivities-module_recentActivities__4xf4d .RecentActivities-module_activity__0Be-t {\n display: flex;\n align-items: center;\n gap: 0.75rem;\n line-height: 1em;\n padding: 0.75rem 0;\n border-bottom: 1px solid #DDE3EB;\n}\n.RecentActivities-module_recentActivities__4xf4d .RecentActivities-module_activity__0Be-t .RecentActivities-module_creationDate__U77UH {\n min-width: 6rem;\n max-width: 6rem;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n.RecentActivities-module_recentActivities__4xf4d .RecentActivities-module_activity__0Be-t .RecentActivities-module_label__wztTp {\n margin: 0;\n font-weight: 700;\n flex-grow: 1;\n word-break: break-all;\n}\n.RecentActivities-module_recentActivities__4xf4d .RecentActivities-module_activity__0Be-t .RecentActivities-module_author__3Uz4U {\n min-width: 10rem;\n max-width: 10rem;\n text-align: right;\n word-break: break-all;\n}";
var styles$a = {"recentActivities":"RecentActivities-module_recentActivities__4xf4d","activity":"RecentActivities-module_activity__0Be-t","creationDate":"RecentActivities-module_creationDate__U77UH","label":"RecentActivities-module_label__wztTp","author":"RecentActivities-module_author__3Uz4U"};
styleInject(css_248z$a);
var RecentActivities = function (_a) {
var activities = _a.activities;
return (React__default.createElement("ul", { className: styles$a.recentActivities }, activities.map(function (activity, index) { return (React__default.createElement("li", { key: index, className: styles$a.activity },
React__default.createElement("time", { className: "text-small ".concat(styles$a.creationDate) }, activity.creationDate),
React__default.createElement("p", { className: "text-small ".concat(styles$a.label) }, activity.label),
React__default.createElement("span", { className: "text-tiny ".concat(styles$a.author) },
"par ",
activity.author))); })));
};
var css_248z$9 = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.RecentActivitiesCard-module_recentActivitiesContainer__bKNIF {\n width: 100%;\n height: 100%;\n max-height: 17.75rem;\n overflow: auto;\n background-color: #FFFFFF;\n padding: 1rem;\n}";
var styles$9 = {"recentActivitiesContainer":"RecentActivitiesCard-module_recentActivitiesContainer__bKNIF"};
styleInject(css_248z$9);
var RecentActivitiesCard = function (props) {
return (React__default.createElement(ShadowCard, null,
React__default.createElement("div", { className: styles$9.recentActivitiesContainer },
React__default.createElement(RecentActivities, __assign({}, props)))));
};
var css_248z$8 = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.InformationsTable-module_informationsTable__-fx7g {\n width: 100%;\n max-width: 100%;\n display: flex;\n}\n.InformationsTable-module_informationsTable__-fx7g thead {\n display: block;\n width: 12rem;\n max-width: 12rem;\n overflow: hidden;\n}\n.InformationsTable-module_informationsTable__-fx7g tbody {\n flex-grow: 1;\n max-width: 100%;\n overflow: hidden;\n}\n.InformationsTable-module_informationsTable__-fx7g tr {\n display: flex;\n align-items: center;\n height: 3rem;\n width: 100%;\n border-bottom: 1px solid #DDE3EB;\n}\n.InformationsTable-module_informationsTable__-fx7g tr:first-child {\n border-top: 1px solid #DDE3EB;\n}\n.InformationsTable-module_informationsTable__-fx7g th, .InformationsTable-module_informationsTable__-fx7g td {\n display: block;\n padding: 0;\n padding-right: 1rem;\n text-align: left;\n width: 100%;\n max-width: 100%;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}";
var styles$8 = {"informationsTable":"InformationsTable-module_informationsTable__-fx7g"};
styleInject(css_248z$8);
var InformationsTable = function (_a) {
var items = _a.items;
return (React__default.createElement("table", { className: styles$8.informationsTable },
React__default.createElement("thead", null, items.map(function (item) { return (React__default.createElement("tr", { key: item.label },
React__default.createElement("th", null, item.label))); })),
React__default.createElement("tbody", null, items.map(function (item) { return (React__default.createElement("tr", { key: item.label },
React__default.createElement("td", null, item.value))); }))));
};
var css_248z$7 = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.UserProfileWidget-module_avatarContainer__JT5hl {\n height: 31px !important;\n width: 31px !important;\n position: relative !important;\n}\n\n.UserProfileWidget-module_userProfileWidget__cI2Xx {\n display: flex;\n align-items: center;\n gap: 0.75rem;\n}\n.UserProfileWidget-module_userProfileWidget__cI2Xx > .UserProfileWidget-module_textContainer__-uBQM {\n max-width: 10rem;\n}\n.UserProfileWidget-module_userProfileWidget__cI2Xx > .UserProfileWidget-module_textContainer__-uBQM span {\n display: block;\n line-height: 1.125rem;\n text-align: right;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n.UserProfileWidget-module_userProfileWidget__cI2Xx > .UserProfileWidget-module_textContainer__-uBQM span.UserProfileWidget-module_name__CYWby {\n font-family: PollyBold;\n color: #002559;\n font-size: 1rem;\n letter-spacing: -0.02em;\n}\n.UserProfileWidget-module_userProfileWidget__cI2Xx > .UserProfileWidget-module_textContainer__-uBQM span.UserProfileWidget-module_company__osmry {\n font-family: \"Open Sans\", sans-serif;\n font-style: normal;\n font-weight: 700;\n color: #A9C2D3;\n font-size: 0.875rem;\n letter-spacing: 0.04em;\n text-transform: uppercase;\n}\n.UserProfileWidget-module_userProfileWidget__cI2Xx > .UserProfileWidget-module_imageContainer__D8x1r {\n width: 2rem;\n height: 2rem;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n.UserProfileWidget-module_userProfileWidget__cI2Xx > .UserProfileWidget-module_imageContainer__D8x1r svg,\n.UserProfileWidget-module_userProfileWidget__cI2Xx > .UserProfileWidget-module_imageContainer__D8x1r img {\n width: 100%;\n height: 100%;\n border-radius: 50%;\n}";
var styles$7 = {"avatarContainer":"UserProfileWidget-module_avatarContainer__JT5hl","userProfileWidget":"UserProfileWidget-module_userProfileWidget__cI2Xx","textContainer":"UserProfileWidget-module_textContainer__-uBQM","name":"UserProfileWidget-module_name__CYWby","company":"UserProfileWidget-module_company__osmry","imageContainer":"UserProfileWidget-module_imageContainer__D8x1r"};
styleInject(css_248z$7);
var UserProfileWidget = function (_a) {
var _b;
var user = _a.user, avatar = _a.avatar;
return (React__default.createElement("div", { className: styles$7.userProfileWidget },
React__default.createElement("div", { className: styles$7.textContainer },
React__default.createElement("span", { className: styles$7.name }, "".concat(user === null || user === void 0 ? void 0 : user.first_name, " ").concat((_b = user === null || user === void 0 ? void 0 : user.last_name) === null || _b === void 0 ? void 0 : _b.toUpperCase())),
React__default.createElement("span", { className: styles$7.company }, user === null || user === void 0 ? void 0 : user.company)),
React__default.createElement("div", { className: styles$7.imageContainer }, avatar ? (React__default.createElement("img", { src: avatar, alt: "avatar de ".concat(user === null || user === void 0 ? void 0 : user.first_name, " ").concat(user === null || user === void 0 ? void 0 : user.last_name), height: '31', width: '31' })) : (React__default.createElement("svg", { width: "30", height: "31", viewBox: "0 0 30 31", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
React__default.createElement("path", { d: "M15 0.75C6.67969 0.75 0 7.48828 0 15.75C0 24.0703 6.67969 30.75 15 30.75C23.2617 30.75 30 24.0703 30 15.75C30 7.48828 23.2617 0.75 15 0.75ZM15 8.25C17.2852 8.25 19.2188 10.1836 19.2188 12.4688C19.2188 14.8125 17.2852 16.6875 15 16.6875C12.6562 16.6875 10.7812 14.8125 10.7812 12.4688C10.7812 10.1836 12.6562 8.25 15 8.25ZM15 27C11.8945 27 9.08203 25.7695 7.03125 23.7188C7.96875 21.2578 10.3125 19.5 13.125 19.5H16.875C19.6289 19.5 21.9727 21.2578 22.9102 23.7188C20.8594 25.7695 18.0469 27 15 27Z", fill: "#1E1E42" }))))));
};
var css_248z$6 = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.TopBar-module_notification__UOEFZ {\n display: flex;\n justify-content: space-between;\n}\n.TopBar-module_notification__UOEFZ > .TopBar-module_label__2AtYu {\n margin-right: 2rem;\n max-width: 400px;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.TopBar-module_unread__K-drX::after {\n margin-right: 1rem;\n content: \"\";\n position: absolute;\n height: 100%;\n top: 50%;\n transform: translateY(-50%);\n right: 0;\n aspect-ratio: 1/1;\n width: 0.5rem;\n height: 0.5rem;\n background-color: #002559;\n border-radius: 50%;\n}\n\n.TopBar-module_topBar__8pC4I {\n width: 100%;\n max-width: 100vw;\n padding: 0 2rem;\n background: #FFFFFF;\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 4rem;\n position: relative;\n}\n.TopBar-module_topBar__8pC4I > .TopBar-module_navigation__tu3E0 {\n display: flex;\n align-items: center;\n gap: 4rem;\n max-width: 75%;\n}\n.TopBar-module_topBar__8pC4I > .TopBar-module_navigation__tu3E0 > .TopBar-module_homeLink__hehft {\n display: flex;\n align-items: center;\n justify-content: center;\n}\n.TopBar-module_topBar__8pC4I > .TopBar-module_navigation__tu3E0 > .TopBar-module_homeLink__hehft svg {\n height: 2rem;\n width: auto;\n}\n.TopBar-module_topBar__8pC4I > .TopBar-module_navigation__tu3E0 > .TopBar-module_items__wJ47Z {\n margin: 0;\n padding: 0;\n list-style: none;\n display: flex;\n align-items: flex-end;\n gap: 2rem;\n flex-grow: 1;\n overflow-x: auto;\n}\n.TopBar-module_topBar__8pC4I > .TopBar-module_navigation__tu3E0 > .TopBar-module_items__wJ47Z .TopBar-module_item__ConzY {\n max-width: 12rem;\n color: #002559;\n}\n.TopBar-module_topBar__8pC4I > .TopBar-module_navigation__tu3E0 > .TopBar-module_items__wJ47Z .TopBar-module_item__ConzY .TopBar-module_link__eBkGp {\n padding: 0.75rem 0.375rem;\n display: block;\n background-color: #FFFFFF;\n line-height: 0.875rem;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n position: relative;\n}\n.TopBar-module_topBar__8pC4I > .TopBar-module_navigation__tu3E0 > .TopBar-module_items__wJ47Z .TopBar-module_item__ConzY .TopBar-module_link__eBkGp .TopBar-module_firstWord__rq5Md {\n font-family: PollyBold;\n font-size: 1rem;\n line-height: 1.125rem;\n letter-spacing: 0.02em;\n text-transform: uppercase;\n}\n.TopBar-module_topBar__8pC4I > .TopBar-module_navigation__tu3E0 > .TopBar-module_items__wJ47Z .TopBar-module_item__ConzY .TopBar-module_link__eBkGp::after {\n content: \"\";\n position: absolute;\n z-index: 99999;\n background-color: #002559;\n width: 100%;\n height: 3px;\n border-radius: 1px;\n bottom: 0;\n left: 0;\n right: 0;\n transform-origin: 100% 0;\n transform: scaleX(0);\n transition: transform 0.4s;\n}\n.TopBar-module_topBar__8pC4I > .TopBar-module_navigation__tu3E0 > .TopBar-module_items__wJ47Z .TopBar-module_item__ConzY .TopBar-module_link__eBkGp:hover::after {\n transform-origin: 0 0;\n transform: scaleX(1);\n}\n.TopBar-module_topBar__8pC4I > .TopBar-module_navigation__tu3E0 > .TopBar-module_items__wJ47Z .TopBar-module_item__ConzY .TopBar-module_link__eBkGp.TopBar-module_active__095JY {\n pointer-events: none;\n}\n.TopBar-module_topBar__8pC4I > .TopBar-module_navigation__tu3E0 > .TopBar-module_items__wJ47Z .TopBar-module_item__ConzY .TopBar-module_link__eBkGp.TopBar-module_active__095JY::after {\n transform: scaleX(1);\n}\n.TopBar-module_topBar__8pC4I > .TopBar-module_rightSide__rDWyd {\n display: flex;\n gap: 1rem;\n align-items: center;\n}\n.TopBar-module_topBar__8pC4I > .TopBar-module_rightSide__rDWyd > .TopBar-module_showNotificationsButton__Dli-w {\n padding: 0;\n margin: 0;\n cursor: pointer;\n background: transparent;\n appearance: none;\n border: 0 solid transparent;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n.TopBar-module_topBar__8pC4I > .TopBar-module_rightSide__rDWyd > .TopBar-module_showNotificationsButton__Dli-w svg {\n fill: #002559;\n}\n.TopBar-module_topBar__8pC4I::after {\n content: \"\";\n position: absolute;\n z-index: 10;\n inset: 0;\n pointer-events: none;\n box-shadow: 0px 0.25rem 0.5rem rgba(0, 0, 0, 0.1);\n}";
var styles$6 = {"notification":"TopBar-module_notification__UOEFZ","label":"TopBar-module_label__2AtYu","unread":"TopBar-module_unread__K-drX","topBar":"TopBar-module_topBar__8pC4I","navigation":"TopBar-module_navigation__tu3E0","homeLink":"TopBar-module_homeLink__hehft","items":"TopBar-module_items__wJ47Z","item":"TopBar-module_item__ConzY","link":"TopBar-module_link__eBkGp","firstWord":"TopBar-module_firstWord__rq5Md","active":"TopBar-module_active__095JY","rightSide":"TopBar-module_rightSide__rDWyd","showNotificationsButton":"TopBar-module_showNotificationsButton__Dli-w"};
styleInject(css_248z$6);
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _setPrototypeOf$1(o, p) {
_setPrototypeOf$1 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf$1(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf$1(subClass, superClass);
}
function _getPrototypeOf$1(o) {
_getPrototypeOf$1 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf$1(o);
}
function _isNativeReflectConstruct$1() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof$1(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct$1();
return function _createSuperInternal() {
var Super = _getPrototypeOf$1(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf$1(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function toArray$1(children) {
var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var ret = [];
React__default.Children.forEach(children, function (child) {
if ((child === undefined || child === null) && !option.keepEmpty) {
return;
}
if (Array.isArray(child)) {
ret = ret.concat(toArray$1(child));
} else if (reactIsExports.isFragment(child) && child.props) {
ret = ret.concat(toArray$1(child.props.children, option));
} else {
ret.push(child);
}
});
return ret;
}
function isDOM(node) {
// https://developer.mozilla.org/en-US/docs/Web/API/Element
// Since XULElement is also subclass of Element, we only need HTMLElement and SVGElement
return node instanceof HTMLElement || node instanceof SVGElement;
}
/**
* Return if a node is a DOM node. Else will return by `findDOMNode`
*/
function findDOMNode(node) {
if (isDOM(node)) {
return node;
}
if (node instanceof React__default.Component) {
return ReactDOM.findDOMNode(node);
}
return null;
}
var CollectionContext = /*#__PURE__*/React.createContext(null);
/**
* Collect all the resize event from children ResizeObserver
*/
function Collection(_ref) {
var children = _ref.children,
onBatchResize = _ref.onBatchResize;
var resizeIdRef = React.useRef(0);
var resizeInfosRef = React.useRef([]);
var onCollectionResize = React.useContext(CollectionContext);
var onResize = React.useCallback(function (size, element, data) {
resizeIdRef.current += 1;
var currentId = resizeIdRef.current;
resizeInfosRef.current.push({
size: size,
element: element,
data: data
});
Promise.resolve().then(function () {
if (currentId === resizeIdRef.current) {
onBatchResize === null || onBatchResize === void 0 || onBatchResize(resizeInfosRef.current);
resizeInfosRef.current = [];
}
});
// Continue bubbling if parent exist
onCollectionResize === null || onCollectionResize === void 0 || onCollectionResize(size, element, data);
}, [onBatchResize, onCollectionResize]);
return /*#__PURE__*/React.createElement(CollectionContext.Provider, {
value: onResize
}, children);
}
/**
* A collection of shims that provide minimal functionality of the ES6 collections.
*
* These implementations are not meant to be used outside of the ResizeObserver
* modules as they cover only a limited range of use cases.
*/
/* eslint-disable require-jsdoc, valid-jsdoc */
var MapShim = function () {
if (typeof Map !== 'undefined') {
return Map;
}
/**
* Returns index in provided array that matches the specified key.
*
* @param {Array<Array>} arr
* @param {*} key
* @returns {number}
*/
function getIndex(arr, key) {
var result = -1;
arr.some(function (entry, index) {
if (entry[0] === key) {
result = index;
return true;
}
return false;
});
return result;
}
return /** @class */function () {
function class_1() {
this.__entries__ = [];
}
Object.defineProperty(class_1.prototype, "size", {
/**
* @returns {boolean}
*/
get: function () {
return this.__entries__.length;
},
enumerable: true,
configurable: true
});
/**
* @param {*} key
* @returns {*}
*/
class_1.prototype.get = function (key) {
var index = getIndex(this.__entries__, key);
var entry = this.__entries__[index];
return entry && entry[1];
};
/**
* @param {*} key
* @param {*} value
* @returns {void}
*/
class_1.prototype.set = function (key, value) {
var index = getIndex(this.__entries__, key);
if (~index) {
this.__entries__[index][1] = value;
} else {
this.__entries__.push([key, value]);
}
};
/**
* @param {*} key
* @returns {void}
*/
class_1.prototype.delete = function (key) {
var entries = this.__entries__;
var index = getIndex(entries, key);
if (~index) {
entries.splice(index, 1);
}
};
/**
* @param {*} key
* @returns {void}
*/
class_1.prototype.has = function (key) {
return !!~getIndex(this.__entries__, key);
};
/**
* @returns {void}
*/
class_1.prototype.clear = function () {
this.__entries__.splice(0);
};
/**
* @param {Function} callback
* @param {*} [ctx=null]
* @returns {void}
*/
class_1.prototype.forEach = function (callback, ctx) {
if (ctx === void 0) {
ctx = null;
}
for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) {
var entry = _a[_i];
callback.call(ctx, entry[1], entry[0]);
}
};
return class_1;
}();
}();
/**
* Detects whether window and document objects are available in current environment.
*/
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document;
// Returns global object of a current environment.
var global$1 = function () {
if (typeof global !== 'undefined' && global.Math === Math) {
return global;
}
if (typeof self !== 'undefined' && self.Math === Math) {
return self;
}
if (typeof window !== 'undefined' && window.Math === Math) {
return window;
}
// eslint-disable-next-line no-new-func
return Function('return this')();
}();
/**
* A shim for the requestAnimationFrame which falls back to the setTimeout if
* first one is not supported.
*
* @returns {number} Requests' identifier.
*/
var requestAnimationFrame$1 = function () {
if (typeof requestAnimationFrame === 'function') {
// It's required to use a bounded function because IE sometimes throws
// an "Invalid calling object" error if rAF is invoked without the global
// object on the left hand side.
return requestAnimationFrame.bind(global$1);
}
return function (callback) {
return setTimeout(function () {
return callback(Date.now());
}, 1000 / 60);
};
}();
// Defines minimum timeout before adding a trailing call.
var trailingTimeout = 2;
/**
* Creates a wrapper function which ensures that provided callback will be
* invoked only once during the specified delay period.
*
* @param {Function} callback - Function to be invoked after the delay period.
* @param {number} delay - Delay after which to invoke callback.
* @returns {Function}
*/
function throttle(callback, delay) {
var leadingCall = false,
trailingCall = false,
lastCallTime = 0;
/**
* Invokes the original callback function and schedules new invocation if
* the "proxy" was called during current request.
*
* @returns {void}
*/
function resolvePending() {
if (leadingCall) {
leadingCall = false;
callback();
}
if (trailingCall) {
proxy();
}
}
/**
* Callback invoked after the specified delay. It will further postpone
* invocation of the original function delegating it to the
* requestAnimationFrame.
*
* @returns {void}
*/
function timeoutCallback() {
requestAnimationFrame$1(resolvePending);
}
/**
* Schedules invocation of the original function.
*
* @returns {void}
*/
function proxy() {
var timeStamp = Date.now();
if (leadingCall) {
// Reject immediately following calls.
if (timeStamp - lastCallTime < trailingTimeout) {
return;
}
// Schedule new call to be in invoked when the pending one is resolved.
// This is important for "transitions" which never actually start
// immediately so there is a chance that we might miss one if change
// happens amids the pending invocation.
trailingCall = true;
} else {
leadingCall = true;
trailingCall = false;
setTimeout(timeoutCallback, delay);
}
lastCallTime = timeStamp;
}
return proxy;
}
// Minimum delay before invoking the update of observers.
var REFRESH_DELAY = 20;
// A list of substrings of CSS properties used to find transition events that
// might affect dimensions of observed elements.
var transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight'];
// Check if MutationObserver is available.
var mutationObserverSupported = typeof MutationObserver !== 'undefined';
/**
* Singleton controller class which handles updates of ResizeObserver instances.
*/
var ResizeObserverController = /** @class */function () {
/**
* Creates a new instance of ResizeObserverController.
*
* @private
*/
function ResizeObserverController() {
/**
* Indicates whether DOM listeners have been added.
*
* @private {boolean}
*/
this.connected_ = false;
/**
* Tells that controller has subscribed for Mutation Events.
*
* @private {boolean}
*/
this.mutationEventsAdded_ = false;
/**
* Keeps reference to the instance of MutationObserver.
*
* @private {MutationObserver}
*/
this.mutationsObserver_ = null;
/**
* A list of connected observers.
*
* @private {Array<ResizeObserverSPI>}
*/
this.observers_ = [];
this.onTransitionEnd_ = this.onTransitionEnd_.bind(this);
this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY);
}
/**
* Adds observer to observers list.
*
* @param {ResizeObserverSPI} observer - Observer to be added.
* @returns {void}
*/
ResizeObserverController.prototype.addObserver = function (observer) {
if (!~this.observers_.indexOf(observer)) {
this.observers_.push(observer);
}
// Add listeners if they haven't been added yet.
if (!this.connected_) {
this.connect_();
}
};
/**
* Removes observer from observers list.
*
* @param {ResizeObserverSPI} observer - Observer to be removed.
* @returns {void}
*/
ResizeObserverController.prototype.removeObserver = function (observer) {
var observers = this.observers_;
var index = observers.indexOf(observer);
// Remove observer if it's present in registry.
if (~index) {
observers.splice(index, 1);
}
// Remove listeners if controller has no connected observers.
if (!observers.length && this.connected_) {
this.disconnect_();
}
};
/**
* Invokes the update of observers. It will continue running updates insofar
* it detects changes.
*
* @returns {void}
*/
ResizeObserverController.prototype.refresh = function () {
var changesDetected = this.updateObservers_();
// Continue running updates if changes have been detected as there might
// be future ones caused by CSS transitions.
if (changesDetected) {
this.refresh();
}
};
/**
* Updates every observer from observers list and notifies them of queued
* entries.
*
* @private
* @returns {boolean} Returns "true" if any observer has detected changes in
* dimensions of it's elements.
*/
ResizeObserverController.prototype.updateObservers_ = function () {
// Collect observers that have active observations.
var activeObservers = this.observers_.filter(function (observer) {
return observer.gatherActive(), observer.hasActive();
});
// Deliver notifications in a separate cycle in order to avoid any
// collisions between observers, e.g. when multiple instances of
// ResizeObserver are tracking the same element and the callback of one
// of them changes content dimensions of the observed target. Sometimes
// this may result in notifications being blocked for the rest of observers.
activeObservers.forEach(function (observer) {
return observer.broadcastActive();
});
return activeObservers.length > 0;
};
/**
* Initializes DOM listeners.
*
* @private
* @returns {void}
*/
ResizeObserverController.prototype.connect_ = function () {
// Do nothing if running in a non-browser environment or if listeners
// have been already added.
if (!isBrowser || this.connected_) {
return;
}
// Subscription to the "Transitionend" event is used as a workaround for
// delayed transitions. This way it's possible to capture at least the
// final state of an element.
document.addEventListener('transitionend', this.onTransitionEnd_);
window.addEventListener('resize', this.refresh);
if (mutationObserverSupported) {
this.mutationsObserver_ = new MutationObserver(this.refresh);
this.mutationsObserver_.observe(document, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
} else {
document.addEventListener('DOMSubtreeModified', this.refresh);
this.mutationEventsAdded_ = true;
}
this.connected_ = true;
};
/**
* Removes DOM listeners.
*
* @private
* @returns {void}
*/
ResizeObserverController.prototype.disconnect_ = function () {
// Do nothing if running in a non-browser environment or if listeners
// have been already removed.
if (!isBrowser || !this.connected_) {
return;
}
document.removeEventListener('transitionend', this.onTransitionEnd_);
window.removeEventListener('resize', this.refresh);
if (this.mutationsObserver_) {
this.mutationsObserver_.disconnect();
}
if (this.mutationEventsAdded_) {
document.removeEventListener('DOMSubtreeModified', this.refresh);
}
this.mutationsObserver_ = null;
this.mutationEventsAdded_ = false;
this.connected_ = false;
};
/**
* "Transitionend" event handler.
*
* @private
* @param {TransitionEvent} event
* @returns {void}
*/
ResizeObserverController.prototype.onTransitionEnd_ = function (_a) {
var _b = _a.propertyName,
propertyName = _b === void 0 ? '' : _b;
// Detect whether transition may affect dimensions of an element.
var isReflowProperty = transitionKeys.some(function (key) {
return !!~propertyName.indexOf(key);
});
if (isReflowProperty) {
this.refresh();
}
};
/**
* Returns instance of the ResizeObserverController.
*
* @returns {ResizeObserverController}
*/
ResizeObserverController.getInstance = function () {
if (!this.instance_) {
this.instance_ = new ResizeObserverController();
}
return this.instance_;
};
/**
* Holds reference to the controller's instance.
*
* @private {ResizeObserverController}
*/
ResizeObserverController.instance_ = null;
return ResizeObserverController;
}();
/**
* Defines non-writable/enumerable properties of the provided target object.
*
* @param {Object} target - Object for which to define properties.
* @param {Object} props - Properties to be defined.
* @returns {Object} Target object.
*/
var defineConfigurable = function (target, props) {
for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {
var key = _a[_i];
Object.defineProperty(target, key, {
value: props[key],
enumerable: false,
writable: false,
configurable: true
});
}
return target;
};
/**
* Returns the global object associated with provided element.
*
* @param {Object} target
* @returns {Object}
*/
var getWindowOf = function (target) {
// Assume that the element is an instance of Node, which means that it
// has the "ownerDocument" property from which we can retrieve a
// corresponding global object.
var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView;
// Return the local global object if it's not possible extract one from
// provided element.
return ownerGlobal || global$1;
};
// Placeholder of an empty content rectangle.
var emptyRect = createRectInit(0, 0, 0, 0);
/**
* Converts provided string to a number.
*
* @param {number|string} value
* @returns {number}
*/
function toFloat(value) {
return parseFloat(value) || 0;
}
/**
* Extracts borders size from provided styles.
*
* @param {CSSStyleDeclaration} styles
* @param {...string} positions - Borders positions (top, right, ...)
* @returns {number}
*/
function getBordersSize(styles) {
var positions = [];
for (var _i = 1; _i < arguments.length; _i++) {
positions[_i - 1] = arguments[_i];
}
return positions.reduce(function (size, position) {
var value = styles['border-' + position + '-width'];
return size + toFloat(value);
}, 0);
}
/**
* Extracts paddings sizes from provided styles.
*
* @param {CSSStyleDeclaration} styles
* @returns {Object} Paddings box.
*/
function getPaddings(styles) {
var positions = ['top', 'right', 'bottom', 'left'];
var paddings = {};
for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {
var position = positions_1[_i];
var value = styles['padding-' + position];
paddings[position] = toFloat(value);
}
return paddings;
}
/**
* Calculates content rectangle of provided SVG element.
*
* @param {SVGGraphicsElement} target - Element content rectangle of which needs
* to be calculated.
* @returns {DOMRectInit}
*/
function getSVGContentRect(target) {
var bbox = target.getBBox();
return createRectInit(0, 0, bbox.width, bbox.height);
}
/**
* Calculates content rectangle of provided HTMLElement.
*
* @param {HTMLElement} target - Element for which to calculate the content rectangle.
* @returns {DOMRectInit}
*/
function getHTMLElementContentRect(target) {
// Client width & height properties can't be
// used exclusively as they provide rounded values.
var clientWidth = target.clientWidth,
clientHeight = target.clientHeight;
// By this condition we can catch all non-replaced inline, hidden and
// detached elements. Though elements with width & height properties less
// than 0.5 will be discarded as well.
//
// Without it we would need to implement separate methods for each of
// those cases and it's not possible to perform a precise and performance
// effective test for hidden elements. E.g. even jQuery's ':visible' filter
// gives wrong results for elements with width & height less than 0.5.
if (!clientWidth && !clientHeight) {
return emptyRect;
}
var styles = getWindowOf(target).getComputedStyle(target);
var paddings = getPaddings(styles);
var horizPad = paddings.left + paddings.right;
var vertPad = paddings.top + paddings.bottom;
// Computed styles of width & height are being used because they are the
// only dimensions available to JS that contain non-rounded values. It could
// be possible to utilize the getBoundingClientRect if only it's data wasn't
// affected by CSS transformations let alone paddings, borders and scroll bars.
var width = toFloat(styles.width),
height = toFloat(styles.height);
// Width & height include paddings and borders when the 'border-box' box
// model is applied (except for IE).
if (styles.boxSizing === 'border-box') {
// Following conditions are required to handle Internet Explorer which
// doesn't include paddings and borders to computed CSS dimensions.
//
// We can say that if CSS dimensions + paddings are equal to the "client"
// properties then it's either IE, and thus we don't need to subtract
// anything, or an element merely doesn't have paddings/borders styles.
if (Math.round(width + horizPad) !== clientWidth) {
width -= getBordersSize(styles, 'left', 'right') + horizPad;
}
if (Math.round(height + vertPad) !== clientHeight) {
height -= getBordersSize(styles, 'top', 'bottom') + vertPad;
}
}
// Following steps can't be applied to the document's root element as its
// client[Width/Height] properties represent viewport area of the window.
// Besides, it's as well not necessary as the <html> itself neither has
// rendered scroll bars nor it can be clipped.
if (!isDocumentElement(target)) {
// In some browsers (only in Firefox, actually) CSS width & height
// include scroll bars size which can be removed at this step as scroll
// bars are the only difference between rounded dimensions + paddings
// and "client" properties, though that is not always true in Chrome.
var vertScrollbar = Math.round(width + horizPad) - clientWidth;
var horizScrollbar = Math.round(height + vertPad) - clientHeight;
// Chrome has a rather weird rounding of "client" properties.
// E.g. for an element with content width of 314.2px it sometimes gives
// the client width of 315px and for the width of 314.7px it may give
// 314px. And it doesn't happen all the time. So just ignore this delta
// as a non-relevant.
if (Math.abs(vertScrollbar) !== 1) {
width -= vertScrollbar;
}
if (Math.abs(horizScrollbar) !== 1) {
height -= horizScrollbar;
}
}
return createRectInit(paddings.left, paddings.top, width, height);
}
/**
* Checks whether provided element is an instance of the SVGGraphicsElement.
*
* @param {Element} target - Element to be checked.
* @returns {boolean}
*/
var isSVGGraphicsElement = function () {
// Some browsers, namely IE and Edge, don't have the SVGGraphicsElement
// interface.
if (typeof SVGGraphicsElement !== 'undefined') {
return function (target) {
return target instanceof getWindowOf(target).SVGGraphicsElement;
};
}
// If it's so, then check that element is at least an instance of the
// SVGElement and that it has the "getBBox" method.
// eslint-disable-next-line no-extra-parens
return function (target) {
return target instanceof getWindowOf(target).SVGElement && typeof target.getBBox === 'function';
};
}();
/**
* Checks whether provided element is a document element (<html>).
*
* @param {Element} target - Element to be checked.
* @returns {boolean}
*/
function isDocumentElement(target) {
return target === getWindowOf(target).document.documentElement;
}
/**
* Calculates an appropriate content rectangle for provided html or svg element.
*
* @param {Element} target - Element content rectangle of which needs to be calculated.
* @returns {DOMRectInit}
*/
function getContentRect(target) {
if (!isBrowser) {
return emptyRect;
}
if (isSVGGraphicsElement(target)) {
return getSVGContentRect(target);
}
return getHTMLElementContentRect(target);
}
/**
* Creates rectangle with an interface of the DOMRectReadOnly.
* Spec: https://drafts.fxtf.org/geometry/#domrectreadonly
*
* @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions.
* @returns {DOMRectReadOnly}
*/
function createReadOnlyRect(_a) {
var x = _a.x,
y = _a.y,
width = _a.width,
height = _a.height;
// If DOMRectReadOnly is available use it as a prototype for the rectangle.
var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object;
var rect = Object.create(Constr.prototype);
// Rectangle's properties are not writable and non-enumerable.
defineConfigurable(rect, {
x: x,
y: y,
width: width,
height: height,
top: y,
right: x + width,
bottom: height + y,
left: x
});
return rect;
}
/**
* Creates DOMRectInit object based on the provided dimensions and the x/y coordinates.
* Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit
*
* @param {number} x - X coordinate.
* @param {number} y - Y coordinate.
* @param {number} width - Rectangle's width.
* @param {number} height - Rectangle's height.
* @returns {DOMRectInit}
*/
function createRectInit(x, y, width, height) {
return {
x: x,
y: y,
width: width,
height: height
};
}
/**
* Class that is responsible for computations of the content rectangle of
* provided DOM element and for keeping track of it's changes.
*/
var ResizeObservation = /** @class */function () {
/**
* Creates an instance of ResizeObservation.
*
* @param {Element} target - Element to be observed.
*/
function ResizeObservation(target) {
/**
* Broadcasted width of content rectangle.
*
* @type {number}
*/
this.broadcastWidth = 0;
/**
* Broadcasted height of content rectangle.
*
* @type {number}
*/
this.broadcastHeight = 0;
/**
* Reference to the last observed content rectangle.
*
* @private {DOMRectInit}
*/
this.contentRect_ = createRectInit(0, 0, 0, 0);
this.target = target;
}
/**
* Updates content rectangle and tells whether it's width or height properties
* have changed since the last broadcast.
*
* @returns {boolean}
*/
ResizeObservation.prototype.isActive = function () {
var rect = getContentRect(this.target);
this.contentRect_ = rect;
return rect.width !== this.broadcastWidth || rect.height !== this.broadcastHeight;
};
/**
* Updates 'broadcastWidth' and 'broadcastHeight' properties with a data
* from the corresponding properties of the last observed content rectangle.
*
* @returns {DOMRectInit} Last observed content rectangle.
*/
ResizeObservation.prototype.broadcastRect = function () {
var rect = this.contentRect_;
this.broadcastWidth = rect.width;
this.broadcastHeight = rect.height;
return rect;
};
return ResizeObservation;
}();
var ResizeObserverEntry = /** @class */function () {
/**
* Creates an instance of ResizeObserverEntry.
*
* @param {Element} target - Element that is being observed.
* @param {DOMRectInit} rectInit - Data of the element's content rectangle.
*/
function ResizeObserverEntry(target, rectInit) {
var contentRect = createReadOnlyRect(rectInit);
// According to the specification following properties are not writable
// and are also not enumerable in the native implementation.
//
// Property accessors are not being used as they'd require to define a
// private WeakMap storage which may cause memory leaks in browsers that
// don't support this type of collections.
defineConfigurable(this, {
target: target,
contentRect: contentRect
});
}
return ResizeObserverEntry;
}();
var ResizeObserverSPI = /** @class */function () {
/**
* Creates a new instance of ResizeObserver.
*
* @param {ResizeObserverCallback} callback - Callback function that is invoked
* when one of the observed elements changes it's content dimensions.
* @param {ResizeObserverController} controller - Controller instance which
* is responsible for the updates of observer.
* @param {ResizeObserver} callbackCtx - Reference to the public
* ResizeObserver instance which will be passed to callback function.
*/
function ResizeObserverSPI(callback, controller, callbackCtx) {
/**
* Collection of resize observations that have detected changes in dimensions
* of elements.
*
* @private {Array<ResizeObservation>}
*/
this.activeObservations_ = [];
/**
* Registry of the ResizeObservation instances.
*
* @private {Map<Element, ResizeObservation>}
*/
this.observations_ = new MapShim();
if (typeof callback !== 'function') {
throw new TypeError('The callback provided as parameter 1 is not a function.');
}
this.callback_ = callback;
this.controller_ = controller;
this.callbackCtx_ = callbackCtx;
}
/**
* Starts observing provided element.
*
* @param {Element} target - Element to be observed.
* @returns {void}
*/
ResizeObserverSPI.prototype.observe = function (target) {
if (!arguments.length) {
throw new TypeError('1 argument required, but only 0 present.');
}
// Do nothing if current environment doesn't have the Element interface.
if (typeof Element === 'undefined' || !(Element instanceof Object)) {
return;
}
if (!(target instanceof getWindowOf(target).Element)) {
throw new TypeError('parameter 1 is not of type "Element".');
}
var observations = this.observations_;
// Do nothing if element is already being observed.
if (observations.has(target)) {
return;
}
observations.set(target, new ResizeObservation(target));
this.controller_.addObserver(this);
// Force the update of observations.
this.controller_.refresh();
};
/**
* Stops observing provided element.
*
* @param {Element} target - Element to stop observing.
* @returns {void}
*/
ResizeObserverSPI.prototype.unobserve = function (target) {
if (!arguments.length) {
throw new TypeError('1 argument required, but only 0 present.');
}
// Do nothing if current environment doesn't have the Element interface.
if (typeof Element === 'undefined' || !(Element instanceof Object)) {
return;
}
if (!(target instanceof getWindowOf(target).Element)) {
throw new TypeError('parameter 1 is not of type "Element".');
}
var observations = this.observations_;
// Do nothing if element is not being observed.
if (!observations.has(target)) {
return;
}
observations.delete(target);
if (!observations.size) {
this.controller_.removeObserver(this);
}
};
/**
* Stops observing all elements.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.disconnect = function () {
this.clearActive();
this.observations_.clear();
this.controller_.removeObserver(this);
};
/**
* Collects observation instances the associated element of which has changed
* it's content rectangle.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.gatherActive = function () {
var _this = this;
this.clearActive();
this.observations_.forEach(function (observation) {
if (observation.isActive()) {
_this.activeObservations_.push(observation);
}
});
};
/**
* Invokes initial callback function with a list of ResizeObserverEntry
* instances collected from active resize observations.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.broadcastActive = function () {
// Do nothing if observer doesn't have active observations.
if (!this.hasActive()) {
return;
}
var ctx = this.callbackCtx_;
// Create ResizeObserverEntry instance for every active observation.
var entries = this.activeObservations_.map(function (observation) {
return new ResizeObserverEntry(observation.target, observation.broadcastRect());
});
this.callback_.call(ctx, entries, ctx);
this.clearActive();
};
/**
* Clears the collection of active observations.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.clearActive = function () {
this.activeObservations_.splice(0);
};
/**
* Tells whether observer has active observations.
*
* @returns {boolean}
*/
ResizeObserverSPI.prototype.hasActive = function () {
return this.activeObservations_.length > 0;
};
return ResizeObserverSPI;
}();
// Registry of internal observers. If WeakMap is not available use current shim
// for the Map collection as it has all required methods and because WeakMap
// can't be fully polyfilled anyway.
var observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim();
/**
* ResizeObserver API. Encapsulates the ResizeObserver SPI implementation
* exposing only those methods and properties that are defined in the spec.
*/
var ResizeObserver$2 = /** @class */function () {
/**
* Creates a new instance of ResizeObserver.
*
* @param {ResizeObserverCallback} callback - Callback that is invoked when
* dimensions of the observed elements change.
*/
function ResizeObserver(callback) {
if (!(this instanceof ResizeObserver)) {
throw new TypeError('Cannot call a class as a function.');
}
if (!arguments.length) {
throw new TypeError('1 argument required, but only 0 present.');
}
var controller = ResizeObserverController.getInstance();
var observer = new ResizeObserverSPI(callback, controller, this);
observers.set(this, observer);
}
return ResizeObserver;
}();
// Expose public methods of ResizeObserver.
['observe', 'unobserve', 'disconnect'].forEach(function (method) {
ResizeObserver$2.prototype[method] = function () {
var _a;
return (_a = observers.get(this))[method].apply(_a, arguments);
};
});
var index = function () {
// Export existing implementation if available.
if (typeof global$1.ResizeObserver !== 'undefined') {
return global$1.ResizeObserver;
}
return ResizeObserver$2;
}();
// =============================== Const ===============================
var elementListeners = new Map();
function onResize(entities) {
entities.forEach(function (entity) {
var _elementListeners$get;
var target = entity.target;
(_elementListeners$get = elementListeners.get(target)) === null || _elementListeners$get === void 0 || _elementListeners$get.forEach(function (listener) {
return listener(target);
});
});
}
// Note: ResizeObserver polyfill not support option to measure border-box resize
var resizeObserver = new index(onResize);
// Dev env only
process.env.NODE_ENV !== 'production' ? elementListeners : null; // eslint-disable-line
process.env.NODE_ENV !== 'production' ? onResize : null; // eslint-disable-line
// ============================== Observe ==============================
function observe(element, callback) {
if (!elementListeners.has(element)) {
elementListeners.set(element, new Set());
resizeObserver.observe(element);
}
elementListeners.get(element).add(callback);
}
function unobserve(element, callback) {
if (elementListeners.has(element)) {
elementListeners.get(element).delete(callback);
if (!elementListeners.get(element).size) {
resizeObserver.unobserve(element);
elementListeners.delete(element);
}
}
}
/**
* Fallback to findDOMNode if origin ref do not provide any dom element
*/
var DomWrapper$1 = /*#__PURE__*/function (_React$Component) {
_inherits(DomWrapper, _React$Component);
var _super = _createSuper(DomWrapper);
function DomWrapper() {
_classCallCheck(this, DomWrapper);
return _super.apply(this, arguments);
}
_createClass(DomWrapper, [{
key: "render",
value: function render() {
return this.props.children;
}
}]);
return DomWrapper;
}(React.Component);
function SingleObserver(props, ref) {
var children = props.children,
disabled = props.disabled;
var elementRef = React.useRef(null);
var wrapperRef = React.useRef(null);
var onCollectionResize = React.useContext(CollectionContext);
// =========================== Children ===========================
var isRenderProps = typeof children === 'function';
var mergedChildren = isRenderProps ? children(elementRef) : children;
// ============================= Size =============================
var sizeRef = React.useRef({
width: -1,
height: -1,
offsetWidth: -1,
offsetHeight: -1
});
// ============================= Ref ==============================
var canRef = !isRenderProps && /*#__PURE__*/React.isValidElement(mergedChildren) && supportRef(mergedChildren);
var originRef = canRef ? mergedChildren.ref : null;
var mergedRef = useComposeRef(originRef, elementRef);
var getDom = function getDom() {
var _elementRef$current;
return findDOMNode(elementRef.current) || (
// Support `nativeElement` format
elementRef.current && _typeof$1(elementRef.current) === 'object' ? findDOMNode((_elementRef$current = elementRef.current) === null || _elementRef$current === void 0 ? void 0 : _elementRef$current.nativeElement) : null) || findDOMNode(wrapperRef.current);
};
React.useImperativeHandle(ref, function () {
return getDom();
});
// =========================== Observe ============================
var propsRef = React.useRef(props);
propsRef.current = props;
// Handler
var onInternalResize = React.useCallback(function (target) {
var _propsRef$current = propsRef.current,
onResize = _propsRef$current.onResize,
data = _propsRef$current.data;
var _target$getBoundingCl = target.getBoundingClientRect(),
width = _target$getBoundingCl.width,
height = _target$getBoundingCl.height;
var offsetWidth = target.offsetWidth,
offsetHeight = target.offsetHeight;
/**
* Resize observer trigger when content size changed.
* In most case we just care about element size,
* let's use `boundary` instead of `contentRect` here to avoid shaking.
*/
var fixedWidth = Math.floor(width);
var fixedHeight = Math.floor(height);
if (sizeRef.current.width !== fixedWidth || sizeRef.current.height !== fixedHeight || sizeRef.current.offsetWidth !== offsetWidth || sizeRef.current.offsetHeight !== offsetHeight) {
var size = {
width: fixedWidth,
height: fixedHeight,
offsetWidth: offsetWidth,
offsetHeight: offsetHeight
};
sizeRef.current = size;
// IE is strange, right?
var mergedOffsetWidth = offsetWidth === Math.round(width) ? width : offsetWidth;
var mergedOffsetHeight = offsetHeight === Math.round(height) ? height : offsetHeight;
var sizeInfo = _objectSpread2$1(_objectSpread2$1({}, size), {}, {
offsetWidth: mergedOffsetWidth,
offsetHeight: mergedOffsetHeight
});
// Let collection know what happened
onCollectionResize === null || onCollectionResize === void 0 || onCollectionResize(sizeInfo, target, data);
if (onResize) {
// defer the callback but not defer to next frame
Promise.resolve().then(function () {
onResize(sizeInfo, target);
});
}
}
}, []);
// Dynamic observe
React.useEffect(function () {
var currentElement = getDom();
if (currentElement && !disabled) {
observe(currentElement, onInternalResize);
}
return function () {
return unobserve(currentElement, onInternalResize);
};
}, [elementRef.current, disabled]);
// ============================ Render ============================
return /*#__PURE__*/React.createElement(DomWrapper$1, {
ref: wrapperRef
}, canRef ? /*#__PURE__*/React.cloneElement(mergedChildren, {
ref: mergedRef
}) : mergedChildren);
}
var RefSingleObserver = /*#__PURE__*/React.forwardRef(SingleObserver);
if (process.env.NODE_ENV !== 'production') {
RefSingleObserver.displayName = 'SingleObserver';
}
var INTERNAL_PREFIX_KEY = 'rc-observer-key';
function ResizeObserver$1(props, ref) {
var children = props.children;
var childNodes = typeof children === 'function' ? [children] : toArray$1(children);
if (process.env.NODE_ENV !== 'production') {
if (childNodes.length > 1) {
warning$5(false, 'Find more than one child node with `children` in ResizeObserver. Please use ResizeObserver.Collection instead.');
} else if (childNodes.length === 0) {
warning$5(false, '`children` of ResizeObserver is empty. Nothing is in observe.');
}
}
return childNodes.map(function (child, index) {
var key = (child === null || child === void 0 ? void 0 : child.key) || "".concat(INTERNAL_PREFIX_KEY, "-").concat(index);
return /*#__PURE__*/React.createElement(RefSingleObserver, _extends$1({}, props, {
key: key,
ref: index === 0 ? ref : undefined
}), child);
});
}
var RefResizeObserver = /*#__PURE__*/React.forwardRef(ResizeObserver$1);
if (process.env.NODE_ENV !== 'production') {
RefResizeObserver.displayName = 'ResizeObserver';
}
RefResizeObserver.Collection = Collection;
function omit(obj, fields) {
var clone = _objectSpread2$1({}, obj);
if (Array.isArray(fields)) {
fields.forEach(function (key) {
delete clone[key];
});
}
return clone;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
/* eslint-disable */
// Inspired by https://github.com/garycourt/murmurhash-js
// Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86
function murmur2(str) {
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
// const m = 0x5bd1e995;
// const r = 24;
// Initialize the hash
var h = 0; // Mix 4 bytes at a time into the hash
var k,
i = 0,
len = str.length;
for (; len >= 4; ++i, len -= 4) {
k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;
k = /* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16);
k ^= /* k >>> r: */
k >>> 24;
h = /* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^ /* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
} // Handle the last few bytes of the input array
switch (len) {
case 3:
h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
case 2:
h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
case 1:
h ^= str.charCodeAt(i) & 0xff;
h = /* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
} // Do a few final mixes of the hash to ensure the last few
// bytes are well-incorporated.
h ^= h >>> 13;
h = /* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
return ((h ^ h >>> 15) >>> 0).toString(36);
}
/**
* Deeply compares two object literals.
* @param obj1 object 1
* @param obj2 object 2
* @param shallow shallow compare
* @returns
*/
function isEqual(obj1, obj2) {
var shallow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
// https://github.com/mapbox/mapbox-gl-js/pull/5979/files#diff-fde7145050c47cc3a306856efd5f9c3016e86e859de9afbd02c879be5067e58f
var refSet = new Set();
function deepEqual(a, b) {
var level = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
var circular = refSet.has(a);
warningOnce(!circular, 'Warning: There may be circular references');
if (circular) {
return false;
}
if (a === b) {
return true;
}
if (shallow && level > 1) {
return false;
}
refSet.add(a);
var newLevel = level + 1;
if (Array.isArray(a)) {
if (!Array.isArray(b) || a.length !== b.length) {
return false;
}
for (var i = 0; i < a.length; i++) {
if (!deepEqual(a[i], b[i], newLevel)) {
return false;
}
}
return true;
}
if (a && b && _typeof$1(a) === 'object' && _typeof$1(b) === 'object') {
var keys = Object.keys(a);
if (keys.length !== Object.keys(b).length) {
return false;
}
return keys.every(function (key) {
return deepEqual(a[key], b[key], newLevel);
});
}
// other
return false;
}
return deepEqual(obj1, obj2);
}
// [times, realValue]
var SPLIT$1 = '%';
var Entity = /*#__PURE__*/function () {
function Entity(instanceId) {
_classCallCheck(this, Entity);
_defineProperty$1(this, "instanceId", void 0);
/** @private Internal cache map. Do not access this directly */
_defineProperty$1(this, "cache", new Map());
this.instanceId = instanceId;
}
_createClass(Entity, [{
key: "get",
value: function get(keys) {
return this.cache.get(keys.join(SPLIT$1)) || null;
}
}, {
key: "update",
value: function update(keys, valueFn) {
var path = keys.join(SPLIT$1);
var prevValue = this.cache.get(path);
var nextValue = valueFn(prevValue);
if (nextValue === null) {
this.cache.delete(path);
} else {
this.cache.set(path, nextValue);
}
}
}]);
return Entity;
}();
var ATTR_TOKEN = 'data-token-hash';
var ATTR_MARK = 'data-css-hash';
var ATTR_CACHE_PATH = 'data-cache-path';
// Mark css-in-js instance in style element
var CSS_IN_JS_INSTANCE = '__cssinjs_instance__';
function createCache() {
var cssinjsInstanceId = Math.random().toString(12).slice(2);
// Tricky SSR: Move all inline style to the head.
// PS: We do not recommend tricky mode.
if (typeof document !== 'undefined' && document.head && document.body) {
var styles = document.body.querySelectorAll("style[".concat(ATTR_MARK, "]")) || [];
var firstChild = document.head.firstChild;
Array.from(styles).forEach(function (style) {
style[CSS_IN_JS_INSTANCE] = style[CSS_IN_JS_INSTANCE] || cssinjsInstanceId;
// Not force move if no head
if (style[CSS_IN_JS_INSTANCE] === cssinjsInstanceId) {
document.head.insertBefore(style, firstChild);
}
});
// Deduplicate of moved styles
var styleHash = {};
Array.from(document.querySelectorAll("style[".concat(ATTR_MARK, "]"))).forEach(function (style) {
var hash = style.getAttribute(ATTR_MARK);
if (styleHash[hash]) {
if (style[CSS_IN_JS_INSTANCE] === cssinjsInstanceId) {
var _style$parentNode;
(_style$parentNode = style.parentNode) === null || _style$parentNode === void 0 || _style$parentNode.removeChild(style);
}
} else {
styleHash[hash] = true;
}
});
}
return new Entity(cssinjsInstanceId);
}
var StyleContext = /*#__PURE__*/React.createContext({
hashPriority: 'low',
cache: createCache(),
defaultCache: true
});
var StyleContext$1 = StyleContext;
// ================================== Cache ==================================
function sameDerivativeOption(left, right) {
if (left.length !== right.length) {
return false;
}
for (var i = 0; i < left.length; i++) {
if (left[i] !== right[i]) {
return false;
}
}
return true;
}
var ThemeCache = /*#__PURE__*/function () {
function ThemeCache() {
_classCallCheck(this, ThemeCache);
_defineProperty$1(this, "cache", void 0);
_defineProperty$1(this, "keys", void 0);
_defineProperty$1(this, "cacheCallTimes", void 0);
this.cache = new Map();
this.keys = [];
this.cacheCallTimes = 0;
}
_createClass(ThemeCache, [{
key: "size",
value: function size() {
return this.keys.length;
}
}, {
key: "internalGet",
value: function internalGet(derivativeOption) {
var _cache2, _cache3;
var updateCallTimes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var cache = {
map: this.cache
};
derivativeOption.forEach(function (derivative) {
if (!cache) {
cache = undefined;
} else {
var _cache;
cache = (_cache = cache) === null || _cache === void 0 || (_cache = _cache.map) === null || _cache === void 0 ? void 0 : _cache.get(derivative);
}
});
if ((_cache2 = cache) !== null && _cache2 !== void 0 && _cache2.value && updateCallTimes) {
cache.value[1] = this.cacheCallTimes++;
}
return (_cache3 = cache) === null || _cache3 === void 0 ? void 0 : _cache3.value;
}
}, {
key: "get",
value: function get(derivativeOption) {
var _this$internalGet;
return (_this$internalGet = this.internalGet(derivativeOption, true)) === null || _this$internalGet === void 0 ? void 0 : _this$internalGet[0];
}
}, {
key: "has",
value: function has(derivativeOption) {
return !!this.internalGet(derivativeOption);
}
}, {
key: "set",
value: function set(derivativeOption, value) {
var _this = this;
// New cache
if (!this.has(derivativeOption)) {
if (this.size() + 1 > ThemeCache.MAX_CACHE_SIZE + ThemeCache.MAX_CACHE_OFFSET) {
var _this$keys$reduce = this.keys.reduce(function (result, key) {
var _result = _slicedToArray(result, 2),
callTimes = _result[1];
if (_this.internalGet(key)[1] < callTimes) {
return [key, _this.internalGet(key)[1]];
}
return result;
}, [this.keys[0], this.cacheCallTimes]),
_this$keys$reduce2 = _slicedToArray(_this$keys$reduce, 1),
targetKey = _this$keys$reduce2[0];
this.delete(targetKey);
}
this.keys.push(derivativeOption);
}
var cache = this.cache;
derivativeOption.forEach(function (derivative, index) {
if (index === derivativeOption.length - 1) {
cache.set(derivative, {
value: [value, _this.cacheCallTimes++]
});
} else {
var cacheValue = cache.get(derivative);
if (!cacheValue) {
cache.set(derivative, {
map: new Map()
});
} else if (!cacheValue.map) {
cacheValue.map = new Map();
}
cache = cache.get(derivative).map;
}
});
}
}, {
key: "deleteByPath",
value: function deleteByPath(currentCache, derivatives) {
var cache = currentCache.get(derivatives[0]);
if (derivatives.length === 1) {
var _cache$value;
if (!cache.map) {
currentCache.delete(derivatives[0]);
} else {
currentCache.set(derivatives[0], {
map: cache.map
});
}
return (_cache$value = cache.value) === null || _cache$value === void 0 ? void 0 : _cache$value[0];
}
var result = this.deleteByPath(cache.map, derivatives.slice(1));
if ((!cache.map || cache.map.size === 0) && !cache.value) {
currentCache.delete(derivatives[0]);
}
return result;
}
}, {
key: "delete",
value: function _delete(derivativeOption) {
// If cache exists
if (this.has(derivativeOption)) {
this.keys = this.keys.filter(function (item) {
return !sameDerivativeOption(item, derivativeOption);
});
return this.deleteByPath(this.cache, derivativeOption);
}
return undefined;
}
}]);
return ThemeCache;
}();
_defineProperty$1(ThemeCache, "MAX_CACHE_SIZE", 20);
_defineProperty$1(ThemeCache, "MAX_CACHE_OFFSET", 5);
var uuid = 0;
/**
* Theme with algorithms to derive tokens from design tokens.
* Use `createTheme` first which will help to manage the theme instance cache.
*/
var Theme = /*#__PURE__*/function () {
function Theme(derivatives) {
_classCallCheck(this, Theme);
_defineProperty$1(this, "derivatives", void 0);
_defineProperty$1(this, "id", void 0);
this.derivatives = Array.isArray(derivatives) ? derivatives : [derivatives];
this.id = uuid;
if (derivatives.length === 0) {
warning$5(derivatives.length > 0, '[Ant Design CSS-in-JS] Theme should have at least one derivative function.');
}
uuid += 1;
}
_createClass(Theme, [{
key: "getDerivativeToken",
value: function getDerivativeToken(token) {
return this.derivatives.reduce(function (result, derivative) {
return derivative(token, result);
}, undefined);
}
}]);
return Theme;
}();
var cacheThemes = new ThemeCache();
/**
* Same as new Theme, but will always return same one if `derivative` not changed.
*/
function createTheme(derivatives) {
var derivativeArr = Array.isArray(derivatives) ? derivatives : [derivatives];
// Create new theme if not exist
if (!cacheThemes.has(derivativeArr)) {
cacheThemes.set(derivativeArr, new Theme(derivativeArr));
}
// Get theme from cache and return
return cacheThemes.get(derivativeArr);
}
// Create a cache for memo concat
var resultCache = new WeakMap();
var RESULT_VALUE = {};
function memoResult(callback, deps) {
var current = resultCache;
for (var i = 0; i < deps.length; i += 1) {
var dep = deps[i];
if (!current.has(dep)) {
current.set(dep, new WeakMap());
}
current = current.get(dep);
}
if (!current.has(RESULT_VALUE)) {
current.set(RESULT_VALUE, callback());
}
return current.get(RESULT_VALUE);
}
// Create a cache here to avoid always loop generate
var flattenTokenCache = new WeakMap();
/**
* Flatten token to string, this will auto cache the result when token not change
*/
function flattenToken(token) {
var str = flattenTokenCache.get(token) || '';
if (!str) {
Object.keys(token).forEach(function (key) {
var value = token[key];
str += key;
if (value instanceof Theme) {
str += value.id;
} else if (value && _typeof$1(value) === 'object') {
str += flattenToken(value);
} else {
str += value;
}
});
// Put in cache
flattenTokenCache.set(token, str);
}
return str;
}
/**
* Convert derivative token to key string
*/
function token2key(token, salt) {
return murmur2("".concat(salt, "_").concat(flattenToken(token)));
}
var randomSelectorKey = "random-".concat(Date.now(), "-").concat(Math.random()).replace(/\./g, '');
// Magic `content` for detect selector support
var checkContent = '_bAmBoO_';
function supportSelector(styleStr, handleElement, supportCheck) {
if (canUseDom()) {
var _getComputedStyle$con, _ele$parentNode;
updateCSS(styleStr, randomSelectorKey);
var _ele = document.createElement('div');
_ele.style.position = 'fixed';
_ele.style.left = '0';
_ele.style.top = '0';
handleElement === null || handleElement === void 0 || handleElement(_ele);
document.body.appendChild(_ele);
if (process.env.NODE_ENV !== 'production') {
_ele.innerHTML = 'Test';
_ele.style.zIndex = '9999999';
}
var support = supportCheck ? supportCheck(_ele) : (_getComputedStyle$con = getComputedStyle(_ele).content) === null || _getComputedStyle$con === void 0 ? void 0 : _getComputedStyle$con.includes(checkContent);
(_ele$parentNode = _ele.parentNode) === null || _ele$parentNode === void 0 || _ele$parentNode.removeChild(_ele);
removeCSS(randomSelectorKey);
return support;
}
return false;
}
var canLayer = undefined;
function supportLayer() {
if (canLayer === undefined) {
canLayer = supportSelector("@layer ".concat(randomSelectorKey, " { .").concat(randomSelectorKey, " { content: \"").concat(checkContent, "\"!important; } }"), function (ele) {
ele.className = randomSelectorKey;
});
}
return canLayer;
}
var isClientSide = canUseDom();
function toStyleStr(style, tokenKey, styleId) {
var _objectSpread2;
var customizeAttrs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var plain = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
if (plain) {
return style;
}
var attrs = _objectSpread2$1(_objectSpread2$1({}, customizeAttrs), {}, (_objectSpread2 = {}, _defineProperty$1(_objectSpread2, ATTR_TOKEN, tokenKey), _defineProperty$1(_objectSpread2, ATTR_MARK, styleId), _objectSpread2));
var attrStr = Object.keys(attrs).map(function (attr) {
var val = attrs[attr];
return val ? "".concat(attr, "=\"").concat(val, "\"") : null;
}).filter(function (v) {
return v;
}).join(' ');
return "<style ".concat(attrStr, ">").concat(style, "</style>");
}
var token2CSSVar = function token2CSSVar(token) {
var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
return "--".concat(prefix ? "".concat(prefix, "-") : '').concat(token).replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/([A-Z]+)([A-Z][a-z0-9]+)/g, '$1-$2').replace(/([a-z])([A-Z0-9])/g, '$1-$2').toLowerCase();
};
var serializeCSSVar = function serializeCSSVar(cssVars, hashId, options) {
if (!Object.keys(cssVars).length) {
return '';
}
return ".".concat(hashId).concat(options !== null && options !== void 0 && options.scope ? ".".concat(options.scope) : '', "{").concat(Object.entries(cssVars).map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
return "".concat(key, ":").concat(value, ";");
}).join(''), "}");
};
var transformToken = function transformToken(token, themeKey, config) {
var cssVars = {};
var result = {};
Object.entries(token).forEach(function (_ref3) {
var _config$preserve, _config$ignore;
var _ref4 = _slicedToArray(_ref3, 2),
key = _ref4[0],
value = _ref4[1];
if (config !== null && config !== void 0 && (_config$preserve = config.preserve) !== null && _config$preserve !== void 0 && _config$preserve[key]) {
result[key] = value;
} else if ((typeof value === 'string' || typeof value === 'number') && !(config !== null && config !== void 0 && (_config$ignore = config.ignore) !== null && _config$ignore !== void 0 && _config$ignore[key])) {
var _config$unitless;
var cssVar = token2CSSVar(key, config === null || config === void 0 ? void 0 : config.prefix);
cssVars[cssVar] = typeof value === 'number' && !(config !== null && config !== void 0 && (_config$unitless = config.unitless) !== null && _config$unitless !== void 0 && _config$unitless[key]) ? "".concat(value, "px") : String(value);
result[key] = "var(".concat(cssVar, ")");
}
});
return [result, serializeCSSVar(cssVars, themeKey, {
scope: config === null || config === void 0 ? void 0 : config.scope
})];
};
/**
* Wrap `React.useLayoutEffect` which will not throw warning message in test env
*/
var useInternalLayoutEffect = process.env.NODE_ENV !== 'test' && canUseDom() ? React.useLayoutEffect : React.useEffect;
var useLayoutEffect = function useLayoutEffect(callback, deps) {
var firstMountRef = React.useRef(true);
useInternalLayoutEffect(function () {
return callback(firstMountRef.current);
}, deps);
// We tell react that first mount has passed
useInternalLayoutEffect(function () {
firstMountRef.current = false;
return function () {
firstMountRef.current = true;
};
}, []);
};
var useLayoutUpdateEffect = function useLayoutUpdateEffect(callback, deps) {
useLayoutEffect(function (firstMount) {
if (!firstMount) {
return callback();
}
}, deps);
};
// We need fully clone React function here
// to avoid webpack warning React 17 do not export `useId`
var fullClone$1 = _objectSpread2$1({}, React);
var useInsertionEffect$1 = fullClone$1.useInsertionEffect;
/**
* Polyfill `useInsertionEffect` for React < 18
* @param renderEffect will be executed in `useMemo`, and do not have callback
* @param effect will be executed in `useLayoutEffect`
* @param deps
*/
var useInsertionEffectPolyfill = function useInsertionEffectPolyfill(renderEffect, effect, deps) {
React.useMemo(renderEffect, deps);
useLayoutEffect(function () {
return effect(true);
}, deps);
};
/**
* Compatible `useInsertionEffect`
* will use `useInsertionEffect` if React version >= 18,
* otherwise use `useInsertionEffectPolyfill`.
*/
var useCompatibleInsertionEffect = useInsertionEffect$1 ? function (renderEffect, effect, deps) {
return useInsertionEffect$1(function () {
renderEffect();
return effect();
}, deps);
} : useInsertionEffectPolyfill;
var useCompatibleInsertionEffect$1 = useCompatibleInsertionEffect;
var fullClone = _objectSpread2$1({}, React);
var useInsertionEffect = fullClone.useInsertionEffect;
// DO NOT register functions in useEffect cleanup function, or functions that registered will never be called.
var useCleanupRegister = function useCleanupRegister(deps) {
var effectCleanups = [];
var cleanupFlag = false;
function register(fn) {
if (cleanupFlag) {
if (process.env.NODE_ENV !== 'production') {
warning$5(false, '[Ant Design CSS-in-JS] You are registering a cleanup function after unmount, which will not have any effect.');
}
return;
}
effectCleanups.push(fn);
}
React.useEffect(function () {
// Compatible with strict mode
cleanupFlag = false;
return function () {
cleanupFlag = true;
if (effectCleanups.length) {
effectCleanups.forEach(function (fn) {
return fn();
});
}
};
}, deps);
return register;
};
var useRun = function useRun() {
return function (fn) {
fn();
};
};
// Only enable register in React 18
var useEffectCleanupRegister = typeof useInsertionEffect !== 'undefined' ? useCleanupRegister : useRun;
var useEffectCleanupRegister$1 = useEffectCleanupRegister;
function useProdHMR() {
return false;
}
var webpackHMR = false;
function useDevHMR() {
return webpackHMR;
}
var useHMR = process.env.NODE_ENV === 'production' ? useProdHMR : useDevHMR;
// Webpack `module.hot.accept` do not support any deps update trigger
// We have to hack handler to force mark as HRM
if (process.env.NODE_ENV !== 'production' && typeof module !== 'undefined' && module && module.hot && typeof window !== 'undefined') {
var win = window;
if (typeof win.webpackHotUpdate === 'function') {
var originWebpackHotUpdate = win.webpackHotUpdate;
win.webpackHotUpdate = function () {
webpackHMR = true;
setTimeout(function () {
webpackHMR = false;
}, 0);
return originWebpackHotUpdate.apply(void 0, arguments);
};
}
}
function useGlobalCache(prefix, keyPath, cacheFn, onCacheRemove,
// Add additional effect trigger by `useInsertionEffect`
onCacheEffect) {
var _React$useContext = React.useContext(StyleContext$1),
globalCache = _React$useContext.cache;
var fullPath = [prefix].concat(_toConsumableArray(keyPath));
var deps = fullPath.join('_');
var register = useEffectCleanupRegister$1([deps]);
var HMRUpdate = useHMR();
var buildCache = function buildCache(updater) {
globalCache.update(fullPath, function (prevCache) {
var _ref = prevCache || [undefined, undefined],
_ref2 = _slicedToArray(_ref, 2),
_ref2$ = _ref2[0],
times = _ref2$ === void 0 ? 0 : _ref2$,
cache = _ref2[1];
// HMR should always ignore cache since developer may change it
var tmpCache = cache;
if (process.env.NODE_ENV !== 'production' && cache && HMRUpdate) {
onCacheRemove === null || onCacheRemove === void 0 || onCacheRemove(tmpCache, HMRUpdate);
tmpCache = null;
}
var mergedCache = tmpCache || cacheFn();
var data = [times, mergedCache];
// Call updater if need additional logic
return updater ? updater(data) : data;
});
};
// Create cache
React.useMemo(function () {
buildCache();
}, /* eslint-disable react-hooks/exhaustive-deps */
[deps]
/* eslint-enable */);
var cacheEntity = globalCache.get(fullPath);
// HMR clean the cache but not trigger `useMemo` again
// Let's fallback of this
// ref https://github.com/ant-design/cssinjs/issues/127
if (process.env.NODE_ENV !== 'production' && !cacheEntity) {
buildCache();
cacheEntity = globalCache.get(fullPath);
}
var cacheContent = cacheEntity[1];
// Remove if no need anymore
useCompatibleInsertionEffect$1(function () {
onCacheEffect === null || onCacheEffect === void 0 || onCacheEffect(cacheContent);
}, function (polyfill) {
// It's bad to call build again in effect.
// But we have to do this since StrictMode will call effect twice
// which will clear cache on the first time.
buildCache(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
times = _ref4[0],
cache = _ref4[1];
if (polyfill && times === 0) {
onCacheEffect === null || onCacheEffect === void 0 || onCacheEffect(cacheContent);
}
return [times + 1, cache];
});
return function () {
globalCache.update(fullPath, function (prevCache) {
var _ref5 = prevCache || [],
_ref6 = _slicedToArray(_ref5, 2),
_ref6$ = _ref6[0],
times = _ref6$ === void 0 ? 0 : _ref6$,
cache = _ref6[1];
var nextCount = times - 1;
if (nextCount === 0) {
// Always remove styles in useEffect callback
register(function () {
// With polyfill, registered callback will always be called synchronously
// But without polyfill, it will be called in effect clean up,
// And by that time this cache is cleaned up.
if (polyfill || !globalCache.get(fullPath)) {
onCacheRemove === null || onCacheRemove === void 0 || onCacheRemove(cache, false);
}
});
return null;
}
return [times - 1, cache];
});
};
}, [deps]);
return cacheContent;
}
var EMPTY_OVERRIDE = {};
// Generate different prefix to make user selector break in production env.
// This helps developer not to do style override directly on the hash id.
var hashPrefix = process.env.NODE_ENV !== 'production' ? 'css-dev-only-do-not-override' : 'css';
var tokenKeys = new Map();
function recordCleanToken(tokenKey) {
tokenKeys.set(tokenKey, (tokenKeys.get(tokenKey) || 0) + 1);
}
function removeStyleTags(key, instanceId) {
if (typeof document !== 'undefined') {
var styles = document.querySelectorAll("style[".concat(ATTR_TOKEN, "=\"").concat(key, "\"]"));
styles.forEach(function (style) {
if (style[CSS_IN_JS_INSTANCE] === instanceId) {
var _style$parentNode;
(_style$parentNode = style.parentNode) === null || _style$parentNode === void 0 || _style$parentNode.removeChild(style);
}
});
}
}
var TOKEN_THRESHOLD = 0;
// Remove will check current keys first
function cleanTokenStyle(tokenKey, instanceId) {
tokenKeys.set(tokenKey, (tokenKeys.get(tokenKey) || 0) - 1);
var tokenKeyList = Array.from(tokenKeys.keys());
var cleanableKeyList = tokenKeyList.filter(function (key) {
var count = tokenKeys.get(key) || 0;
return count <= 0;
});
// Should keep tokens under threshold for not to insert style too often
if (tokenKeyList.length - cleanableKeyList.length > TOKEN_THRESHOLD) {
cleanableKeyList.forEach(function (key) {
removeStyleTags(key, instanceId);
tokenKeys.delete(key);
});
}
}
var getComputedToken = function getComputedToken(originToken, overrideToken, theme, format) {
var derivativeToken = theme.getDerivativeToken(originToken);
// Merge with override
var mergedDerivativeToken = _objectSpread2$1(_objectSpread2$1({}, derivativeToken), overrideToken);
// Format if needed
if (format) {
mergedDerivativeToken = format(mergedDerivativeToken);
}
return mergedDerivativeToken;
};
var TOKEN_PREFIX = 'token';
/**
* Cache theme derivative token as global shared one
* @param theme Theme entity
* @param tokens List of tokens, used for cache. Please do not dynamic generate object directly
* @param option Additional config
* @returns Call Theme.getDerivativeToken(tokenObject) to get token
*/
function useCacheToken(theme, tokens) {
var option = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var _useContext = useContext(StyleContext$1),
instanceId = _useContext.cache.instanceId,
container = _useContext.container;
var _option$salt = option.salt,
salt = _option$salt === void 0 ? '' : _option$salt,
_option$override = option.override,
override = _option$override === void 0 ? EMPTY_OVERRIDE : _option$override,
formatToken = option.formatToken,
compute = option.getComputedToken,
cssVar = option.cssVar;
// Basic - We do basic cache here
var mergedToken = memoResult(function () {
return Object.assign.apply(Object, [{}].concat(_toConsumableArray(tokens)));
}, tokens);
var tokenStr = flattenToken(mergedToken);
var overrideTokenStr = flattenToken(override);
var cssVarStr = cssVar ? flattenToken(cssVar) : '';
var cachedToken = useGlobalCache(TOKEN_PREFIX, [salt, theme.id, tokenStr, overrideTokenStr, cssVarStr], function () {
var _cssVar$key;
var mergedDerivativeToken = compute ? compute(mergedToken, override, theme) : getComputedToken(mergedToken, override, theme, formatToken);
// Replace token value with css variables
var actualToken = _objectSpread2$1({}, mergedDerivativeToken);
var cssVarsStr = '';
if (!!cssVar) {
var _transformToken = transformToken(mergedDerivativeToken, cssVar.key, {
prefix: cssVar.prefix,
ignore: cssVar.ignore,
unitless: cssVar.unitless,
preserve: cssVar.preserve
});
var _transformToken2 = _slicedToArray(_transformToken, 2);
mergedDerivativeToken = _transformToken2[0];
cssVarsStr = _transformToken2[1];
}
// Optimize for `useStyleRegister` performance
var tokenKey = token2key(mergedDerivativeToken, salt);
mergedDerivativeToken._tokenKey = tokenKey;
actualToken._tokenKey = token2key(actualToken, salt);
var themeKey = (_cssVar$key = cssVar === null || cssVar === void 0 ? void 0 : cssVar.key) !== null && _cssVar$key !== void 0 ? _cssVar$key : tokenKey;
mergedDerivativeToken._themeKey = themeKey;
recordCleanToken(themeKey);
var hashId = "".concat(hashPrefix, "-").concat(murmur2(tokenKey));
mergedDerivativeToken._hashId = hashId; // Not used
return [mergedDerivativeToken, hashId, actualToken, cssVarsStr, (cssVar === null || cssVar === void 0 ? void 0 : cssVar.key) || ''];
}, function (cache) {
// Remove token will remove all related style
cleanTokenStyle(cache[0]._themeKey, instanceId);
}, function (_ref) {
var _ref2 = _slicedToArray(_ref, 4),
token = _ref2[0],
cssVarsStr = _ref2[3];
if (cssVar && cssVarsStr) {
var style = updateCSS(cssVarsStr, murmur2("css-variables-".concat(token._themeKey)), {
mark: ATTR_MARK,
prepend: 'queue',
attachTo: container,
priority: -999
});
style[CSS_IN_JS_INSTANCE] = instanceId;
// Used for `useCacheToken` to remove on batch when token removed
style.setAttribute(ATTR_TOKEN, token._themeKey);
}
});
return cachedToken;
}
var extract$2 = function extract(cache, effectStyles, options) {
var _cache = _slicedToArray(cache, 5),
realToken = _cache[2],
styleStr = _cache[3],
cssVarKey = _cache[4];
var _ref3 = options || {},
plain = _ref3.plain;
if (!styleStr) {
return null;
}
var styleId = realToken._tokenKey;
var order = -999;
// ====================== Style ======================
// Used for rc-util
var sharedAttrs = {
'data-rc-order': 'prependQueue',
'data-rc-priority': "".concat(order)
};
var styleText = toStyleStr(styleStr, cssVarKey, styleId, sharedAttrs, plain);
return [order, styleId, styleText];
};
var unitlessKeys = {
animationIterationCount: 1,
borderImageOutset: 1,
borderImageSlice: 1,
borderImageWidth: 1,
boxFlex: 1,
boxFlexGroup: 1,
boxOrdinalGroup: 1,
columnCount: 1,
columns: 1,
flex: 1,
flexGrow: 1,
flexPositive: 1,
flexShrink: 1,
flexNegative: 1,
flexOrder: 1,
gridRow: 1,
gridRowEnd: 1,
gridRowSpan: 1,
gridRowStart: 1,
gridColumn: 1,
gridColumnEnd: 1,
gridColumnSpan: 1,
gridColumnStart: 1,
msGridRow: 1,
msGridRowSpan: 1,
msGridColumn: 1,
msGridColumnSpan: 1,
fontWeight: 1,
lineHeight: 1,
opacity: 1,
order: 1,
orphans: 1,
tabSize: 1,
widows: 1,
zIndex: 1,
zoom: 1,
WebkitLineClamp: 1,
// SVG-related properties
fillOpacity: 1,
floodOpacity: 1,
stopOpacity: 1,
strokeDasharray: 1,
strokeDashoffset: 1,
strokeMiterlimit: 1,
strokeOpacity: 1,
strokeWidth: 1
};
var COMMENT = 'comm';
var RULESET = 'rule';
var DECLARATION = 'decl';
var IMPORT = '@import';
var KEYFRAMES = '@keyframes';
var LAYER = '@layer';
/**
* @param {number}
* @return {number}
*/
var abs = Math.abs;
/**
* @param {number}
* @return {string}
*/
var from = String.fromCharCode;
/**
* @param {string} value
* @return {string}
*/
function trim(value) {
return value.trim();
}
/**
* @param {string} value
* @param {(string|RegExp)} pattern
* @param {string} replacement
* @return {string}
*/
function replace(value, pattern, replacement) {
return value.replace(pattern, replacement);
}
/**
* @param {string} value
* @param {string} search
* @param {number} position
* @return {number}
*/
function indexof(value, search, position) {
return value.indexOf(search, position);
}
/**
* @param {string} value
* @param {number} index
* @return {number}
*/
function charat(value, index) {
return value.charCodeAt(index) | 0;
}
/**
* @param {string} value
* @param {number} begin
* @param {number} end
* @return {string}
*/
function substr(value, begin, end) {
return value.slice(begin, end);
}
/**
* @param {string} value
* @return {number}
*/
function strlen(value) {
return value.length;
}
/**
* @param {any[]} value
* @return {number}
*/
function sizeof(value) {
return value.length;
}
/**
* @param {any} value
* @param {any[]} array
* @return {any}
*/
function append(value, array) {
return array.push(value), value;
}
var line = 1;
var column = 1;
var length = 0;
var position = 0;
var character = 0;
var characters = '';
/**
* @param {string} value
* @param {object | null} root
* @param {object | null} parent
* @param {string} type
* @param {string[] | string} props
* @param {object[] | string} children
* @param {object[]} siblings
* @param {number} length
*/
function node(value, root, parent, type, props, children, length, siblings) {
return {
value: value,
root: root,
parent: parent,
type: type,
props: props,
children: children,
line: line,
column: column,
length: length,
return: '',
siblings: siblings
};
}
/**
* @return {number}
*/
function char() {
return character;
}
/**
* @return {number}
*/
function prev() {
character = position > 0 ? charat(characters, --position) : 0;
if (column--, character === 10) column = 1, line--;
return character;
}
/**
* @return {number}
*/
function next() {
character = position < length ? charat(characters, position++) : 0;
if (column++, character === 10) column = 1, line++;
return character;
}
/**
* @return {number}
*/
function peek() {
return charat(characters, position);
}
/**
* @return {number}
*/
function caret() {
return position;
}
/**
* @param {number} begin
* @param {number} end
* @return {string}
*/
function slice(begin, end) {
return substr(characters, begin, end);
}
/**
* @param {number} type
* @return {number}
*/
function token(type) {
switch (type) {
// \0 \t \n \r \s whitespace token
case 0:
case 9:
case 10:
case 13:
case 32:
return 5;
// ! + , / > @ ~ isolate token
case 33:
case 43:
case 44:
case 47:
case 62:
case 64:
case 126:
// ; { } breakpoint token
case 59:
case 123:
case 125:
return 4;
// : accompanied token
case 58:
return 3;
// " ' ( [ opening delimit token
case 34:
case 39:
case 40:
case 91:
return 2;
// ) ] closing delimit token
case 41:
case 93:
return 1;
}
return 0;
}
/**
* @param {string} value
* @return {any[]}
*/
function alloc(value) {
return line = column = 1, length = strlen(characters = value), position = 0, [];
}
/**
* @param {any} value
* @return {any}
*/
function dealloc(value) {
return characters = '', value;
}
/**
* @param {number} type
* @return {string}
*/
function delimit(type) {
return trim(slice(position - 1, delimiter(type === 91 ? type + 2 : type === 40 ? type + 1 : type)));
}
/**
* @param {number} type
* @return {string}
*/
function whitespace$1(type) {
while (character = peek()) if (character < 33) next();else break;
return token(type) > 2 || token(character) > 3 ? '' : ' ';
}
/**
* @param {number} index
* @param {number} count
* @return {string}
*/
function escaping(index, count) {
while (--count && next())
// not 0-9 A-F a-f
if (character < 48 || character > 102 || character > 57 && character < 65 || character > 70 && character < 97) break;
return slice(index, caret() + (count < 6 && peek() == 32 && next() == 32));
}
/**
* @param {number} type
* @return {number}
*/
function delimiter(type) {
while (next()) switch (character) {
// ] ) " '
case type:
return position;
// " '
case 34:
case 39:
if (type !== 34 && type !== 39) delimiter(character);
break;
// (
case 40:
if (type === 41) delimiter(type);
break;
// \
case 92:
next();
break;
}
return position;
}
/**
* @param {number} type
* @param {number} index
* @return {number}
*/
function commenter(type, index) {
while (next())
// //
if (type + character === 47 + 10) break;
// /*
else if (type + character === 42 + 42 && peek() === 47) break;
return '/*' + slice(index, position - 1) + '*' + from(type === 47 ? type : next());
}
/**
* @param {number} index
* @return {string}
*/
function identifier(index) {
while (!token(peek())) next();
return slice(index, position);
}
/**
* @param {string} value
* @return {object[]}
*/
function compile(value) {
return dealloc(parse('', null, null, null, [''], value = alloc(value), 0, [0], value));
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {string[]} rule
* @param {string[]} rules
* @param {string[]} rulesets
* @param {number[]} pseudo
* @param {number[]} points
* @param {string[]} declarations
* @return {object}
*/
function parse(value, root, parent, rule, rules, rulesets, pseudo, points, declarations) {
var index = 0;
var offset = 0;
var length = pseudo;
var atrule = 0;
var property = 0;
var previous = 0;
var variable = 1;
var scanning = 1;
var ampersand = 1;
var character = 0;
var type = '';
var props = rules;
var children = rulesets;
var reference = rule;
var characters = type;
while (scanning) switch (previous = character, character = next()) {
// (
case 40:
if (previous != 108 && charat(characters, length - 1) == 58) {
if (indexof(characters += replace(delimit(character), '&', '&\f'), '&\f', abs(index ? points[index - 1] : 0)) != -1) ampersand = -1;
break;
}
// " ' [
case 34:
case 39:
case 91:
characters += delimit(character);
break;
// \t \n \r \s
case 9:
case 10:
case 13:
case 32:
characters += whitespace$1(previous);
break;
// \
case 92:
characters += escaping(caret() - 1, 7);
continue;
// /
case 47:
switch (peek()) {
case 42:
case 47:
append(comment(commenter(next(), caret()), root, parent, declarations), declarations);
break;
default:
characters += '/';
}
break;
// {
case 123 * variable:
points[index++] = strlen(characters) * ampersand;
// } ; \0
case 125 * variable:
case 59:
case 0:
switch (character) {
// \0 }
case 0:
case 125:
scanning = 0;
// ;
case 59 + offset:
if (ampersand == -1) characters = replace(characters, /\f/g, '');
if (property > 0 && strlen(characters) - length) append(property > 32 ? declaration(characters + ';', rule, parent, length - 1, declarations) : declaration(replace(characters, ' ', '') + ';', rule, parent, length - 2, declarations), declarations);
break;
// @ ;
case 59:
characters += ';';
// { rule/at-rule
default:
append(reference = ruleset(characters, root, parent, index, offset, rules, points, type, props = [], children = [], length, rulesets), rulesets);
if (character === 123) if (offset === 0) parse(characters, root, reference, reference, props, rulesets, length, points, children);else switch (atrule === 99 && charat(characters, 3) === 110 ? 100 : atrule) {
// d l m s
case 100:
case 108:
case 109:
case 115:
parse(value, reference, reference, rule && append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length, children), children), rules, children, length, points, rule ? props : children);
break;
default:
parse(characters, reference, reference, reference, [''], children, 0, points, children);
}
}
index = offset = property = 0, variable = ampersand = 1, type = characters = '', length = pseudo;
break;
// :
case 58:
length = 1 + strlen(characters), property = previous;
default:
if (variable < 1) if (character == 123) --variable;else if (character == 125 && variable++ == 0 && prev() == 125) continue;
switch (characters += from(character), character * variable) {
// &
case 38:
ampersand = offset > 0 ? 1 : (characters += '\f', -1);
break;
// ,
case 44:
points[index++] = (strlen(characters) - 1) * ampersand, ampersand = 1;
break;
// @
case 64:
// -
if (peek() === 45) characters += delimit(next());
atrule = peek(), offset = length = strlen(type = characters += identifier(caret())), character++;
break;
// -
case 45:
if (previous === 45 && strlen(characters) == 2) variable = 0;
}
}
return rulesets;
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {number} index
* @param {number} offset
* @param {string[]} rules
* @param {number[]} points
* @param {string} type
* @param {string[]} props
* @param {string[]} children
* @param {number} length
* @param {object[]} siblings
* @return {object}
*/
function ruleset(value, root, parent, index, offset, rules, points, type, props, children, length, siblings) {
var post = offset - 1;
var rule = offset === 0 ? rules : [''];
var size = sizeof(rule);
for (var i = 0, j = 0, k = 0; i < index; ++i) for (var x = 0, y = substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x) if (z = trim(j > 0 ? rule[x] + ' ' + y : replace(y, /&\f/g, rule[x]))) props[k++] = z;
return node(value, root, parent, offset === 0 ? RULESET : type, props, children, length, siblings);
}
/**
* @param {number} value
* @param {object} root
* @param {object?} parent
* @param {object[]} siblings
* @return {object}
*/
function comment(value, root, parent, siblings) {
return node(value, root, parent, COMMENT, from(char()), substr(value, 2, -2), 0, siblings);
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {number} length
* @param {object[]} siblings
* @return {object}
*/
function declaration(value, root, parent, length, siblings) {
return node(value, root, parent, DECLARATION, substr(value, 0, length), substr(value, length + 1, -1), length, siblings);
}
/**
* @param {object[]} children
* @param {function} callback
* @return {string}
*/
function serialize(children, callback) {
var output = '';
for (var i = 0; i < children.length; i++) output += callback(children[i], i, children, callback) || '';
return output;
}
/**
* @param {object} element
* @param {number} index
* @param {object[]} children
* @param {function} callback
* @return {string}
*/
function stringify$1(element, index, children, callback) {
switch (element.type) {
case LAYER:
if (element.children.length) break;
case IMPORT:
case DECLARATION:
return element.return = element.return || element.value;
case COMMENT:
return '';
case KEYFRAMES:
return element.return = element.value + '{' + serialize(element.children, callback) + '}';
case RULESET:
if (!strlen(element.value = element.props.join(','))) return '';
}
return strlen(children = serialize(element.children, callback)) ? element.return = element.value + '{' + children + '}' : '';
}
function lintWarning(message, info) {
var path = info.path,
parentSelectors = info.parentSelectors;
warningOnce(false, "[Ant Design CSS-in-JS] ".concat(path ? "Error in ".concat(path, ": ") : '').concat(message).concat(parentSelectors.length ? " Selector: ".concat(parentSelectors.join(' | ')) : ''));
}
var linter$1 = function linter(key, value, info) {
if (key === 'content') {
// From emotion: https://github.com/emotion-js/emotion/blob/main/packages/serialize/src/index.js#L63
var contentValuePattern = /(attr|counters?|url|(((repeating-)?(linear|radial))|conic)-gradient)\(|(no-)?(open|close)-quote/;
var contentValues = ['normal', 'none', 'initial', 'inherit', 'unset'];
if (typeof value !== 'string' || contentValues.indexOf(value) === -1 && !contentValuePattern.test(value) && (value.charAt(0) !== value.charAt(value.length - 1) || value.charAt(0) !== '"' && value.charAt(0) !== "'")) {
lintWarning("You seem to be using a value for 'content' without quotes, try replacing it with `content: '\"".concat(value, "\"'`."), info);
}
}
};
var linter = function linter(key, value, info) {
if (key === 'animation') {
if (info.hashId && value !== 'none') {
lintWarning("You seem to be using hashed animation '".concat(value, "', in which case 'animationName' with Keyframe as value is recommended."), info);
}
}
};
var ATTR_CACHE_MAP = 'data-ant-cssinjs-cache-path';
/**
* This marks style from the css file.
* Which means not exist in `<style />` tag.
*/
var CSS_FILE_STYLE = '_FILE_STYLE__';
var cachePathMap;
var fromCSSFile = true;
function prepare() {
if (!cachePathMap) {
cachePathMap = {};
if (canUseDom()) {
var div = document.createElement('div');
div.className = ATTR_CACHE_MAP;
div.style.position = 'fixed';
div.style.visibility = 'hidden';
div.style.top = '-9999px';
document.body.appendChild(div);
var content = getComputedStyle(div).content || '';
content = content.replace(/^"/, '').replace(/"$/, '');
// Fill data
content.split(';').forEach(function (item) {
var _item$split = item.split(':'),
_item$split2 = _slicedToArray(_item$split, 2),
path = _item$split2[0],
hash = _item$split2[1];
cachePathMap[path] = hash;
});
// Remove inline record style
var inlineMapStyle = document.querySelector("style[".concat(ATTR_CACHE_MAP, "]"));
if (inlineMapStyle) {
var _inlineMapStyle$paren;
fromCSSFile = false;
(_inlineMapStyle$paren = inlineMapStyle.parentNode) === null || _inlineMapStyle$paren === void 0 || _inlineMapStyle$paren.removeChild(inlineMapStyle);
}
document.body.removeChild(div);
}
}
}
function existPath(path) {
prepare();
return !!cachePathMap[path];
}
function getStyleAndHash(path) {
var hash = cachePathMap[path];
var styleStr = null;
if (hash && canUseDom()) {
if (fromCSSFile) {
styleStr = CSS_FILE_STYLE;
} else {
var _style = document.querySelector("style[".concat(ATTR_MARK, "=\"").concat(cachePathMap[path], "\"]"));
if (_style) {
styleStr = _style.innerHTML;
} else {
// Clean up since not exist anymore
delete cachePathMap[path];
}
}
}
return [styleStr, hash];
}
var SKIP_CHECK = '_skip_check_';
var MULTI_VALUE = '_multi_value_';
// ============================================================================
// == Parser ==
// ============================================================================
// Preprocessor style content to browser support one
function normalizeStyle(styleStr) {
var serialized = serialize(compile(styleStr), stringify$1);
return serialized.replace(/\{%%%\:[^;];}/g, ';');
}
function isCompoundCSSProperty(value) {
return _typeof$1(value) === 'object' && value && (SKIP_CHECK in value || MULTI_VALUE in value);
}
// 注入 hash 值
function injectSelectorHash(key, hashId, hashPriority) {
if (!hashId) {
return key;
}
var hashClassName = ".".concat(hashId);
var hashSelector = hashPriority === 'low' ? ":where(".concat(hashClassName, ")") : hashClassName;
// 注入 hashId
var keys = key.split(',').map(function (k) {
var _firstPath$match;
var fullPath = k.trim().split(/\s+/);
// 如果 Selector 第一个是 HTML Element,那我们就插到它的后面。反之,就插到最前面。
var firstPath = fullPath[0] || '';
var htmlElement = ((_firstPath$match = firstPath.match(/^\w+/)) === null || _firstPath$match === void 0 ? void 0 : _firstPath$match[0]) || '';
firstPath = "".concat(htmlElement).concat(hashSelector).concat(firstPath.slice(htmlElement.length));
return [firstPath].concat(_toConsumableArray(fullPath.slice(1))).join(' ');
});
return keys.join(',');
}
// Parse CSSObject to style content
var parseStyle = function parseStyle(interpolation) {
var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
root: true,
parentSelectors: []
},
root = _ref.root,
injectHash = _ref.injectHash,
parentSelectors = _ref.parentSelectors;
var hashId = config.hashId,
layer = config.layer,
path = config.path,
hashPriority = config.hashPriority,
_config$transformers = config.transformers,
transformers = _config$transformers === void 0 ? [] : _config$transformers,
_config$linters = config.linters,
linters = _config$linters === void 0 ? [] : _config$linters;
var styleStr = '';
var effectStyle = {};
function parseKeyframes(keyframes) {
var animationName = keyframes.getName(hashId);
if (!effectStyle[animationName]) {
var _parseStyle = parseStyle(keyframes.style, config, {
root: false,
parentSelectors: parentSelectors
}),
_parseStyle2 = _slicedToArray(_parseStyle, 1),
_parsedStr = _parseStyle2[0];
effectStyle[animationName] = "@keyframes ".concat(keyframes.getName(hashId)).concat(_parsedStr);
}
}
function flattenList(list) {
var fullList = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
list.forEach(function (item) {
if (Array.isArray(item)) {
flattenList(item, fullList);
} else if (item) {
fullList.push(item);
}
});
return fullList;
}
var flattenStyleList = flattenList(Array.isArray(interpolation) ? interpolation : [interpolation]);
flattenStyleList.forEach(function (originStyle) {
// Only root level can use raw string
var style = typeof originStyle === 'string' && !root ? {} : originStyle;
if (typeof style === 'string') {
styleStr += "".concat(style, "\n");
} else if (style._keyframe) {
// Keyframe
parseKeyframes(style);
} else {
var mergedStyle = transformers.reduce(function (prev, trans) {
var _trans$visit;
return (trans === null || trans === void 0 || (_trans$visit = trans.visit) === null || _trans$visit === void 0 ? void 0 : _trans$visit.call(trans, prev)) || prev;
}, style);
// Normal CSSObject
Object.keys(mergedStyle).forEach(function (key) {
var value = mergedStyle[key];
if (_typeof$1(value) === 'object' && value && (key !== 'animationName' || !value._keyframe) && !isCompoundCSSProperty(value)) {
var subInjectHash = false;
// 当成嵌套对象来处理
var mergedKey = key.trim();
// Whether treat child as root. In most case it is false.
var nextRoot = false;
// 拆分多个选择器
if ((root || injectHash) && hashId) {
if (mergedKey.startsWith('@')) {
// 略过媒体查询,交给子节点继续插入 hashId
subInjectHash = true;
} else {
// 注入 hashId
mergedKey = injectSelectorHash(key, hashId, hashPriority);
}
} else if (root && !hashId && (mergedKey === '&' || mergedKey === '')) {
// In case of `{ '&': { a: { color: 'red' } } }` or `{ '': { a: { color: 'red' } } }` without hashId,
// we will get `&{a:{color:red;}}` or `{a:{color:red;}}` string for stylis to compile.
// But it does not conform to stylis syntax,
// and finally we will get `{color:red;}` as css, which is wrong.
// So we need to remove key in root, and treat child `{ a: { color: 'red' } }` as root.
mergedKey = '';
nextRoot = true;
}
var _parseStyle3 = parseStyle(value, config, {
root: nextRoot,
injectHash: subInjectHash,
parentSelectors: [].concat(_toConsumableArray(parentSelectors), [mergedKey])
}),
_parseStyle4 = _slicedToArray(_parseStyle3, 2),
_parsedStr2 = _parseStyle4[0],
childEffectStyle = _parseStyle4[1];
effectStyle = _objectSpread2$1(_objectSpread2$1({}, effectStyle), childEffectStyle);
styleStr += "".concat(mergedKey).concat(_parsedStr2);
} else {
var _value;
function appendStyle(cssKey, cssValue) {
if (process.env.NODE_ENV !== 'production' && (_typeof$1(value) !== 'object' || !(value !== null && value !== void 0 && value[SKIP_CHECK]))) {
[linter$1, linter].concat(_toConsumableArray(linters)).forEach(function (linter) {
return linter(cssKey, cssValue, {
path: path,
hashId: hashId,
parentSelectors: parentSelectors
});
});
}
// 如果是样式则直接插入
var styleName = cssKey.replace(/[A-Z]/g, function (match) {
return "-".concat(match.toLowerCase());
});
// Auto suffix with px
var formatValue = cssValue;
if (!unitlessKeys[cssKey] && typeof formatValue === 'number' && formatValue !== 0) {
formatValue = "".concat(formatValue, "px");
}
// handle animationName & Keyframe value
if (cssKey === 'animationName' && cssValue !== null && cssValue !== void 0 && cssValue._keyframe) {
parseKeyframes(cssValue);
formatValue = cssValue.getName(hashId);
}
styleStr += "".concat(styleName, ":").concat(formatValue, ";");
}
var actualValue = (_value = value === null || value === void 0 ? void 0 : value.value) !== null && _value !== void 0 ? _value : value;
if (_typeof$1(value) === 'object' && value !== null && value !== void 0 && value[MULTI_VALUE] && Array.isArray(actualValue)) {
actualValue.forEach(function (item) {
appendStyle(key, item);
});
} else {
appendStyle(key, actualValue);
}
}
});
}
});
if (!root) {
styleStr = "{".concat(styleStr, "}");
} else if (layer && supportLayer()) {
var layerCells = layer.split(',');
var layerName = layerCells[layerCells.length - 1].trim();
styleStr = "@layer ".concat(layerName, " {").concat(styleStr, "}");
// Order of layer if needed
if (layerCells.length > 1) {
// zombieJ: stylis do not support layer order, so we need to handle it manually.
styleStr = "@layer ".concat(layer, "{%%%:%}").concat(styleStr);
}
}
return [styleStr, effectStyle];
};
// ============================================================================
// == Register ==
// ============================================================================
function uniqueHash(path, styleStr) {
return murmur2("".concat(path.join('%')).concat(styleStr));
}
function Empty() {
return null;
}
var STYLE_PREFIX = 'style';
/**
* Register a style to the global style sheet.
*/
function useStyleRegister(info, styleFn) {
var token = info.token,
path = info.path,
hashId = info.hashId,
layer = info.layer,
nonce = info.nonce,
clientOnly = info.clientOnly,
_info$order = info.order,
order = _info$order === void 0 ? 0 : _info$order;
var _React$useContext = React.useContext(StyleContext$1),
autoClear = _React$useContext.autoClear,
mock = _React$useContext.mock,
defaultCache = _React$useContext.defaultCache,
hashPriority = _React$useContext.hashPriority,
container = _React$useContext.container,
ssrInline = _React$useContext.ssrInline,
transformers = _React$useContext.transformers,
linters = _React$useContext.linters,
cache = _React$useContext.cache;
var tokenKey = token._tokenKey;
var fullPath = [tokenKey].concat(_toConsumableArray(path));
// Check if need insert style
var isMergedClientSide = isClientSide;
if (process.env.NODE_ENV !== 'production' && mock !== undefined) {
isMergedClientSide = mock === 'client';
}
var _useGlobalCache = useGlobalCache(STYLE_PREFIX, fullPath,
// Create cache if needed
function () {
var cachePath = fullPath.join('|');
// Get style from SSR inline style directly
if (existPath(cachePath)) {
var _getStyleAndHash = getStyleAndHash(cachePath),
_getStyleAndHash2 = _slicedToArray(_getStyleAndHash, 2),
inlineCacheStyleStr = _getStyleAndHash2[0],
styleHash = _getStyleAndHash2[1];
if (inlineCacheStyleStr) {
return [inlineCacheStyleStr, tokenKey, styleHash, {}, clientOnly, order];
}
}
// Generate style
var styleObj = styleFn();
var _parseStyle5 = parseStyle(styleObj, {
hashId: hashId,
hashPriority: hashPriority,
layer: layer,
path: path.join('-'),
transformers: transformers,
linters: linters
}),
_parseStyle6 = _slicedToArray(_parseStyle5, 2),
parsedStyle = _parseStyle6[0],
effectStyle = _parseStyle6[1];
var styleStr = normalizeStyle(parsedStyle);
var styleId = uniqueHash(fullPath, styleStr);
return [styleStr, tokenKey, styleId, effectStyle, clientOnly, order];
},
// Remove cache if no need
function (_ref2, fromHMR) {
var _ref3 = _slicedToArray(_ref2, 3),
styleId = _ref3[2];
if ((fromHMR || autoClear) && isClientSide) {
removeCSS(styleId, {
mark: ATTR_MARK
});
}
},
// Effect: Inject style here
function (_ref4) {
var _ref5 = _slicedToArray(_ref4, 4),
styleStr = _ref5[0];
_ref5[1];
var styleId = _ref5[2],
effectStyle = _ref5[3];
if (isMergedClientSide && styleStr !== CSS_FILE_STYLE) {
var mergedCSSConfig = {
mark: ATTR_MARK,
prepend: 'queue',
attachTo: container,
priority: order
};
var nonceStr = typeof nonce === 'function' ? nonce() : nonce;
if (nonceStr) {
mergedCSSConfig.csp = {
nonce: nonceStr
};
}
var style = updateCSS(styleStr, styleId, mergedCSSConfig);
style[CSS_IN_JS_INSTANCE] = cache.instanceId;
// Used for `useCacheToken` to remove on batch when token removed
style.setAttribute(ATTR_TOKEN, tokenKey);
// Debug usage. Dev only
if (process.env.NODE_ENV !== 'production') {
style.setAttribute(ATTR_CACHE_PATH, fullPath.join('|'));
}
// Inject client side effect style
Object.keys(effectStyle).forEach(function (effectKey) {
updateCSS(normalizeStyle(effectStyle[effectKey]), "_effect-".concat(effectKey), mergedCSSConfig);
});
}
}),
_useGlobalCache2 = _slicedToArray(_useGlobalCache, 3),
cachedStyleStr = _useGlobalCache2[0],
cachedTokenKey = _useGlobalCache2[1],
cachedStyleId = _useGlobalCache2[2];
return function (node) {
var styleNode;
if (!ssrInline || isMergedClientSide || !defaultCache) {
styleNode = /*#__PURE__*/React.createElement(Empty, null);
} else {
var _ref6;
styleNode = /*#__PURE__*/React.createElement("style", _extends$1({}, (_ref6 = {}, _defineProperty$1(_ref6, ATTR_TOKEN, cachedTokenKey), _defineProperty$1(_ref6, ATTR_MARK, cachedStyleId), _ref6), {
dangerouslySetInnerHTML: {
__html: cachedStyleStr
}
}));
}
return /*#__PURE__*/React.createElement(React.Fragment, null, styleNode, node);
};
}
var extract$1 = function extract(cache, effectStyles, options) {
var _cache = _slicedToArray(cache, 6),
styleStr = _cache[0],
tokenKey = _cache[1],
styleId = _cache[2],
effectStyle = _cache[3],
clientOnly = _cache[4],
order = _cache[5];
var _ref7 = options || {},
plain = _ref7.plain;
// Skip client only style
if (clientOnly) {
return null;
}
var keyStyleText = styleStr;
// ====================== Style ======================
// Used for rc-util
var sharedAttrs = {
'data-rc-order': 'prependQueue',
'data-rc-priority': "".concat(order)
};
keyStyleText = toStyleStr(styleStr, tokenKey, styleId, sharedAttrs, plain);
// =============== Create effect style ===============
if (effectStyle) {
Object.keys(effectStyle).forEach(function (effectKey) {
// Effect style can be reused
if (!effectStyles[effectKey]) {
effectStyles[effectKey] = true;
var effectStyleStr = normalizeStyle(effectStyle[effectKey]);
keyStyleText += toStyleStr(effectStyleStr, tokenKey, "_effect-".concat(effectKey), sharedAttrs, plain);
}
});
}
return [order, styleId, keyStyleText];
};
var CSS_VAR_PREFIX = 'cssVar';
var extract = function extract(cache, effectStyles, options) {
var _cache = _slicedToArray(cache, 4),
styleStr = _cache[1],
styleId = _cache[2],
cssVarKey = _cache[3];
var _ref5 = options || {},
plain = _ref5.plain;
if (!styleStr) {
return null;
}
var order = -999;
// ====================== Style ======================
// Used for rc-util
var sharedAttrs = {
'data-rc-order': 'prependQueue',
'data-rc-priority': "".concat(order)
};
var styleText = toStyleStr(styleStr, cssVarKey, styleId, sharedAttrs, plain);
return [order, styleId, styleText];
};
var _ExtractStyleFns;
(_ExtractStyleFns = {}, _defineProperty$1(_ExtractStyleFns, STYLE_PREFIX, extract$1), _defineProperty$1(_ExtractStyleFns, TOKEN_PREFIX, extract$2), _defineProperty$1(_ExtractStyleFns, CSS_VAR_PREFIX, extract), _ExtractStyleFns);
var Keyframe = /*#__PURE__*/function () {
function Keyframe(name, style) {
_classCallCheck(this, Keyframe);
_defineProperty$1(this, "name", void 0);
_defineProperty$1(this, "style", void 0);
_defineProperty$1(this, "_keyframe", true);
this.name = name;
this.style = style;
}
_createClass(Keyframe, [{
key: "getName",
value: function getName() {
var hashId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
return hashId ? "".concat(hashId, "-").concat(this.name) : this.name;
}
}]);
return Keyframe;
}();
function noSplit(list) {
list.notSplit = true;
return list;
}
({
// Inset
inset: ['top', 'right', 'bottom', 'left'],
insetBlock: ['top', 'bottom'],
insetBlockStart: ['top'],
insetBlockEnd: ['bottom'],
insetInline: ['left', 'right'],
insetInlineStart: ['left'],
insetInlineEnd: ['right'],
// Margin
marginBlock: ['marginTop', 'marginBottom'],
marginBlockStart: ['marginTop'],
marginBlockEnd: ['marginBottom'],
marginInline: ['marginLeft', 'marginRight'],
marginInlineStart: ['marginLeft'],
marginInlineEnd: ['marginRight'],
// Padding
paddingBlock: ['paddingTop', 'paddingBottom'],
paddingBlockStart: ['paddingTop'],
paddingBlockEnd: ['paddingBottom'],
paddingInline: ['paddingLeft', 'paddingRight'],
paddingInlineStart: ['paddingLeft'],
paddingInlineEnd: ['paddingRight'],
// Border
borderBlock: noSplit(['borderTop', 'borderBottom']),
borderBlockStart: noSplit(['borderTop']),
borderBlockEnd: noSplit(['borderBottom']),
borderInline: noSplit(['borderLeft', 'borderRight']),
borderInlineStart: noSplit(['borderLeft']),
borderInlineEnd: noSplit(['borderRight']),
// Border width
borderBlockWidth: ['borderTopWidth', 'borderBottomWidth'],
borderBlockStartWidth: ['borderTopWidth'],
borderBlockEndWidth: ['borderBottomWidth'],
borderInlineWidth: ['borderLeftWidth', 'borderRightWidth'],
borderInlineStartWidth: ['borderLeftWidth'],
borderInlineEndWidth: ['borderRightWidth'],
// Border style
borderBlockStyle: ['borderTopStyle', 'borderBottomStyle'],
borderBlockStartStyle: ['borderTopStyle'],
borderBlockEndStyle: ['borderBottomStyle'],
borderInlineStyle: ['borderLeftStyle', 'borderRightStyle'],
borderInlineStartStyle: ['borderLeftStyle'],
borderInlineEndStyle: ['borderRightStyle'],
// Border color
borderBlockColor: ['borderTopColor', 'borderBottomColor'],
borderBlockStartColor: ['borderTopColor'],
borderBlockEndColor: ['borderBottomColor'],
borderInlineColor: ['borderLeftColor', 'borderRightColor'],
borderInlineStartColor: ['borderLeftColor'],
borderInlineEndColor: ['borderRightColor'],
// Border radius
borderStartStartRadius: ['borderTopLeftRadius'],
borderStartEndRadius: ['borderTopRightRadius'],
borderEndStartRadius: ['borderBottomLeftRadius'],
borderEndEndRadius: ['borderBottomRightRadius']
});
var IconContext = /*#__PURE__*/createContext({});
var Context$2 = IconContext;
var HOOK_MARK = 'RC_FORM_INTERNAL_HOOKS';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var warningFunc = function warningFunc() {
warningOnce(false, 'Can not find FormContext. Please make sure you wrap Field under Form.');
};
var Context$1 = /*#__PURE__*/React.createContext({
getFieldValue: warningFunc,
getFieldsValue: warningFunc,
getFieldError: warningFunc,
getFieldWarning: warningFunc,
getFieldsError: warningFunc,
isFieldsTouched: warningFunc,
isFieldTouched: warningFunc,
isFieldValidating: warningFunc,
isFieldsValidating: warningFunc,
resetFields: warningFunc,
setFields: warningFunc,
setFieldValue: warningFunc,
setFieldsValue: warningFunc,
validateFields: warningFunc,
submit: warningFunc,
getInternalHooks: function getInternalHooks() {
warningFunc();
return {
dispatch: warningFunc,
initEntityValue: warningFunc,
registerField: warningFunc,
useSubscribe: warningFunc,
setInitialValues: warningFunc,
destroyForm: warningFunc,
setCallbacks: warningFunc,
registerWatch: warningFunc,
getFields: warningFunc,
setValidateMessages: warningFunc,
setPreserve: warningFunc,
getInitialValue: warningFunc
};
}
});
function toArray(value) {
if (value === undefined || value === null) {
return [];
}
return Array.isArray(value) ? value : [value];
}
function _regeneratorRuntime() {
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
_regeneratorRuntime = function _regeneratorRuntime() {
return e;
};
var t,
e = {},
r = Object.prototype,
n = r.hasOwnProperty,
o = Object.defineProperty || function (t, e, r) {
t[e] = r.value;
},
i = "function" == typeof Symbol ? Symbol : {},
a = i.iterator || "@@iterator",
c = i.asyncIterator || "@@asyncIterator",
u = i.toStringTag || "@@toStringTag";
function define(t, e, r) {
return Object.defineProperty(t, e, {
value: r,
enumerable: !0,
configurable: !0,
writable: !0
}), t[e];
}
try {
define({}, "");
} catch (t) {
define = function define(t, e, r) {
return t[e] = r;
};
}
function wrap(t, e, r, n) {
var i = e && e.prototype instanceof Generator ? e : Generator,
a = Object.create(i.prototype),
c = new Context(n || []);
return o(a, "_invoke", {
value: makeInvokeMethod(t, r, c)
}), a;
}
function tryCatch(t, e, r) {
try {
return {
type: "normal",
arg: t.call(e, r)
};
} catch (t) {
return {
type: "throw",
arg: t
};
}
}
e.wrap = wrap;
var h = "suspendedStart",
l = "suspendedYield",
f = "executing",
s = "completed",
y = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var p = {};
define(p, a, function () {
return this;
});
var d = Object.getPrototypeOf,
v = d && d(d(values([])));
v && v !== r && n.call(v, a) && (p = v);
var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
function defineIteratorMethods(t) {
["next", "throw", "return"].forEach(function (e) {
define(t, e, function (t) {
return this._invoke(e, t);
});
});
}
function AsyncIterator(t, e) {
function invoke(r, o, i, a) {
var c = tryCatch(t[r], t, o);
if ("throw" !== c.type) {
var u = c.arg,
h = u.value;
return h && "object" == _typeof$1(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
invoke("next", t, i, a);
}, function (t) {
invoke("throw", t, i, a);
}) : e.resolve(h).then(function (t) {
u.value = t, i(u);
}, function (t) {
return invoke("throw", t, i, a);
});
}
a(c.arg);
}
var r;
o(this, "_invoke", {
value: function value(t, n) {
function callInvokeWithMethodAndArg() {
return new e(function (e, r) {
invoke(t, n, e, r);
});
}
return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
}
});
}
function makeInvokeMethod(e, r, n) {
var o = h;
return function (i, a) {
if (o === f) throw new Error("Generator is already running");
if (o === s) {
if ("throw" === i) throw a;
return {
value: t,
done: !0
};
}
for (n.method = i, n.arg = a;;) {
var c = n.delegate;
if (c) {
var u = maybeInvokeDelegate(c, n);
if (u) {
if (u === y) continue;
return u;
}
}
if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
if (o === h) throw o = s, n.arg;
n.dispatchException(n.arg);
} else "return" === n.method && n.abrupt("return", n.arg);
o = f;
var p = tryCatch(e, r, n);
if ("normal" === p.type) {
if (o = n.done ? s : l, p.arg === y) continue;
return {
value: p.arg,
done: n.done
};
}
"throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
}
};
}
function maybeInvokeDelegate(e, r) {
var n = r.method,
o = e.iterator[n];
if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
var i = tryCatch(o, e.iterator, r.arg);
if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
var a = i.arg;
return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
}
function pushTryEntry(t) {
var e = {
tryLoc: t[0]
};
1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
}
function resetTryEntry(t) {
var e = t.completion || {};
e.type = "normal", delete e.arg, t.completion = e;
}
function Context(t) {
this.tryEntries = [{
tryLoc: "root"
}], t.forEach(pushTryEntry, this), this.reset(!0);
}
function values(e) {
if (e || "" === e) {
var r = e[a];
if (r) return r.call(e);
if ("function" == typeof e.next) return e;
if (!isNaN(e.length)) {
var o = -1,
i = function next() {
for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
return next.value = t, next.done = !0, next;
};
return i.next = i;
}
}
throw new TypeError(_typeof$1(e) + " is not iterable");
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
value: GeneratorFunctionPrototype,
configurable: !0
}), o(GeneratorFunctionPrototype, "constructor", {
value: GeneratorFunction,
configurable: !0
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
var e = "function" == typeof t && t.constructor;
return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
}, e.mark = function (t) {
return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
}, e.awrap = function (t) {
return {
__await: t
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
return this;
}), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
void 0 === i && (i = Promise);
var a = new AsyncIterator(wrap(t, r, n, o), i);
return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
return t.done ? t.value : a.next();
});
}, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
return this;
}), define(g, "toString", function () {
return "[object Generator]";
}), e.keys = function (t) {
var e = Object(t),
r = [];
for (var n in e) r.push(n);
return r.reverse(), function next() {
for (; r.length;) {
var t = r.pop();
if (t in e) return next.value = t, next.done = !1, next;
}
return next.done = !0, next;
};
}, e.values = values, Context.prototype = {
constructor: Context,
reset: function reset(e) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
},
stop: function stop() {
this.done = !0;
var t = this.tryEntries[0].completion;
if ("throw" === t.type) throw t.arg;
return this.rval;
},
dispatchException: function dispatchException(e) {
if (this.done) throw e;
var r = this;
function handle(n, o) {
return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
}
for (var o = this.tryEntries.length - 1; o >= 0; --o) {
var i = this.tryEntries[o],
a = i.completion;
if ("root" === i.tryLoc) return handle("end");
if (i.tryLoc <= this.prev) {
var c = n.call(i, "catchLoc"),
u = n.call(i, "finallyLoc");
if (c && u) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
} else if (c) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
} else {
if (!u) throw new Error("try statement without catch or finally");
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
}
}
}
},
abrupt: function abrupt(t, e) {
for (var r = this.tryEntries.length - 1; r >= 0; --r) {
var o = this.tryEntries[r];
if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
var i = o;
break;
}
}
i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
var a = i ? i.completion : {};
return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
},
complete: function complete(t, e) {
if ("throw" === t.type) throw t.arg;
return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
},
finish: function finish(t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
}
},
"catch": function _catch(t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.tryLoc === t) {
var n = r.completion;
if ("throw" === n.type) {
var o = n.arg;
resetTryEntry(r);
}
return o;
}
}
throw new Error("illegal catch attempt");
},
delegateYield: function delegateYield(e, r, n) {
return this.delegate = {
iterator: values(e),
resultName: r,
nextLoc: n
}, "next" === this.method && (this.arg = t), y;
}
}, e;
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _extends() {
_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;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
_setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _construct(Parent, args, Class) {
if (_isNativeReflectConstruct()) {
_construct = Reflect.construct.bind();
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) _setPrototypeOf(instance, Class.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
function _isNativeFunction(fn) {
return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function _wrapNativeSuper(Class) {
var _cache = typeof Map === "function" ? new Map() : undefined;
_wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !_isNativeFunction(Class)) return Class;
if (typeof Class !== "function") {
throw new TypeError("Super expression must either be null or a function");
}
if (typeof _cache !== "undefined") {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return _construct(Class, arguments, _getPrototypeOf(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
});
return _setPrototypeOf(Wrapper, Class);
};
return _wrapNativeSuper(Class);
}
/* eslint no-console:0 */
var formatRegExp = /%[sdj%]/g;
var warning$3 = function warning() {}; // don't print warning message when in production env or node runtime
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV !== 'production' && typeof window !== 'undefined' && typeof document !== 'undefined') {
warning$3 = function warning(type, errors) {
if (typeof console !== 'undefined' && console.warn && typeof ASYNC_VALIDATOR_NO_WARNING === 'undefined') {
if (errors.every(function (e) {
return typeof e === 'string';
})) {
console.warn(type, errors);
}
}
};
}
function convertFieldsError(errors) {
if (!errors || !errors.length) return null;
var fields = {};
errors.forEach(function (error) {
var field = error.field;
fields[field] = fields[field] || [];
fields[field].push(error);
});
return fields;
}
function format(template) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var i = 0;
var len = args.length;
if (typeof template === 'function') {
return template.apply(null, args);
}
if (typeof template === 'string') {
var str = template.replace(formatRegExp, function (x) {
if (x === '%%') {
return '%';
}
if (i >= len) {
return x;
}
switch (x) {
case '%s':
return String(args[i++]);
case '%d':
return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
break;
default:
return x;
}
});
return str;
}
return template;
}
function isNativeStringType(type) {
return type === 'string' || type === 'url' || type === 'hex' || type === 'email' || type === 'date' || type === 'pattern';
}
function isEmptyValue(value, type) {
if (value === undefined || value === null) {
return true;
}
if (type === 'array' && Array.isArray(value) && !value.length) {
return true;
}
if (isNativeStringType(type) && typeof value === 'string' && !value) {
return true;
}
return false;
}
function asyncParallelArray(arr, func, callback) {
var results = [];
var total = 0;
var arrLength = arr.length;
function count(errors) {
results.push.apply(results, errors || []);
total++;
if (total === arrLength) {
callback(results);
}
}
arr.forEach(function (a) {
func(a, count);
});
}
function asyncSerialArray(arr, func, callback) {
var index = 0;
var arrLength = arr.length;
function next(errors) {
if (errors && errors.length) {
callback(errors);
return;
}
var original = index;
index = index + 1;
if (original < arrLength) {
func(arr[original], next);
} else {
callback([]);
}
}
next([]);
}
function flattenObjArr(objArr) {
var ret = [];
Object.keys(objArr).forEach(function (k) {
ret.push.apply(ret, objArr[k] || []);
});
return ret;
}
var AsyncValidationError = /*#__PURE__*/function (_Error) {
_inheritsLoose(AsyncValidationError, _Error);
function AsyncValidationError(errors, fields) {
var _this;
_this = _Error.call(this, 'Async Validation Error') || this;
_this.errors = errors;
_this.fields = fields;
return _this;
}
return AsyncValidationError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
function asyncMap(objArr, option, func, callback, source) {
if (option.first) {
var _pending = new Promise(function (resolve, reject) {
var next = function next(errors) {
callback(errors);
return errors.length ? reject(new AsyncValidationError(errors, convertFieldsError(errors))) : resolve(source);
};
var flattenArr = flattenObjArr(objArr);
asyncSerialArray(flattenArr, func, next);
});
_pending["catch"](function (e) {
return e;
});
return _pending;
}
var firstFields = option.firstFields === true ? Object.keys(objArr) : option.firstFields || [];
var objArrKeys = Object.keys(objArr);
var objArrLength = objArrKeys.length;
var total = 0;
var results = [];
var pending = new Promise(function (resolve, reject) {
var next = function next(errors) {
results.push.apply(results, errors);
total++;
if (total === objArrLength) {
callback(results);
return results.length ? reject(new AsyncValidationError(results, convertFieldsError(results))) : resolve(source);
}
};
if (!objArrKeys.length) {
callback(results);
resolve(source);
}
objArrKeys.forEach(function (key) {
var arr = objArr[key];
if (firstFields.indexOf(key) !== -1) {
asyncSerialArray(arr, func, next);
} else {
asyncParallelArray(arr, func, next);
}
});
});
pending["catch"](function (e) {
return e;
});
return pending;
}
function isErrorObj(obj) {
return !!(obj && obj.message !== undefined);
}
function getValue$2(value, path) {
var v = value;
for (var i = 0; i < path.length; i++) {
if (v == undefined) {
return v;
}
v = v[path[i]];
}
return v;
}
function complementError(rule, source) {
return function (oe) {
var fieldValue;
if (rule.fullFields) {
fieldValue = getValue$2(source, rule.fullFields);
} else {
fieldValue = source[oe.field || rule.fullField];
}
if (isErrorObj(oe)) {
oe.field = oe.field || rule.fullField;
oe.fieldValue = fieldValue;
return oe;
}
return {
message: typeof oe === 'function' ? oe() : oe,
fieldValue: fieldValue,
field: oe.field || rule.fullField
};
};
}
function deepMerge(target, source) {
if (source) {
for (var s in source) {
if (source.hasOwnProperty(s)) {
var value = source[s];
if (typeof value === 'object' && typeof target[s] === 'object') {
target[s] = _extends({}, target[s], value);
} else {
target[s] = value;
}
}
}
}
return target;
}
var required$1 = function required(rule, value, source, errors, options, type) {
if (rule.required && (!source.hasOwnProperty(rule.field) || isEmptyValue(value, type || rule.type))) {
errors.push(format(options.messages.required, rule.fullField));
}
};
/**
* Rule for validating whitespace.
*
* @param rule The validation rule.
* @param value The value of the field on the source object.
* @param source The source object being validated.
* @param errors An array of errors that this rule may add
* validation errors to.
* @param options The validation options.
* @param options.messages The validation messages.
*/
var whitespace = function whitespace(rule, value, source, errors, options) {
if (/^\s+$/.test(value) || value === '') {
errors.push(format(options.messages.whitespace, rule.fullField));
}
};
// https://github.com/kevva/url-regex/blob/master/index.js
var urlReg;
var getUrlRegex = function () {
if (urlReg) {
return urlReg;
}
var word = '[a-fA-F\\d:]';
var b = function b(options) {
return options && options.includeBoundaries ? "(?:(?<=\\s|^)(?=" + word + ")|(?<=" + word + ")(?=\\s|$))" : '';
};
var v4 = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}';
var v6seg = '[a-fA-F\\d]{1,4}';
var v6 = ("\n(?:\n(?:" + v6seg + ":){7}(?:" + v6seg + "|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:" + v6seg + ":){6}(?:" + v4 + "|:" + v6seg + "|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:" + v6seg + ":){5}(?::" + v4 + "|(?::" + v6seg + "){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:" + v6seg + ":){4}(?:(?::" + v6seg + "){0,1}:" + v4 + "|(?::" + v6seg + "){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:" + v6seg + ":){3}(?:(?::" + v6seg + "){0,2}:" + v4 + "|(?::" + v6seg + "){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:" + v6seg + ":){2}(?:(?::" + v6seg + "){0,3}:" + v4 + "|(?::" + v6seg + "){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:" + v6seg + ":){1}(?:(?::" + v6seg + "){0,4}:" + v4 + "|(?::" + v6seg + "){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::" + v6seg + "){0,5}:" + v4 + "|(?::" + v6seg + "){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n").replace(/\s*\/\/.*$/gm, '').replace(/\n/g, '').trim(); // Pre-compile only the exact regexes because adding a global flag make regexes stateful
var v46Exact = new RegExp("(?:^" + v4 + "$)|(?:^" + v6 + "$)");
var v4exact = new RegExp("^" + v4 + "$");
var v6exact = new RegExp("^" + v6 + "$");
var ip = function ip(options) {
return options && options.exact ? v46Exact : new RegExp("(?:" + b(options) + v4 + b(options) + ")|(?:" + b(options) + v6 + b(options) + ")", 'g');
};
ip.v4 = function (options) {
return options && options.exact ? v4exact : new RegExp("" + b(options) + v4 + b(options), 'g');
};
ip.v6 = function (options) {
return options && options.exact ? v6exact : new RegExp("" + b(options) + v6 + b(options), 'g');
};
var protocol = "(?:(?:[a-z]+:)?//)";
var auth = '(?:\\S+(?::\\S*)?@)?';
var ipv4 = ip.v4().source;
var ipv6 = ip.v6().source;
var host = "(?:(?:[a-z\\u00a1-\\uffff0-9][-_]*)*[a-z\\u00a1-\\uffff0-9]+)";
var domain = "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*";
var tld = "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))";
var port = '(?::\\d{2,5})?';
var path = '(?:[/?#][^\\s"]*)?';
var regex = "(?:" + protocol + "|www\\.)" + auth + "(?:localhost|" + ipv4 + "|" + ipv6 + "|" + host + domain + tld + ")" + port + path;
urlReg = new RegExp("(?:^" + regex + "$)", 'i');
return urlReg;
};
/* eslint max-len:0 */
var pattern$2 = {
// http://emailregex.com/
email: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+\.)+[a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}))$/,
// url: new RegExp(
// '^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$',
// 'i',
// ),
hex: /^#?([a-f0-9]{6}|[a-f0-9]{3})$/i
};
var types = {
integer: function integer(value) {
return types.number(value) && parseInt(value, 10) === value;
},
"float": function float(value) {
return types.number(value) && !types.integer(value);
},
array: function array(value) {
return Array.isArray(value);
},
regexp: function regexp(value) {
if (value instanceof RegExp) {
return true;
}
try {
return !!new RegExp(value);
} catch (e) {
return false;
}
},
date: function date(value) {
return typeof value.getTime === 'function' && typeof value.getMonth === 'function' && typeof value.getYear === 'function' && !isNaN(value.getTime());
},
number: function number(value) {
if (isNaN(value)) {
return false;
}
return typeof value === 'number';
},
object: function object(value) {
return typeof value === 'object' && !types.array(value);
},
method: function method(value) {
return typeof value === 'function';
},
email: function email(value) {
return typeof value === 'string' && value.length <= 320 && !!value.match(pattern$2.email);
},
url: function url(value) {
return typeof value === 'string' && value.length <= 2048 && !!value.match(getUrlRegex());
},
hex: function hex(value) {
return typeof value === 'string' && !!value.match(pattern$2.hex);
}
};
var type$1 = function type(rule, value, source, errors, options) {
if (rule.required && value === undefined) {
required$1(rule, value, source, errors, options);
return;
}
var custom = ['integer', 'float', 'array', 'regexp', 'object', 'method', 'email', 'number', 'date', 'url', 'hex'];
var ruleType = rule.type;
if (custom.indexOf(ruleType) > -1) {
if (!types[ruleType](value)) {
errors.push(format(options.messages.types[ruleType], rule.fullField, rule.type));
} // straight typeof check
} else if (ruleType && typeof value !== rule.type) {
errors.push(format(options.messages.types[ruleType], rule.fullField, rule.type));
}
};
var range = function range(rule, value, source, errors, options) {
var len = typeof rule.len === 'number';
var min = typeof rule.min === 'number';
var max = typeof rule.max === 'number'; // 正则匹配码点范围从U+010000一直到U+10FFFF的文字(补充平面Supplementary Plane)
var spRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
var val = value;
var key = null;
var num = typeof value === 'number';
var str = typeof value === 'string';
var arr = Array.isArray(value);
if (num) {
key = 'number';
} else if (str) {
key = 'string';
} else if (arr) {
key = 'array';
} // if the value is not of a supported type for range validation
// the validation rule rule should use the
// type property to also test for a particular type
if (!key) {
return false;
}
if (arr) {
val = value.length;
}
if (str) {
// 处理码点大于U+010000的文字length属性不准确的bug,如"𠮷𠮷𠮷".lenght !== 3
val = value.replace(spRegexp, '_').length;
}
if (len) {
if (val !== rule.len) {
errors.push(format(options.messages[key].len, rule.fullField, rule.len));
}
} else if (min && !max && val < rule.min) {
errors.push(format(options.messages[key].min, rule.fullField, rule.min));
} else if (max && !min && val > rule.max) {
errors.push(format(options.messages[key].max, rule.fullField, rule.max));
} else if (min && max && (val < rule.min || val > rule.max)) {
errors.push(format(options.messages[key].range, rule.fullField, rule.min, rule.max));
}
};
var ENUM$1 = 'enum';
var enumerable$1 = function enumerable(rule, value, source, errors, options) {
rule[ENUM$1] = Array.isArray(rule[ENUM$1]) ? rule[ENUM$1] : [];
if (rule[ENUM$1].indexOf(value) === -1) {
errors.push(format(options.messages[ENUM$1], rule.fullField, rule[ENUM$1].join(', ')));
}
};
var pattern$1 = function pattern(rule, value, source, errors, options) {
if (rule.pattern) {
if (rule.pattern instanceof RegExp) {
// if a RegExp instance is passed, reset `lastIndex` in case its `global`
// flag is accidentally set to `true`, which in a validation scenario
// is not necessary and the result might be misleading
rule.pattern.lastIndex = 0;
if (!rule.pattern.test(value)) {
errors.push(format(options.messages.pattern.mismatch, rule.fullField, value, rule.pattern));
}
} else if (typeof rule.pattern === 'string') {
var _pattern = new RegExp(rule.pattern);
if (!_pattern.test(value)) {
errors.push(format(options.messages.pattern.mismatch, rule.fullField, value, rule.pattern));
}
}
}
};
var rules = {
required: required$1,
whitespace: whitespace,
type: type$1,
range: range,
"enum": enumerable$1,
pattern: pattern$1
};
var string = function string(rule, value, callback, source, options) {
var errors = [];
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
if (validate) {
if (isEmptyValue(value, 'string') && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options, 'string');
if (!isEmptyValue(value, 'string')) {
rules.type(rule, value, source, errors, options);
rules.range(rule, value, source, errors, options);
rules.pattern(rule, value, source, errors, options);
if (rule.whitespace === true) {
rules.whitespace(rule, value, source, errors, options);
}
}
}
callback(errors);
};
var method = function method(rule, value, callback, source, options) {
var errors = [];
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
if (validate) {
if (isEmptyValue(value) && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options);
if (value !== undefined) {
rules.type(rule, value, source, errors, options);
}
}
callback(errors);
};
var number = function number(rule, value, callback, source, options) {
var errors = [];
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
if (validate) {
if (value === '') {
value = undefined;
}
if (isEmptyValue(value) && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options);
if (value !== undefined) {
rules.type(rule, value, source, errors, options);
rules.range(rule, value, source, errors, options);
}
}
callback(errors);
};
var _boolean = function _boolean(rule, value, callback, source, options) {
var errors = [];
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
if (validate) {
if (isEmptyValue(value) && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options);
if (value !== undefined) {
rules.type(rule, value, source, errors, options);
}
}
callback(errors);
};
var regexp = function regexp(rule, value, callback, source, options) {
var errors = [];
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
if (validate) {
if (isEmptyValue(value) && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options);
if (!isEmptyValue(value)) {
rules.type(rule, value, source, errors, options);
}
}
callback(errors);
};
var integer = function integer(rule, value, callback, source, options) {
var errors = [];
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
if (validate) {
if (isEmptyValue(value) && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options);
if (value !== undefined) {
rules.type(rule, value, source, errors, options);
rules.range(rule, value, source, errors, options);
}
}
callback(errors);
};
var floatFn = function floatFn(rule, value, callback, source, options) {
var errors = [];
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
if (validate) {
if (isEmptyValue(value) && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options);
if (value !== undefined) {
rules.type(rule, value, source, errors, options);
rules.range(rule, value, source, errors, options);
}
}
callback(errors);
};
var array = function array(rule, value, callback, source, options) {
var errors = [];
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
if (validate) {
if ((value === undefined || value === null) && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options, 'array');
if (value !== undefined && value !== null) {
rules.type(rule, value, source, errors, options);
rules.range(rule, value, source, errors, options);
}
}
callback(errors);
};
var object = function object(rule, value, callback, source, options) {
var errors = [];
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
if (validate) {
if (isEmptyValue(value) && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options);
if (value !== undefined) {
rules.type(rule, value, source, errors, options);
}
}
callback(errors);
};
var ENUM = 'enum';
var enumerable = function enumerable(rule, value, callback, source, options) {
var errors = [];
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
if (validate) {
if (isEmptyValue(value) && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options);
if (value !== undefined) {
rules[ENUM](rule, value, source, errors, options);
}
}
callback(errors);
};
var pattern = function pattern(rule, value, callback, source, options) {
var errors = [];
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
if (validate) {
if (isEmptyValue(value, 'string') && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options);
if (!isEmptyValue(value, 'string')) {
rules.pattern(rule, value, source, errors, options);
}
}
callback(errors);
};
var date = function date(rule, value, callback, source, options) {
// console.log('integer rule called %j', rule);
var errors = [];
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field); // console.log('validate on %s value', value);
if (validate) {
if (isEmptyValue(value, 'date') && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options);
if (!isEmptyValue(value, 'date')) {
var dateObject;
if (value instanceof Date) {
dateObject = value;
} else {
dateObject = new Date(value);
}
rules.type(rule, dateObject, source, errors, options);
if (dateObject) {
rules.range(rule, dateObject.getTime(), source, errors, options);
}
}
}
callback(errors);
};
var required = function required(rule, value, callback, source, options) {
var errors = [];
var type = Array.isArray(value) ? 'array' : typeof value;
rules.required(rule, value, source, errors, options, type);
callback(errors);
};
var type = function type(rule, value, callback, source, options) {
var ruleType = rule.type;
var errors = [];
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
if (validate) {
if (isEmptyValue(value, ruleType) && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options, ruleType);
if (!isEmptyValue(value, ruleType)) {
rules.type(rule, value, source, errors, options);
}
}
callback(errors);
};
var any = function any(rule, value, callback, source, options) {
var errors = [];
var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
if (validate) {
if (isEmptyValue(value) && !rule.required) {
return callback();
}
rules.required(rule, value, source, errors, options);
}
callback(errors);
};
var validators = {
string: string,
method: method,
number: number,
"boolean": _boolean,
regexp: regexp,
integer: integer,
"float": floatFn,
array: array,
object: object,
"enum": enumerable,
pattern: pattern,
date: date,
url: type,
hex: type,
email: type,
required: required,
any: any
};
function newMessages() {
return {
"default": 'Validation error on field %s',
required: '%s is required',
"enum": '%s must be one of %s',
whitespace: '%s cannot be empty',
date: {
format: '%s date %s is invalid for format %s',
parse: '%s date could not be parsed, %s is invalid ',
invalid: '%s date %s is invalid'
},
types: {
string: '%s is not a %s',
method: '%s is not a %s (function)',
array: '%s is not an %s',
object: '%s is not an %s',
number: '%s is not a %s',
date: '%s is not a %s',
"boolean": '%s is not a %s',
integer: '%s is not an %s',
"float": '%s is not a %s',
regexp: '%s is not a valid %s',
email: '%s is not a valid %s',
url: '%s is not a valid %s',
hex: '%s is not a valid %s'
},
string: {
len: '%s must be exactly %s characters',
min: '%s must be at least %s characters',
max: '%s cannot be longer than %s characters',
range: '%s must be between %s and %s characters'
},
number: {
len: '%s must equal %s',
min: '%s cannot be less than %s',
max: '%s cannot be greater than %s',
range: '%s must be between %s and %s'
},
array: {
len: '%s must be exactly %s in length',
min: '%s cannot be less than %s in length',
max: '%s cannot be greater than %s in length',
range: '%s must be between %s and %s in length'
},
pattern: {
mismatch: '%s value %s does not match pattern %s'
},
clone: function clone() {
var cloned = JSON.parse(JSON.stringify(this));
cloned.clone = this.clone;
return cloned;
}
};
}
var messages = newMessages();
/**
* Encapsulates a validation schema.
*
* @param descriptor An object declaring validation rules
* for this schema.
*/
var Schema = /*#__PURE__*/function () {
// ========================= Static =========================
// ======================== Instance ========================
function Schema(descriptor) {
this.rules = null;
this._messages = messages;
this.define(descriptor);
}
var _proto = Schema.prototype;
_proto.define = function define(rules) {
var _this = this;
if (!rules) {
throw new Error('Cannot configure a schema with no rules');
}
if (typeof rules !== 'object' || Array.isArray(rules)) {
throw new Error('Rules must be an object');
}
this.rules = {};
Object.keys(rules).forEach(function (name) {
var item = rules[name];
_this.rules[name] = Array.isArray(item) ? item : [item];
});
};
_proto.messages = function messages(_messages) {
if (_messages) {
this._messages = deepMerge(newMessages(), _messages);
}
return this._messages;
};
_proto.validate = function validate(source_, o, oc) {
var _this2 = this;
if (o === void 0) {
o = {};
}
if (oc === void 0) {
oc = function oc() {};
}
var source = source_;
var options = o;
var callback = oc;
if (typeof options === 'function') {
callback = options;
options = {};
}
if (!this.rules || Object.keys(this.rules).length === 0) {
if (callback) {
callback(null, source);
}
return Promise.resolve(source);
}
function complete(results) {
var errors = [];
var fields = {};
function add(e) {
if (Array.isArray(e)) {
var _errors;
errors = (_errors = errors).concat.apply(_errors, e);
} else {
errors.push(e);
}
}
for (var i = 0; i < results.length; i++) {
add(results[i]);
}
if (!errors.length) {
callback(null, source);
} else {
fields = convertFieldsError(errors);
callback(errors, fields);
}
}
if (options.messages) {
var messages$1 = this.messages();
if (messages$1 === messages) {
messages$1 = newMessages();
}
deepMerge(messages$1, options.messages);
options.messages = messages$1;
} else {
options.messages = this.messages();
}
var series = {};
var keys = options.keys || Object.keys(this.rules);
keys.forEach(function (z) {
var arr = _this2.rules[z];
var value = source[z];
arr.forEach(function (r) {
var rule = r;
if (typeof rule.transform === 'function') {
if (source === source_) {
source = _extends({}, source);
}
value = source[z] = rule.transform(value);
}
if (typeof rule === 'function') {
rule = {
validator: rule
};
} else {
rule = _extends({}, rule);
} // Fill validator. Skip if nothing need to validate
rule.validator = _this2.getValidationMethod(rule);
if (!rule.validator) {
return;
}
rule.field = z;
rule.fullField = rule.fullField || z;
rule.type = _this2.getType(rule);
series[z] = series[z] || [];
series[z].push({
rule: rule,
value: value,
source: source,
field: z
});
});
});
var errorFields = {};
return asyncMap(series, options, function (data, doIt) {
var rule = data.rule;
var deep = (rule.type === 'object' || rule.type === 'array') && (typeof rule.fields === 'object' || typeof rule.defaultField === 'object');
deep = deep && (rule.required || !rule.required && data.value);
rule.field = data.field;
function addFullField(key, schema) {
return _extends({}, schema, {
fullField: rule.fullField + "." + key,
fullFields: rule.fullFields ? [].concat(rule.fullFields, [key]) : [key]
});
}
function cb(e) {
if (e === void 0) {
e = [];
}
var errorList = Array.isArray(e) ? e : [e];
if (!options.suppressWarning && errorList.length) {
Schema.warning('async-validator:', errorList);
}
if (errorList.length && rule.message !== undefined) {
errorList = [].concat(rule.message);
} // Fill error info
var filledErrors = errorList.map(complementError(rule, source));
if (options.first && filledErrors.length) {
errorFields[rule.field] = 1;
return doIt(filledErrors);
}
if (!deep) {
doIt(filledErrors);
} else {
// if rule is required but the target object
// does not exist fail at the rule level and don't
// go deeper
if (rule.required && !data.value) {
if (rule.message !== undefined) {
filledErrors = [].concat(rule.message).map(complementError(rule, source));
} else if (options.error) {
filledErrors = [options.error(rule, format(options.messages.required, rule.field))];
}
return doIt(filledErrors);
}
var fieldsSchema = {};
if (rule.defaultField) {
Object.keys(data.value).map(function (key) {
fieldsSchema[key] = rule.defaultField;
});
}
fieldsSchema = _extends({}, fieldsSchema, data.rule.fields);
var paredFieldsSchema = {};
Object.keys(fieldsSchema).forEach(function (field) {
var fieldSchema = fieldsSchema[field];
var fieldSchemaList = Array.isArray(fieldSchema) ? fieldSchema : [fieldSchema];
paredFieldsSchema[field] = fieldSchemaList.map(addFullField.bind(null, field));
});
var schema = new Schema(paredFieldsSchema);
schema.messages(options.messages);
if (data.rule.options) {
data.rule.options.messages = options.messages;
data.rule.options.error = options.error;
}
schema.validate(data.value, data.rule.options || options, function (errs) {
var finalErrors = [];
if (filledErrors && filledErrors.length) {
finalErrors.push.apply(finalErrors, filledErrors);
}
if (errs && errs.length) {
finalErrors.push.apply(finalErrors, errs);
}
doIt(finalErrors.length ? finalErrors : null);
});
}
}
var res;
if (rule.asyncValidator) {
res = rule.asyncValidator(rule, data.value, cb, data.source, options);
} else if (rule.validator) {
try {
res = rule.validator(rule, data.value, cb, data.source, options);
} catch (error) {
console.error == null ? void 0 : console.error(error); // rethrow to report error
if (!options.suppressValidatorError) {
setTimeout(function () {
throw error;
}, 0);
}
cb(error.message);
}
if (res === true) {
cb();
} else if (res === false) {
cb(typeof rule.message === 'function' ? rule.message(rule.fullField || rule.field) : rule.message || (rule.fullField || rule.field) + " fails");
} else if (res instanceof Array) {
cb(res);
} else if (res instanceof Error) {
cb(res.message);
}
}
if (res && res.then) {
res.then(function () {
return cb();
}, function (e) {
return cb(e);
});
}
}, function (results) {
complete(results);
}, source);
};
_proto.getType = function getType(rule) {
if (rule.type === undefined && rule.pattern instanceof RegExp) {
rule.type = 'pattern';
}
if (typeof rule.validator !== 'function' && rule.type && !validators.hasOwnProperty(rule.type)) {
throw new Error(format('Unknown rule type %s', rule.type));
}
return rule.type || 'string';
};
_proto.getValidationMethod = function getValidationMethod(rule) {
if (typeof rule.validator === 'function') {
return rule.validator;
}
var keys = Object.keys(rule);
var messageIndex = keys.indexOf('message');
if (messageIndex !== -1) {
keys.splice(messageIndex, 1);
}
if (keys.length === 1 && keys[0] === 'required') {
return validators.required;
}
return validators[this.getType(rule)] || undefined;
};
return Schema;
}();
Schema.register = function register(type, validator) {
if (typeof validator !== 'function') {
throw new Error('Cannot register a validator by type, validator is not a function');
}
validators[type] = validator;
};
Schema.warning = warning$3;
Schema.messages = messages;
Schema.validators = validators;
var typeTemplate$1 = "'${name}' is not a valid ${type}";
var defaultValidateMessages = {
default: "Validation error on field '${name}'",
required: "'${name}' is required",
enum: "'${name}' must be one of [${enum}]",
whitespace: "'${name}' cannot be empty",
date: {
format: "'${name}' is invalid for format date",
parse: "'${name}' could not be parsed as date",
invalid: "'${name}' is invalid date"
},
types: {
string: typeTemplate$1,
method: typeTemplate$1,
array: typeTemplate$1,
object: typeTemplate$1,
number: typeTemplate$1,
date: typeTemplate$1,
boolean: typeTemplate$1,
integer: typeTemplate$1,
float: typeTemplate$1,
regexp: typeTemplate$1,
email: typeTemplate$1,
url: typeTemplate$1,
hex: typeTemplate$1
},
string: {
len: "'${name}' must be exactly ${len} characters",
min: "'${name}' must be at least ${min} characters",
max: "'${name}' cannot be longer than ${max} characters",
range: "'${name}' must be between ${min} and ${max} characters"
},
number: {
len: "'${name}' must equal ${len}",
min: "'${name}' cannot be less than ${min}",
max: "'${name}' cannot be greater than ${max}",
range: "'${name}' must be between ${min} and ${max}"
},
array: {
len: "'${name}' must be exactly ${len} in length",
min: "'${name}' cannot be less than ${min} in length",
max: "'${name}' cannot be greater than ${max} in length",
range: "'${name}' must be between ${min} and ${max} in length"
},
pattern: {
mismatch: "'${name}' does not match pattern ${pattern}"
}
};
function get(entity, path) {
var current = entity;
for (var i = 0; i < path.length; i += 1) {
if (current === null || current === undefined) {
return undefined;
}
current = current[path[i]];
}
return current;
}
function _toArray(arr) {
return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest();
}
function internalSet(entity, paths, value, removeIfUndefined) {
if (!paths.length) {
return value;
}
var _paths = _toArray(paths),
path = _paths[0],
restPath = _paths.slice(1);
var clone;
if (!entity && typeof path === 'number') {
clone = [];
} else if (Array.isArray(entity)) {
clone = _toConsumableArray(entity);
} else {
clone = _objectSpread2$1({}, entity);
}
// Delete prop if `removeIfUndefined` and value is undefined
if (removeIfUndefined && value === undefined && restPath.length === 1) {
delete clone[path][restPath[0]];
} else {
clone[path] = internalSet(clone[path], restPath, value, removeIfUndefined);
}
return clone;
}
function set(entity, paths, value) {
var removeIfUndefined = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
// Do nothing if `removeIfUndefined` and parent object not exist
if (paths.length && removeIfUndefined && value === undefined && !get(entity, paths.slice(0, -1))) {
return entity;
}
return internalSet(entity, paths, value, removeIfUndefined);
}
function cloneDeep(val) {
if (Array.isArray(val)) {
return cloneArrayDeep(val);
} else if (_typeof$1(val) === 'object' && val !== null) {
return cloneObjectDeep(val);
}
return val;
}
function cloneObjectDeep(val) {
if (Object.getPrototypeOf(val) === Object.prototype) {
var res = {};
for (var key in val) {
res[key] = cloneDeep(val[key]);
}
return res;
}
return val;
}
function cloneArrayDeep(val) {
return val.map(function (item) {
return cloneDeep(item);
});
}
/**
* Convert name to internal supported format.
* This function should keep since we still thinking if need support like `a.b.c` format.
* 'a' => ['a']
* 123 => [123]
* ['a', 123] => ['a', 123]
*/
function getNamePath(path) {
return toArray(path);
}
function getValue$1(store, namePath) {
var value = get(store, namePath);
return value;
}
function setValue(store, namePath, value) {
var removeIfUndefined = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var newStore = set(store, namePath, value, removeIfUndefined);
return newStore;
}
function cloneByNamePathList(store, namePathList) {
var newStore = {};
namePathList.forEach(function (namePath) {
var value = getValue$1(store, namePath);
newStore = setValue(newStore, namePath, value);
});
return newStore;
}
function containsNamePath(namePathList, namePath) {
return namePathList && namePathList.some(function (path) {
return matchNamePath(path, namePath);
});
}
function isObject(obj) {
return _typeof$1(obj) === 'object' && obj !== null && Object.getPrototypeOf(obj) === Object.prototype;
}
/**
* Copy values into store and return a new values object
* ({ a: 1, b: { c: 2 } }, { a: 4, b: { d: 5 } }) => { a: 4, b: { c: 2, d: 5 } }
*/
function internalSetValues(store, values) {
var newStore = Array.isArray(store) ? _toConsumableArray(store) : _objectSpread2$1({}, store);
if (!values) {
return newStore;
}
Object.keys(values).forEach(function (key) {
var prevValue = newStore[key];
var value = values[key];
// If both are object (but target is not array), we use recursion to set deep value
var recursive = isObject(prevValue) && isObject(value);
newStore[key] = recursive ? internalSetValues(prevValue, value || {}) : cloneDeep(value); // Clone deep for arrays
});
return newStore;
}
function setValues(store) {
for (var _len = arguments.length, restValues = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
restValues[_key - 1] = arguments[_key];
}
return restValues.reduce(function (current, newStore) {
return internalSetValues(current, newStore);
}, store);
}
function matchNamePath(namePath, changedNamePath) {
if (!namePath || !changedNamePath || namePath.length !== changedNamePath.length) {
return false;
}
return namePath.every(function (nameUnit, i) {
return changedNamePath[i] === nameUnit;
});
}
function isSimilar(source, target) {
if (source === target) {
return true;
}
if (!source && target || source && !target) {
return false;
}
if (!source || !target || _typeof$1(source) !== 'object' || _typeof$1(target) !== 'object') {
return false;
}
var sourceKeys = Object.keys(source);
var targetKeys = Object.keys(target);
var keys = new Set([].concat(sourceKeys, targetKeys));
return _toConsumableArray(keys).every(function (key) {
var sourceValue = source[key];
var targetValue = target[key];
if (typeof sourceValue === 'function' && typeof targetValue === 'function') {
return true;
}
return sourceValue === targetValue;
});
}
function defaultGetValueFromEvent(valuePropName) {
var event = arguments.length <= 1 ? undefined : arguments[1];
if (event && event.target && _typeof$1(event.target) === 'object' && valuePropName in event.target) {
return event.target[valuePropName];
}
return event;
}
/**
* Moves an array item from one position in an array to another.
*
* Note: This is a pure function so a new array will be returned, instead
* of altering the array argument.
*
* @param array Array in which to move an item. (required)
* @param moveIndex The index of the item to move. (required)
* @param toIndex The index to move item at moveIndex to. (required)
*/
function move(array, moveIndex, toIndex) {
var length = array.length;
if (moveIndex < 0 || moveIndex >= length || toIndex < 0 || toIndex >= length) {
return array;
}
var item = array[moveIndex];
var diff = moveIndex - toIndex;
if (diff > 0) {
// move left
return [].concat(_toConsumableArray(array.slice(0, toIndex)), [item], _toConsumableArray(array.slice(toIndex, moveIndex)), _toConsumableArray(array.slice(moveIndex + 1, length)));
}
if (diff < 0) {
// move right
return [].concat(_toConsumableArray(array.slice(0, moveIndex)), _toConsumableArray(array.slice(moveIndex + 1, toIndex + 1)), [item], _toConsumableArray(array.slice(toIndex + 1, length)));
}
return array;
}
// Remove incorrect original ts define
var AsyncValidator = Schema;
/**
* Replace with template.
* `I'm ${name}` + { name: 'bamboo' } = I'm bamboo
*/
function replaceMessage(template, kv) {
return template.replace(/\$\{\w+\}/g, function (str) {
var key = str.slice(2, -1);
return kv[key];
});
}
var CODE_LOGIC_ERROR = 'CODE_LOGIC_ERROR';
function validateRule(_x, _x2, _x3, _x4, _x5) {
return _validateRule.apply(this, arguments);
}
/**
* We use `async-validator` to validate the value.
* But only check one value in a time to avoid namePath validate issue.
*/
function _validateRule() {
_validateRule = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(name, value, rule, options, messageVariables) {
var cloneRule, originValidator, subRuleField, validator, messages, result, subResults, kv, fillVariableResult;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
cloneRule = _objectSpread2$1({}, rule); // Bug of `async-validator`
// https://github.com/react-component/field-form/issues/316
// https://github.com/react-component/field-form/issues/313
delete cloneRule.ruleIndex;
if (cloneRule.validator) {
originValidator = cloneRule.validator;
cloneRule.validator = function () {
try {
return originValidator.apply(void 0, arguments);
} catch (error) {
console.error(error);
return Promise.reject(CODE_LOGIC_ERROR);
}
};
}
// We should special handle array validate
subRuleField = null;
if (cloneRule && cloneRule.type === 'array' && cloneRule.defaultField) {
subRuleField = cloneRule.defaultField;
delete cloneRule.defaultField;
}
validator = new AsyncValidator(_defineProperty$1({}, name, [cloneRule]));
messages = setValues({}, defaultValidateMessages, options.validateMessages);
validator.messages(messages);
result = [];
_context2.prev = 9;
_context2.next = 12;
return Promise.resolve(validator.validate(_defineProperty$1({}, name, value), _objectSpread2$1({}, options)));
case 12:
_context2.next = 17;
break;
case 14:
_context2.prev = 14;
_context2.t0 = _context2["catch"](9);
if (_context2.t0.errors) {
result = _context2.t0.errors.map(function (_ref4, index) {
var message = _ref4.message;
var mergedMessage = message === CODE_LOGIC_ERROR ? messages.default : message;
return /*#__PURE__*/React.isValidElement(mergedMessage) ? /*#__PURE__*/
// Wrap ReactNode with `key`
React.cloneElement(mergedMessage, {
key: "error_".concat(index)
}) : mergedMessage;
});
}
case 17:
if (!(!result.length && subRuleField)) {
_context2.next = 22;
break;
}
_context2.next = 20;
return Promise.all(value.map(function (subValue, i) {
return validateRule("".concat(name, ".").concat(i), subValue, subRuleField, options, messageVariables);
}));
case 20:
subResults = _context2.sent;
return _context2.abrupt("return", subResults.reduce(function (prev, errors) {
return [].concat(_toConsumableArray(prev), _toConsumableArray(errors));
}, []));
case 22:
// Replace message with variables
kv = _objectSpread2$1(_objectSpread2$1({}, rule), {}, {
name: name,
enum: (rule.enum || []).join(', ')
}, messageVariables);
fillVariableResult = result.map(function (error) {
if (typeof error === 'string') {
return replaceMessage(error, kv);
}
return error;
});
return _context2.abrupt("return", fillVariableResult);
case 25:
case "end":
return _context2.stop();
}
}, _callee2, null, [[9, 14]]);
}));
return _validateRule.apply(this, arguments);
}
function validateRules(namePath, value, rules, options, validateFirst, messageVariables) {
var name = namePath.join('.');
// Fill rule with context
var filledRules = rules.map(function (currentRule, ruleIndex) {
var originValidatorFunc = currentRule.validator;
var cloneRule = _objectSpread2$1(_objectSpread2$1({}, currentRule), {}, {
ruleIndex: ruleIndex
});
// Replace validator if needed
if (originValidatorFunc) {
cloneRule.validator = function (rule, val, callback) {
var hasPromise = false;
// Wrap callback only accept when promise not provided
var wrappedCallback = function wrappedCallback() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// Wait a tick to make sure return type is a promise
Promise.resolve().then(function () {
warningOnce(!hasPromise, 'Your validator function has already return a promise. `callback` will be ignored.');
if (!hasPromise) {
callback.apply(void 0, args);
}
});
};
// Get promise
var promise = originValidatorFunc(rule, val, wrappedCallback);
hasPromise = promise && typeof promise.then === 'function' && typeof promise.catch === 'function';
/**
* 1. Use promise as the first priority.
* 2. If promise not exist, use callback with warning instead
*/
warningOnce(hasPromise, '`callback` is deprecated. Please return a promise instead.');
if (hasPromise) {
promise.then(function () {
callback();
}).catch(function (err) {
callback(err || ' ');
});
}
};
}
return cloneRule;
}).sort(function (_ref, _ref2) {
var w1 = _ref.warningOnly,
i1 = _ref.ruleIndex;
var w2 = _ref2.warningOnly,
i2 = _ref2.ruleIndex;
if (!!w1 === !!w2) {
// Let keep origin order
return i1 - i2;
}
if (w1) {
return 1;
}
return -1;
});
// Do validate rules
var summaryPromise;
if (validateFirst === true) {
// >>>>> Validate by serialization
summaryPromise = new Promise( /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(resolve, reject) {
var i, rule, errors;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
i = 0;
case 1:
if (!(i < filledRules.length)) {
_context.next = 12;
break;
}
rule = filledRules[i];
_context.next = 5;
return validateRule(name, value, rule, options, messageVariables);
case 5:
errors = _context.sent;
if (!errors.length) {
_context.next = 9;
break;
}
reject([{
errors: errors,
rule: rule
}]);
return _context.abrupt("return");
case 9:
i += 1;
_context.next = 1;
break;
case 12:
/* eslint-enable */
resolve([]);
case 13:
case "end":
return _context.stop();
}
}, _callee);
}));
return function (_x6, _x7) {
return _ref3.apply(this, arguments);
};
}());
} else {
// >>>>> Validate by parallel
var rulePromises = filledRules.map(function (rule) {
return validateRule(name, value, rule, options, messageVariables).then(function (errors) {
return {
errors: errors,
rule: rule
};
});
});
summaryPromise = (validateFirst ? finishOnFirstFailed(rulePromises) : finishOnAllFailed(rulePromises)).then(function (errors) {
// Always change to rejection for Field to catch
return Promise.reject(errors);
});
}
// Internal catch error to avoid console error log.
summaryPromise.catch(function (e) {
return e;
});
return summaryPromise;
}
function finishOnAllFailed(_x8) {
return _finishOnAllFailed.apply(this, arguments);
}
function _finishOnAllFailed() {
_finishOnAllFailed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(rulePromises) {
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
return _context3.abrupt("return", Promise.all(rulePromises).then(function (errorsList) {
var _ref5;
var errors = (_ref5 = []).concat.apply(_ref5, _toConsumableArray(errorsList));
return errors;
}));
case 1:
case "end":
return _context3.stop();
}
}, _callee3);
}));
return _finishOnAllFailed.apply(this, arguments);
}
function finishOnFirstFailed(_x9) {
return _finishOnFirstFailed.apply(this, arguments);
}
function _finishOnFirstFailed() {
_finishOnFirstFailed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(rulePromises) {
var count;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
count = 0;
return _context4.abrupt("return", new Promise(function (resolve) {
rulePromises.forEach(function (promise) {
promise.then(function (ruleError) {
if (ruleError.errors.length) {
resolve([ruleError]);
}
count += 1;
if (count === rulePromises.length) {
resolve([]);
}
});
});
}));
case 2:
case "end":
return _context4.stop();
}
}, _callee4);
}));
return _finishOnFirstFailed.apply(this, arguments);
}
var _excluded$i = ["name"];
var EMPTY_ERRORS = [];
function requireUpdate(shouldUpdate, prev, next, prevValue, nextValue, info) {
if (typeof shouldUpdate === 'function') {
return shouldUpdate(prev, next, 'source' in info ? {
source: info.source
} : {});
}
return prevValue !== nextValue;
}
// We use Class instead of Hooks here since it will cost much code by using Hooks.
var Field = /*#__PURE__*/function (_React$Component) {
_inherits(Field, _React$Component);
var _super = _createSuper(Field);
/**
* Follow state should not management in State since it will async update by React.
* This makes first render of form can not get correct state value.
*/
/**
* Mark when touched & validated. Currently only used for `dependencies`.
* Note that we do not think field with `initialValue` is dirty
* but this will be by `isFieldDirty` func.
*/
// ============================== Subscriptions ==============================
function Field(props) {
var _this;
_classCallCheck(this, Field);
_this = _super.call(this, props);
// Register on init
_this.state = {
resetCount: 0
};
_this.cancelRegisterFunc = null;
_this.mounted = false;
_this.touched = false;
_this.dirty = false;
_this.validatePromise = null;
_this.prevValidating = void 0;
_this.errors = EMPTY_ERRORS;
_this.warnings = EMPTY_ERRORS;
_this.cancelRegister = function () {
var _this$props = _this.props,
preserve = _this$props.preserve,
isListField = _this$props.isListField,
name = _this$props.name;
if (_this.cancelRegisterFunc) {
_this.cancelRegisterFunc(isListField, preserve, getNamePath(name));
}
_this.cancelRegisterFunc = null;
};
_this.getNamePath = function () {
var _this$props2 = _this.props,
name = _this$props2.name,
fieldContext = _this$props2.fieldContext;
var _fieldContext$prefixN = fieldContext.prefixName,
prefixName = _fieldContext$prefixN === void 0 ? [] : _fieldContext$prefixN;
return name !== undefined ? [].concat(_toConsumableArray(prefixName), _toConsumableArray(name)) : [];
};
_this.getRules = function () {
var _this$props3 = _this.props,
_this$props3$rules = _this$props3.rules,
rules = _this$props3$rules === void 0 ? [] : _this$props3$rules,
fieldContext = _this$props3.fieldContext;
return rules.map(function (rule) {
if (typeof rule === 'function') {
return rule(fieldContext);
}
return rule;
});
};
_this.refresh = function () {
if (!_this.mounted) return;
/**
* Clean up current node.
*/
_this.setState(function (_ref) {
var resetCount = _ref.resetCount;
return {
resetCount: resetCount + 1
};
});
};
_this.triggerMetaEvent = function (destroy) {
var onMetaChange = _this.props.onMetaChange;
onMetaChange === null || onMetaChange === void 0 ? void 0 : onMetaChange(_objectSpread2$1(_objectSpread2$1({}, _this.getMeta()), {}, {
destroy: destroy
}));
};
_this.onStoreChange = function (prevStore, namePathList, info) {
var _this$props4 = _this.props,
shouldUpdate = _this$props4.shouldUpdate,
_this$props4$dependen = _this$props4.dependencies,
dependencies = _this$props4$dependen === void 0 ? [] : _this$props4$dependen,
onReset = _this$props4.onReset;
var store = info.store;
var namePath = _this.getNamePath();
var prevValue = _this.getValue(prevStore);
var curValue = _this.getValue(store);
var namePathMatch = namePathList && containsNamePath(namePathList, namePath);
// `setFieldsValue` is a quick access to update related status
if (info.type === 'valueUpdate' && info.source === 'external' && prevValue !== curValue) {
_this.touched = true;
_this.dirty = true;
_this.validatePromise = null;
_this.errors = EMPTY_ERRORS;
_this.warnings = EMPTY_ERRORS;
_this.triggerMetaEvent();
}
switch (info.type) {
case 'reset':
if (!namePathList || namePathMatch) {
// Clean up state
_this.touched = false;
_this.dirty = false;
_this.validatePromise = null;
_this.errors = EMPTY_ERRORS;
_this.warnings = EMPTY_ERRORS;
_this.triggerMetaEvent();
onReset === null || onReset === void 0 ? void 0 : onReset();
_this.refresh();
return;
}
break;
/**
* In case field with `preserve = false` nest deps like:
* - A = 1 => show B
* - B = 1 => show C
* - Reset A, need clean B, C
*/
case 'remove':
{
if (shouldUpdate) {
_this.reRender();
return;
}
break;
}
case 'setField':
{
if (namePathMatch) {
var data = info.data;
if ('touched' in data) {
_this.touched = data.touched;
}
if ('validating' in data && !('originRCField' in data)) {
_this.validatePromise = data.validating ? Promise.resolve([]) : null;
}
if ('errors' in data) {
_this.errors = data.errors || EMPTY_ERRORS;
}
if ('warnings' in data) {
_this.warnings = data.warnings || EMPTY_ERRORS;
}
_this.dirty = true;
_this.triggerMetaEvent();
_this.reRender();
return;
}
// Handle update by `setField` with `shouldUpdate`
if (shouldUpdate && !namePath.length && requireUpdate(shouldUpdate, prevStore, store, prevValue, curValue, info)) {
_this.reRender();
return;
}
break;
}
case 'dependenciesUpdate':
{
/**
* Trigger when marked `dependencies` updated. Related fields will all update
*/
var dependencyList = dependencies.map(getNamePath);
// No need for `namePathMath` check and `shouldUpdate` check, since `valueUpdate` will be
// emitted earlier and they will work there
// If set it may cause unnecessary twice rerendering
if (dependencyList.some(function (dependency) {
return containsNamePath(info.relatedFields, dependency);
})) {
_this.reRender();
return;
}
break;
}
default:
// 1. If `namePath` exists in `namePathList`, means it's related value and should update
// For example <List name="list"><Field name={['list', 0]}></List>
// If `namePathList` is [['list']] (List value update), Field should be updated
// If `namePathList` is [['list', 0]] (Field value update), List shouldn't be updated
// 2.
// 2.1 If `dependencies` is set, `name` is not set and `shouldUpdate` is not set,
// don't use `shouldUpdate`. `dependencies` is view as a shortcut if `shouldUpdate`
// is not provided
// 2.2 If `shouldUpdate` provided, use customize logic to update the field
// else to check if value changed
if (namePathMatch || (!dependencies.length || namePath.length || shouldUpdate) && requireUpdate(shouldUpdate, prevStore, store, prevValue, curValue, info)) {
_this.reRender();
return;
}
break;
}
if (shouldUpdate === true) {
_this.reRender();
}
};
_this.validateRules = function (options) {
// We should fixed namePath & value to avoid developer change then by form function
var namePath = _this.getNamePath();
var currentValue = _this.getValue();
// Force change to async to avoid rule OOD under renderProps field
var rootPromise = Promise.resolve().then(function () {
if (!_this.mounted) {
return [];
}
var _this$props5 = _this.props,
_this$props5$validate = _this$props5.validateFirst,
validateFirst = _this$props5$validate === void 0 ? false : _this$props5$validate,
messageVariables = _this$props5.messageVariables;
var _ref2 = options || {},
triggerName = _ref2.triggerName;
var filteredRules = _this.getRules();
if (triggerName) {
filteredRules = filteredRules.filter(function (rule) {
return rule;
}).filter(function (rule) {
var validateTrigger = rule.validateTrigger;
if (!validateTrigger) {
return true;
}
var triggerList = toArray(validateTrigger);
return triggerList.includes(triggerName);
});
}
var promise = validateRules(namePath, currentValue, filteredRules, options, validateFirst, messageVariables);
promise.catch(function (e) {
return e;
}).then(function () {
var ruleErrors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : EMPTY_ERRORS;
if (_this.validatePromise === rootPromise) {
var _ruleErrors$forEach;
_this.validatePromise = null;
// Get errors & warnings
var nextErrors = [];
var nextWarnings = [];
(_ruleErrors$forEach = ruleErrors.forEach) === null || _ruleErrors$forEach === void 0 ? void 0 : _ruleErrors$forEach.call(ruleErrors, function (_ref3) {
var warningOnly = _ref3.rule.warningOnly,
_ref3$errors = _ref3.errors,
errors = _ref3$errors === void 0 ? EMPTY_ERRORS : _ref3$errors;
if (warningOnly) {
nextWarnings.push.apply(nextWarnings, _toConsumableArray(errors));
} else {
nextErrors.push.apply(nextErrors, _toConsumableArray(errors));
}
});
_this.errors = nextErrors;
_this.warnings = nextWarnings;
_this.triggerMetaEvent();
_this.reRender();
}
});
return promise;
});
_this.validatePromise = rootPromise;
_this.dirty = true;
_this.errors = EMPTY_ERRORS;
_this.warnings = EMPTY_ERRORS;
_this.triggerMetaEvent();
// Force trigger re-render since we need sync renderProps with new meta
_this.reRender();
return rootPromise;
};
_this.isFieldValidating = function () {
return !!_this.validatePromise;
};
_this.isFieldTouched = function () {
return _this.touched;
};
_this.isFieldDirty = function () {
// Touched or validate or has initialValue
if (_this.dirty || _this.props.initialValue !== undefined) {
return true;
}
// Form set initialValue
var fieldContext = _this.props.fieldContext;
var _fieldContext$getInte = fieldContext.getInternalHooks(HOOK_MARK),
getInitialValue = _fieldContext$getInte.getInitialValue;
if (getInitialValue(_this.getNamePath()) !== undefined) {
return true;
}
return false;
};
_this.getErrors = function () {
return _this.errors;
};
_this.getWarnings = function () {
return _this.warnings;
};
_this.isListField = function () {
return _this.props.isListField;
};
_this.isList = function () {
return _this.props.isList;
};
_this.isPreserve = function () {
return _this.props.preserve;
};
_this.getMeta = function () {
// Make error & validating in cache to save perf
_this.prevValidating = _this.isFieldValidating();
var meta = {
touched: _this.isFieldTouched(),
validating: _this.prevValidating,
errors: _this.errors,
warnings: _this.warnings,
name: _this.getNamePath()
};
return meta;
};
_this.getOnlyChild = function (children) {
// Support render props
if (typeof children === 'function') {
var meta = _this.getMeta();
return _objectSpread2$1(_objectSpread2$1({}, _this.getOnlyChild(children(_this.getControlled(), meta, _this.props.fieldContext))), {}, {
isFunction: true
});
}
// Filed element only
var childList = toArray$1(children);
if (childList.length !== 1 || ! /*#__PURE__*/React.isValidElement(childList[0])) {
return {
child: childList,
isFunction: false
};
}
return {
child: childList[0],
isFunction: false
};
};
_this.getValue = function (store) {
var getFieldsValue = _this.props.fieldContext.getFieldsValue;
var namePath = _this.getNamePath();
return getValue$1(store || getFieldsValue(true), namePath);
};
_this.getControlled = function () {
var childProps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var _this$props6 = _this.props,
trigger = _this$props6.trigger,
validateTrigger = _this$props6.validateTrigger,
getValueFromEvent = _this$props6.getValueFromEvent,
normalize = _this$props6.normalize,
valuePropName = _this$props6.valuePropName,
getValueProps = _this$props6.getValueProps,
fieldContext = _this$props6.fieldContext;
var mergedValidateTrigger = validateTrigger !== undefined ? validateTrigger : fieldContext.validateTrigger;
var namePath = _this.getNamePath();
var getInternalHooks = fieldContext.getInternalHooks,
getFieldsValue = fieldContext.getFieldsValue;
var _getInternalHooks = getInternalHooks(HOOK_MARK),
dispatch = _getInternalHooks.dispatch;
var value = _this.getValue();
var mergedGetValueProps = getValueProps || function (val) {
return _defineProperty$1({}, valuePropName, val);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var originTriggerFunc = childProps[trigger];
var control = _objectSpread2$1(_objectSpread2$1({}, childProps), mergedGetValueProps(value));
// Add trigger
control[trigger] = function () {
// Mark as touched
_this.touched = true;
_this.dirty = true;
_this.triggerMetaEvent();
var newValue;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (getValueFromEvent) {
newValue = getValueFromEvent.apply(void 0, args);
} else {
newValue = defaultGetValueFromEvent.apply(void 0, [valuePropName].concat(args));
}
if (normalize) {
newValue = normalize(newValue, value, getFieldsValue(true));
}
dispatch({
type: 'updateValue',
namePath: namePath,
value: newValue
});
if (originTriggerFunc) {
originTriggerFunc.apply(void 0, args);
}
};
// Add validateTrigger
var validateTriggerList = toArray(mergedValidateTrigger || []);
validateTriggerList.forEach(function (triggerName) {
// Wrap additional function of component, so that we can get latest value from store
var originTrigger = control[triggerName];
control[triggerName] = function () {
if (originTrigger) {
originTrigger.apply(void 0, arguments);
}
// Always use latest rules
var rules = _this.props.rules;
if (rules && rules.length) {
// We dispatch validate to root,
// since it will update related data with other field with same name
dispatch({
type: 'validateField',
namePath: namePath,
triggerName: triggerName
});
}
};
});
return control;
};
if (props.fieldContext) {
var getInternalHooks = props.fieldContext.getInternalHooks;
var _getInternalHooks2 = getInternalHooks(HOOK_MARK),
initEntityValue = _getInternalHooks2.initEntityValue;
initEntityValue(_assertThisInitialized(_this));
}
return _this;
}
_createClass(Field, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this$props7 = this.props,
shouldUpdate = _this$props7.shouldUpdate,
fieldContext = _this$props7.fieldContext;
this.mounted = true;
// Register on init
if (fieldContext) {
var getInternalHooks = fieldContext.getInternalHooks;
var _getInternalHooks3 = getInternalHooks(HOOK_MARK),
registerField = _getInternalHooks3.registerField;
this.cancelRegisterFunc = registerField(this);
}
// One more render for component in case fields not ready
if (shouldUpdate === true) {
this.reRender();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.cancelRegister();
this.triggerMetaEvent(true);
this.mounted = false;
}
}, {
key: "reRender",
value: function reRender() {
if (!this.mounted) return;
this.forceUpdate();
}
}, {
key: "render",
value: function render() {
var resetCount = this.state.resetCount;
var children = this.props.children;
var _this$getOnlyChild = this.getOnlyChild(children),
child = _this$getOnlyChild.child,
isFunction = _this$getOnlyChild.isFunction;
// Not need to `cloneElement` since user can handle this in render function self
var returnChildNode;
if (isFunction) {
returnChildNode = child;
} else if ( /*#__PURE__*/React.isValidElement(child)) {
returnChildNode = /*#__PURE__*/React.cloneElement(child, this.getControlled(child.props));
} else {
warningOnce(!child, '`children` of Field is not validate ReactElement.');
returnChildNode = child;
}
return /*#__PURE__*/React.createElement(React.Fragment, {
key: resetCount
}, returnChildNode);
}
}]);
return Field;
}(React.Component);
Field.contextType = Context$1;
Field.defaultProps = {
trigger: 'onChange',
valuePropName: 'value'
};
function WrapperField(_ref5) {
var name = _ref5.name,
restProps = _objectWithoutProperties(_ref5, _excluded$i);
var fieldContext = React.useContext(Context$1);
var namePath = name !== undefined ? getNamePath(name) : undefined;
var key = 'keep';
if (!restProps.isListField) {
key = "_".concat((namePath || []).join('_'));
}
// Warning if it's a directly list field.
// We can still support multiple level field preserve.
if (process.env.NODE_ENV !== 'production' && restProps.preserve === false && restProps.isListField && namePath.length <= 1) {
warningOnce(false, '`preserve` should not apply on Form.List fields.');
}
return /*#__PURE__*/React.createElement(Field, _extends$1({
key: key,
name: namePath
}, restProps, {
fieldContext: fieldContext
}));
}
var ListContext = /*#__PURE__*/React.createContext(null);
var List = function List(_ref) {
var name = _ref.name,
initialValue = _ref.initialValue,
children = _ref.children,
rules = _ref.rules,
validateTrigger = _ref.validateTrigger;
var context = React.useContext(Context$1);
var keyRef = React.useRef({
keys: [],
id: 0
});
var keyManager = keyRef.current;
var prefixName = React.useMemo(function () {
var parentPrefixName = getNamePath(context.prefixName) || [];
return [].concat(_toConsumableArray(parentPrefixName), _toConsumableArray(getNamePath(name)));
}, [context.prefixName, name]);
var fieldContext = React.useMemo(function () {
return _objectSpread2$1(_objectSpread2$1({}, context), {}, {
prefixName: prefixName
});
}, [context, prefixName]);
// List context
var listContext = React.useMemo(function () {
return {
getKey: function getKey(namePath) {
var len = prefixName.length;
var pathName = namePath[len];
return [keyManager.keys[pathName], namePath.slice(len + 1)];
}
};
}, [prefixName]);
// User should not pass `children` as other type.
if (typeof children !== 'function') {
warningOnce(false, 'Form.List only accepts function as children.');
return null;
}
var shouldUpdate = function shouldUpdate(prevValue, nextValue, _ref2) {
var source = _ref2.source;
if (source === 'internal') {
return false;
}
return prevValue !== nextValue;
};
return /*#__PURE__*/React.createElement(ListContext.Provider, {
value: listContext
}, /*#__PURE__*/React.createElement(Context$1.Provider, {
value: fieldContext
}, /*#__PURE__*/React.createElement(WrapperField, {
name: [],
shouldUpdate: shouldUpdate,
rules: rules,
validateTrigger: validateTrigger,
initialValue: initialValue,
isList: true
}, function (_ref3, meta) {
var _ref3$value = _ref3.value,
value = _ref3$value === void 0 ? [] : _ref3$value,
onChange = _ref3.onChange;
var getFieldValue = context.getFieldValue;
var getNewValue = function getNewValue() {
var values = getFieldValue(prefixName || []);
return values || [];
};
/**
* Always get latest value in case user update fields by `form` api.
*/
var operations = {
add: function add(defaultValue, index) {
// Mapping keys
var newValue = getNewValue();
if (index >= 0 && index <= newValue.length) {
keyManager.keys = [].concat(_toConsumableArray(keyManager.keys.slice(0, index)), [keyManager.id], _toConsumableArray(keyManager.keys.slice(index)));
onChange([].concat(_toConsumableArray(newValue.slice(0, index)), [defaultValue], _toConsumableArray(newValue.slice(index))));
} else {
if (process.env.NODE_ENV !== 'production' && (index < 0 || index > newValue.length)) {
warningOnce(false, 'The second parameter of the add function should be a valid positive number.');
}
keyManager.keys = [].concat(_toConsumableArray(keyManager.keys), [keyManager.id]);
onChange([].concat(_toConsumableArray(newValue), [defaultValue]));
}
keyManager.id += 1;
},
remove: function remove(index) {
var newValue = getNewValue();
var indexSet = new Set(Array.isArray(index) ? index : [index]);
if (indexSet.size <= 0) {
return;
}
keyManager.keys = keyManager.keys.filter(function (_, keysIndex) {
return !indexSet.has(keysIndex);
});
// Trigger store change
onChange(newValue.filter(function (_, valueIndex) {
return !indexSet.has(valueIndex);
}));
},
move: function move$1(from, to) {
if (from === to) {
return;
}
var newValue = getNewValue();
// Do not handle out of range
if (from < 0 || from >= newValue.length || to < 0 || to >= newValue.length) {
return;
}
keyManager.keys = move(keyManager.keys, from, to);
// Trigger store change
onChange(move(newValue, from, to));
}
};
var listValue = value || [];
if (!Array.isArray(listValue)) {
listValue = [];
if (process.env.NODE_ENV !== 'production') {
warningOnce(false, "Current value of '".concat(prefixName.join(' > '), "' is not an array type."));
}
}
return children(listValue.map(function (__, index) {
var key = keyManager.keys[index];
if (key === undefined) {
keyManager.keys[index] = keyManager.id;
key = keyManager.keys[index];
keyManager.id += 1;
}
return {
name: index,
key: key,
isListField: true
};
}), operations, meta);
})));
};
function allPromiseFinish(promiseList) {
var hasError = false;
var count = promiseList.length;
var results = [];
if (!promiseList.length) {
return Promise.resolve([]);
}
return new Promise(function (resolve, reject) {
promiseList.forEach(function (promise, index) {
promise.catch(function (e) {
hasError = true;
return e;
}).then(function (result) {
count -= 1;
results[index] = result;
if (count > 0) {
return;
}
if (hasError) {
reject(results);
}
resolve(results);
});
});
});
}
var SPLIT = '__@field_split__';
/**
* Convert name path into string to fast the fetch speed of Map.
*/
function normalize(namePath) {
return namePath.map(function (cell) {
return "".concat(_typeof$1(cell), ":").concat(cell);
})
// Magic split
.join(SPLIT);
}
/**
* NameMap like a `Map` but accepts `string[]` as key.
*/
var NameMap = /*#__PURE__*/function () {
function NameMap() {
_classCallCheck(this, NameMap);
this.kvs = new Map();
}
_createClass(NameMap, [{
key: "set",
value: function set(key, value) {
this.kvs.set(normalize(key), value);
}
}, {
key: "get",
value: function get(key) {
return this.kvs.get(normalize(key));
}
}, {
key: "update",
value: function update(key, updater) {
var origin = this.get(key);
var next = updater(origin);
if (!next) {
this.delete(key);
} else {
this.set(key, next);
}
}
}, {
key: "delete",
value: function _delete(key) {
this.kvs.delete(normalize(key));
}
// Since we only use this in test, let simply realize this
}, {
key: "map",
value: function map(callback) {
return _toConsumableArray(this.kvs.entries()).map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
var cells = key.split(SPLIT);
return callback({
key: cells.map(function (cell) {
var _cell$match = cell.match(/^([^:]*):(.*)$/),
_cell$match2 = _slicedToArray(_cell$match, 3),
type = _cell$match2[1],
unit = _cell$match2[2];
return type === 'number' ? Number(unit) : unit;
}),
value: value
});
});
}
}, {
key: "toJSON",
value: function toJSON() {
var json = {};
this.map(function (_ref3) {
var key = _ref3.key,
value = _ref3.value;
json[key.join('.')] = value;
return null;
});
return json;
}
}]);
return NameMap;
}();
var _excluded$h = ["name", "errors"];
var FormStore = /*#__PURE__*/_createClass(function FormStore(forceRootUpdate) {
var _this = this;
_classCallCheck(this, FormStore);
this.formHooked = false;
this.forceRootUpdate = void 0;
this.subscribable = true;
this.store = {};
this.fieldEntities = [];
this.initialValues = {};
this.callbacks = {};
this.validateMessages = null;
this.preserve = null;
this.lastValidatePromise = null;
this.getForm = function () {
return {
getFieldValue: _this.getFieldValue,
getFieldsValue: _this.getFieldsValue,
getFieldError: _this.getFieldError,
getFieldWarning: _this.getFieldWarning,
getFieldsError: _this.getFieldsError,
isFieldsTouched: _this.isFieldsTouched,
isFieldTouched: _this.isFieldTouched,
isFieldValidating: _this.isFieldValidating,
isFieldsValidating: _this.isFieldsValidating,
resetFields: _this.resetFields,
setFields: _this.setFields,
setFieldValue: _this.setFieldValue,
setFieldsValue: _this.setFieldsValue,
validateFields: _this.validateFields,
submit: _this.submit,
_init: true,
getInternalHooks: _this.getInternalHooks
};
};
this.getInternalHooks = function (key) {
if (key === HOOK_MARK) {
_this.formHooked = true;
return {
dispatch: _this.dispatch,
initEntityValue: _this.initEntityValue,
registerField: _this.registerField,
useSubscribe: _this.useSubscribe,
setInitialValues: _this.setInitialValues,
destroyForm: _this.destroyForm,
setCallbacks: _this.setCallbacks,
setValidateMessages: _this.setValidateMessages,
getFields: _this.getFields,
setPreserve: _this.setPreserve,
getInitialValue: _this.getInitialValue,
registerWatch: _this.registerWatch
};
}
warningOnce(false, '`getInternalHooks` is internal usage. Should not call directly.');
return null;
};
this.useSubscribe = function (subscribable) {
_this.subscribable = subscribable;
};
this.prevWithoutPreserves = null;
this.setInitialValues = function (initialValues, init) {
_this.initialValues = initialValues || {};
if (init) {
var _this$prevWithoutPres;
var nextStore = setValues({}, initialValues, _this.store);
// We will take consider prev form unmount fields.
// When the field is not `preserve`, we need fill this with initialValues instead of store.
// eslint-disable-next-line array-callback-return
(_this$prevWithoutPres = _this.prevWithoutPreserves) === null || _this$prevWithoutPres === void 0 ? void 0 : _this$prevWithoutPres.map(function (_ref) {
var namePath = _ref.key;
nextStore = setValue(nextStore, namePath, getValue$1(initialValues, namePath));
});
_this.prevWithoutPreserves = null;
_this.updateStore(nextStore);
}
};
this.destroyForm = function () {
var prevWithoutPreserves = new NameMap();
_this.getFieldEntities(true).forEach(function (entity) {
if (!_this.isMergedPreserve(entity.isPreserve())) {
prevWithoutPreserves.set(entity.getNamePath(), true);
}
});
_this.prevWithoutPreserves = prevWithoutPreserves;
};
this.getInitialValue = function (namePath) {
var initValue = getValue$1(_this.initialValues, namePath);
// Not cloneDeep when without `namePath`
return namePath.length ? cloneDeep(initValue) : initValue;
};
this.setCallbacks = function (callbacks) {
_this.callbacks = callbacks;
};
this.setValidateMessages = function (validateMessages) {
_this.validateMessages = validateMessages;
};
this.setPreserve = function (preserve) {
_this.preserve = preserve;
};
this.watchList = [];
this.registerWatch = function (callback) {
_this.watchList.push(callback);
return function () {
_this.watchList = _this.watchList.filter(function (fn) {
return fn !== callback;
});
};
};
this.notifyWatch = function () {
var namePath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
// No need to cost perf when nothing need to watch
if (_this.watchList.length) {
var values = _this.getFieldsValue();
_this.watchList.forEach(function (callback) {
callback(values, namePath);
});
}
};
this.timeoutId = null;
this.warningUnhooked = function () {
if (process.env.NODE_ENV !== 'production' && !_this.timeoutId && typeof window !== 'undefined') {
_this.timeoutId = setTimeout(function () {
_this.timeoutId = null;
if (!_this.formHooked) {
warningOnce(false, 'Instance created by `useForm` is not connected to any Form element. Forget to pass `form` prop?');
}
});
}
};
this.updateStore = function (nextStore) {
_this.store = nextStore;
};
this.getFieldEntities = function () {
var pure = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (!pure) {
return _this.fieldEntities;
}
return _this.fieldEntities.filter(function (field) {
return field.getNamePath().length;
});
};
this.getFieldsMap = function () {
var pure = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var cache = new NameMap();
_this.getFieldEntities(pure).forEach(function (field) {
var namePath = field.getNamePath();
cache.set(namePath, field);
});
return cache;
};
this.getFieldEntitiesForNamePathList = function (nameList) {
if (!nameList) {
return _this.getFieldEntities(true);
}
var cache = _this.getFieldsMap(true);
return nameList.map(function (name) {
var namePath = getNamePath(name);
return cache.get(namePath) || {
INVALIDATE_NAME_PATH: getNamePath(name)
};
});
};
this.getFieldsValue = function (nameList, filterFunc) {
_this.warningUnhooked();
if (nameList === true && !filterFunc) {
return _this.store;
}
var fieldEntities = _this.getFieldEntitiesForNamePathList(Array.isArray(nameList) ? nameList : null);
var filteredNameList = [];
fieldEntities.forEach(function (entity) {
var _entity$isListField;
var namePath = 'INVALIDATE_NAME_PATH' in entity ? entity.INVALIDATE_NAME_PATH : entity.getNamePath();
// Ignore when it's a list item and not specific the namePath,
// since parent field is already take in count
if (!nameList && ((_entity$isListField = entity.isListField) === null || _entity$isListField === void 0 ? void 0 : _entity$isListField.call(entity))) {
return;
}
if (!filterFunc) {
filteredNameList.push(namePath);
} else {
var meta = 'getMeta' in entity ? entity.getMeta() : null;
if (filterFunc(meta)) {
filteredNameList.push(namePath);
}
}
});
return cloneByNamePathList(_this.store, filteredNameList.map(getNamePath));
};
this.getFieldValue = function (name) {
_this.warningUnhooked();
var namePath = getNamePath(name);
return getValue$1(_this.store, namePath);
};
this.getFieldsError = function (nameList) {
_this.warningUnhooked();
var fieldEntities = _this.getFieldEntitiesForNamePathList(nameList);
return fieldEntities.map(function (entity, index) {
if (entity && !('INVALIDATE_NAME_PATH' in entity)) {
return {
name: entity.getNamePath(),
errors: entity.getErrors(),
warnings: entity.getWarnings()
};
}
return {
name: getNamePath(nameList[index]),
errors: [],
warnings: []
};
});
};
this.getFieldError = function (name) {
_this.warningUnhooked();
var namePath = getNamePath(name);
var fieldError = _this.getFieldsError([namePath])[0];
return fieldError.errors;
};
this.getFieldWarning = function (name) {
_this.warningUnhooked();
var namePath = getNamePath(name);
var fieldError = _this.getFieldsError([namePath])[0];
return fieldError.warnings;
};
this.isFieldsTouched = function () {
_this.warningUnhooked();
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var arg0 = args[0],
arg1 = args[1];
var namePathList;
var isAllFieldsTouched = false;
if (args.length === 0) {
namePathList = null;
} else if (args.length === 1) {
if (Array.isArray(arg0)) {
namePathList = arg0.map(getNamePath);
isAllFieldsTouched = false;
} else {
namePathList = null;
isAllFieldsTouched = arg0;
}
} else {
namePathList = arg0.map(getNamePath);
isAllFieldsTouched = arg1;
}
var fieldEntities = _this.getFieldEntities(true);
var isFieldTouched = function isFieldTouched(field) {
return field.isFieldTouched();
};
// ===== Will get fully compare when not config namePathList =====
if (!namePathList) {
return isAllFieldsTouched ? fieldEntities.every(isFieldTouched) : fieldEntities.some(isFieldTouched);
}
// Generate a nest tree for validate
var map = new NameMap();
namePathList.forEach(function (shortNamePath) {
map.set(shortNamePath, []);
});
fieldEntities.forEach(function (field) {
var fieldNamePath = field.getNamePath();
// Find matched entity and put into list
namePathList.forEach(function (shortNamePath) {
if (shortNamePath.every(function (nameUnit, i) {
return fieldNamePath[i] === nameUnit;
})) {
map.update(shortNamePath, function (list) {
return [].concat(_toConsumableArray(list), [field]);
});
}
});
});
// Check if NameMap value is touched
var isNamePathListTouched = function isNamePathListTouched(entities) {
return entities.some(isFieldTouched);
};
var namePathListEntities = map.map(function (_ref2) {
var value = _ref2.value;
return value;
});
return isAllFieldsTouched ? namePathListEntities.every(isNamePathListTouched) : namePathListEntities.some(isNamePathListTouched);
};
this.isFieldTouched = function (name) {
_this.warningUnhooked();
return _this.isFieldsTouched([name]);
};
this.isFieldsValidating = function (nameList) {
_this.warningUnhooked();
var fieldEntities = _this.getFieldEntities();
if (!nameList) {
return fieldEntities.some(function (testField) {
return testField.isFieldValidating();
});
}
var namePathList = nameList.map(getNamePath);
return fieldEntities.some(function (testField) {
var fieldNamePath = testField.getNamePath();
return containsNamePath(namePathList, fieldNamePath) && testField.isFieldValidating();
});
};
this.isFieldValidating = function (name) {
_this.warningUnhooked();
return _this.isFieldsValidating([name]);
};
this.resetWithFieldInitialValue = function () {
var info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
// Create cache
var cache = new NameMap();
var fieldEntities = _this.getFieldEntities(true);
fieldEntities.forEach(function (field) {
var initialValue = field.props.initialValue;
var namePath = field.getNamePath();
// Record only if has `initialValue`
if (initialValue !== undefined) {
var records = cache.get(namePath) || new Set();
records.add({
entity: field,
value: initialValue
});
cache.set(namePath, records);
}
});
// Reset
var resetWithFields = function resetWithFields(entities) {
entities.forEach(function (field) {
var initialValue = field.props.initialValue;
if (initialValue !== undefined) {
var namePath = field.getNamePath();
var formInitialValue = _this.getInitialValue(namePath);
if (formInitialValue !== undefined) {
// Warning if conflict with form initialValues and do not modify value
warningOnce(false, "Form already set 'initialValues' with path '".concat(namePath.join('.'), "'. Field can not overwrite it."));
} else {
var records = cache.get(namePath);
if (records && records.size > 1) {
// Warning if multiple field set `initialValue`and do not modify value
warningOnce(false, "Multiple Field with path '".concat(namePath.join('.'), "' set 'initialValue'. Can not decide which one to pick."));
} else if (records) {
var originValue = _this.getFieldValue(namePath);
// Set `initialValue`
if (!info.skipExist || originValue === undefined) {
_this.updateStore(setValue(_this.store, namePath, _toConsumableArray(records)[0].value));
}
}
}
}
});
};
var requiredFieldEntities;
if (info.entities) {
requiredFieldEntities = info.entities;
} else if (info.namePathList) {
requiredFieldEntities = [];
info.namePathList.forEach(function (namePath) {
var records = cache.get(namePath);
if (records) {
var _requiredFieldEntitie;
(_requiredFieldEntitie = requiredFieldEntities).push.apply(_requiredFieldEntitie, _toConsumableArray(_toConsumableArray(records).map(function (r) {
return r.entity;
})));
}
});
} else {
requiredFieldEntities = fieldEntities;
}
resetWithFields(requiredFieldEntities);
};
this.resetFields = function (nameList) {
_this.warningUnhooked();
var prevStore = _this.store;
if (!nameList) {
_this.updateStore(setValues({}, _this.initialValues));
_this.resetWithFieldInitialValue();
_this.notifyObservers(prevStore, null, {
type: 'reset'
});
_this.notifyWatch();
return;
}
// Reset by `nameList`
var namePathList = nameList.map(getNamePath);
namePathList.forEach(function (namePath) {
var initialValue = _this.getInitialValue(namePath);
_this.updateStore(setValue(_this.store, namePath, initialValue));
});
_this.resetWithFieldInitialValue({
namePathList: namePathList
});
_this.notifyObservers(prevStore, namePathList, {
type: 'reset'
});
_this.notifyWatch(namePathList);
};
this.setFields = function (fields) {
_this.warningUnhooked();
var prevStore = _this.store;
var namePathList = [];
fields.forEach(function (fieldData) {
var name = fieldData.name;
fieldData.errors;
var data = _objectWithoutProperties(fieldData, _excluded$h);
var namePath = getNamePath(name);
namePathList.push(namePath);
// Value
if ('value' in data) {
_this.updateStore(setValue(_this.store, namePath, data.value));
}
_this.notifyObservers(prevStore, [namePath], {
type: 'setField',
data: fieldData
});
});
_this.notifyWatch(namePathList);
};
this.getFields = function () {
var entities = _this.getFieldEntities(true);
var fields = entities.map(function (field) {
var namePath = field.getNamePath();
var meta = field.getMeta();
var fieldData = _objectSpread2$1(_objectSpread2$1({}, meta), {}, {
name: namePath,
value: _this.getFieldValue(namePath)
});
Object.defineProperty(fieldData, 'originRCField', {
value: true
});
return fieldData;
});
return fields;
};
this.initEntityValue = function (entity) {
var initialValue = entity.props.initialValue;
if (initialValue !== undefined) {
var namePath = entity.getNamePath();
var prevValue = getValue$1(_this.store, namePath);
if (prevValue === undefined) {
_this.updateStore(setValue(_this.store, namePath, initialValue));
}
}
};
this.isMergedPreserve = function (fieldPreserve) {
var mergedPreserve = fieldPreserve !== undefined ? fieldPreserve : _this.preserve;
return mergedPreserve !== null && mergedPreserve !== void 0 ? mergedPreserve : true;
};
this.registerField = function (entity) {
_this.fieldEntities.push(entity);
var namePath = entity.getNamePath();
_this.notifyWatch([namePath]);
// Set initial values
if (entity.props.initialValue !== undefined) {
var prevStore = _this.store;
_this.resetWithFieldInitialValue({
entities: [entity],
skipExist: true
});
_this.notifyObservers(prevStore, [entity.getNamePath()], {
type: 'valueUpdate',
source: 'internal'
});
}
// un-register field callback
return function (isListField, preserve) {
var subNamePath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
_this.fieldEntities = _this.fieldEntities.filter(function (item) {
return item !== entity;
});
// Clean up store value if not preserve
if (!_this.isMergedPreserve(preserve) && (!isListField || subNamePath.length > 1)) {
var defaultValue = isListField ? undefined : _this.getInitialValue(namePath);
if (namePath.length && _this.getFieldValue(namePath) !== defaultValue && _this.fieldEntities.every(function (field) {
return (
// Only reset when no namePath exist
!matchNamePath(field.getNamePath(), namePath)
);
})) {
var _prevStore = _this.store;
_this.updateStore(setValue(_prevStore, namePath, defaultValue, true));
// Notify that field is unmount
_this.notifyObservers(_prevStore, [namePath], {
type: 'remove'
});
// Dependencies update
_this.triggerDependenciesUpdate(_prevStore, namePath);
}
}
_this.notifyWatch([namePath]);
};
};
this.dispatch = function (action) {
switch (action.type) {
case 'updateValue':
{
var namePath = action.namePath,
value = action.value;
_this.updateValue(namePath, value);
break;
}
case 'validateField':
{
var _namePath = action.namePath,
triggerName = action.triggerName;
_this.validateFields([_namePath], {
triggerName: triggerName
});
break;
}
// Currently we don't have other action. Do nothing.
}
};
this.notifyObservers = function (prevStore, namePathList, info) {
if (_this.subscribable) {
var mergedInfo = _objectSpread2$1(_objectSpread2$1({}, info), {}, {
store: _this.getFieldsValue(true)
});
_this.getFieldEntities().forEach(function (_ref3) {
var onStoreChange = _ref3.onStoreChange;
onStoreChange(prevStore, namePathList, mergedInfo);
});
} else {
_this.forceRootUpdate();
}
};
this.triggerDependenciesUpdate = function (prevStore, namePath) {
var childrenFields = _this.getDependencyChildrenFields(namePath);
if (childrenFields.length) {
_this.validateFields(childrenFields);
}
_this.notifyObservers(prevStore, childrenFields, {
type: 'dependenciesUpdate',
relatedFields: [namePath].concat(_toConsumableArray(childrenFields))
});
return childrenFields;
};
this.updateValue = function (name, value) {
var namePath = getNamePath(name);
var prevStore = _this.store;
_this.updateStore(setValue(_this.store, namePath, value));
_this.notifyObservers(prevStore, [namePath], {
type: 'valueUpdate',
source: 'internal'
});
_this.notifyWatch([namePath]);
// Dependencies update
var childrenFields = _this.triggerDependenciesUpdate(prevStore, namePath);
// trigger callback function
var onValuesChange = _this.callbacks.onValuesChange;
if (onValuesChange) {
var changedValues = cloneByNamePathList(_this.store, [namePath]);
onValuesChange(changedValues, _this.getFieldsValue());
}
_this.triggerOnFieldsChange([namePath].concat(_toConsumableArray(childrenFields)));
};
this.setFieldsValue = function (store) {
_this.warningUnhooked();
var prevStore = _this.store;
if (store) {
var nextStore = setValues(_this.store, store);
_this.updateStore(nextStore);
}
_this.notifyObservers(prevStore, null, {
type: 'valueUpdate',
source: 'external'
});
_this.notifyWatch();
};
this.setFieldValue = function (name, value) {
_this.setFields([{
name: name,
value: value
}]);
};
this.getDependencyChildrenFields = function (rootNamePath) {
var children = new Set();
var childrenFields = [];
var dependencies2fields = new NameMap();
/**
* Generate maps
* Can use cache to save perf if user report performance issue with this
*/
_this.getFieldEntities().forEach(function (field) {
var dependencies = field.props.dependencies;
(dependencies || []).forEach(function (dependency) {
var dependencyNamePath = getNamePath(dependency);
dependencies2fields.update(dependencyNamePath, function () {
var fields = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Set();
fields.add(field);
return fields;
});
});
});
var fillChildren = function fillChildren(namePath) {
var fields = dependencies2fields.get(namePath) || new Set();
fields.forEach(function (field) {
if (!children.has(field)) {
children.add(field);
var fieldNamePath = field.getNamePath();
if (field.isFieldDirty() && fieldNamePath.length) {
childrenFields.push(fieldNamePath);
fillChildren(fieldNamePath);
}
}
});
};
fillChildren(rootNamePath);
return childrenFields;
};
this.triggerOnFieldsChange = function (namePathList, filedErrors) {
var onFieldsChange = _this.callbacks.onFieldsChange;
if (onFieldsChange) {
var fields = _this.getFields();
/**
* Fill errors since `fields` may be replaced by controlled fields
*/
if (filedErrors) {
var cache = new NameMap();
filedErrors.forEach(function (_ref4) {
var name = _ref4.name,
errors = _ref4.errors;
cache.set(name, errors);
});
fields.forEach(function (field) {
// eslint-disable-next-line no-param-reassign
field.errors = cache.get(field.name) || field.errors;
});
}
var changedFields = fields.filter(function (_ref5) {
var fieldName = _ref5.name;
return containsNamePath(namePathList, fieldName);
});
onFieldsChange(changedFields, fields);
}
};
this.validateFields = function (nameList, options) {
_this.warningUnhooked();
var provideNameList = !!nameList;
var namePathList = provideNameList ? nameList.map(getNamePath) : [];
// Collect result in promise list
var promiseList = [];
_this.getFieldEntities(true).forEach(function (field) {
// Add field if not provide `nameList`
if (!provideNameList) {
namePathList.push(field.getNamePath());
}
/**
* Recursive validate if configured.
* TODO: perf improvement @zombieJ
*/
if ((options === null || options === void 0 ? void 0 : options.recursive) && provideNameList) {
var namePath = field.getNamePath();
if (
// nameList[i] === undefined 说明是以 nameList 开头的
// ['name'] -> ['name','list']
namePath.every(function (nameUnit, i) {
return nameList[i] === nameUnit || nameList[i] === undefined;
})) {
namePathList.push(namePath);
}
}
// Skip if without rule
if (!field.props.rules || !field.props.rules.length) {
return;
}
var fieldNamePath = field.getNamePath();
// Add field validate rule in to promise list
if (!provideNameList || containsNamePath(namePathList, fieldNamePath)) {
var promise = field.validateRules(_objectSpread2$1({
validateMessages: _objectSpread2$1(_objectSpread2$1({}, defaultValidateMessages), _this.validateMessages)
}, options));
// Wrap promise with field
promiseList.push(promise.then(function () {
return {
name: fieldNamePath,
errors: [],
warnings: []
};
}).catch(function (ruleErrors) {
var _ruleErrors$forEach;
var mergedErrors = [];
var mergedWarnings = [];
(_ruleErrors$forEach = ruleErrors.forEach) === null || _ruleErrors$forEach === void 0 ? void 0 : _ruleErrors$forEach.call(ruleErrors, function (_ref6) {
var warningOnly = _ref6.rule.warningOnly,
errors = _ref6.errors;
if (warningOnly) {
mergedWarnings.push.apply(mergedWarnings, _toConsumableArray(errors));
} else {
mergedErrors.push.apply(mergedErrors, _toConsumableArray(errors));
}
});
if (mergedErrors.length) {
return Promise.reject({
name: fieldNamePath,
errors: mergedErrors,
warnings: mergedWarnings
});
}
return {
name: fieldNamePath,
errors: mergedErrors,
warnings: mergedWarnings
};
}));
}
});
var summaryPromise = allPromiseFinish(promiseList);
_this.lastValidatePromise = summaryPromise;
// Notify fields with rule that validate has finished and need update
summaryPromise.catch(function (results) {
return results;
}).then(function (results) {
var resultNamePathList = results.map(function (_ref7) {
var name = _ref7.name;
return name;
});
_this.notifyObservers(_this.store, resultNamePathList, {
type: 'validateFinish'
});
_this.triggerOnFieldsChange(resultNamePathList, results);
});
var returnPromise = summaryPromise.then(function () {
if (_this.lastValidatePromise === summaryPromise) {
return Promise.resolve(_this.getFieldsValue(namePathList));
}
return Promise.reject([]);
}).catch(function (results) {
var errorList = results.filter(function (result) {
return result && result.errors.length;
});
return Promise.reject({
values: _this.getFieldsValue(namePathList),
errorFields: errorList,
outOfDate: _this.lastValidatePromise !== summaryPromise
});
});
// Do not throw in console
returnPromise.catch(function (e) {
return e;
});
return returnPromise;
};
this.submit = function () {
_this.warningUnhooked();
_this.validateFields().then(function (values) {
var onFinish = _this.callbacks.onFinish;
if (onFinish) {
try {
onFinish(values);
} catch (err) {
// Should print error if user `onFinish` callback failed
console.error(err);
}
}
}).catch(function (e) {
var onFinishFailed = _this.callbacks.onFinishFailed;
if (onFinishFailed) {
onFinishFailed(e);
}
});
};
this.forceRootUpdate = forceRootUpdate;
});
function useForm(form) {
var formRef = React.useRef();
var _React$useState = React.useState({}),
_React$useState2 = _slicedToArray(_React$useState, 2),
forceUpdate = _React$useState2[1];
if (!formRef.current) {
if (form) {
formRef.current = form;
} else {
// Create a new FormStore if not provided
var forceReRender = function forceReRender() {
forceUpdate({});
};
var formStore = new FormStore(forceReRender);
formRef.current = formStore.getForm();
}
}
return [formRef.current];
}
var FormContext = /*#__PURE__*/React.createContext({
triggerFormChange: function triggerFormChange() {},
triggerFormFinish: function triggerFormFinish() {},
registerForm: function registerForm() {},
unregisterForm: function unregisterForm() {}
});
var FormProvider = function FormProvider(_ref) {
var validateMessages = _ref.validateMessages,
onFormChange = _ref.onFormChange,
onFormFinish = _ref.onFormFinish,
children = _ref.children;
var formContext = React.useContext(FormContext);
var formsRef = React.useRef({});
return /*#__PURE__*/React.createElement(FormContext.Provider, {
value: _objectSpread2$1(_objectSpread2$1({}, formContext), {}, {
validateMessages: _objectSpread2$1(_objectSpread2$1({}, formContext.validateMessages), validateMessages),
// =========================================================
// = Global Form Control =
// =========================================================
triggerFormChange: function triggerFormChange(name, changedFields) {
if (onFormChange) {
onFormChange(name, {
changedFields: changedFields,
forms: formsRef.current
});
}
formContext.triggerFormChange(name, changedFields);
},
triggerFormFinish: function triggerFormFinish(name, values) {
if (onFormFinish) {
onFormFinish(name, {
values: values,
forms: formsRef.current
});
}
formContext.triggerFormFinish(name, values);
},
registerForm: function registerForm(name, form) {
if (name) {
formsRef.current = _objectSpread2$1(_objectSpread2$1({}, formsRef.current), {}, _defineProperty$1({}, name, form));
}
formContext.registerForm(name, form);
},
unregisterForm: function unregisterForm(name) {
var newForms = _objectSpread2$1({}, formsRef.current);
delete newForms[name];
formsRef.current = newForms;
formContext.unregisterForm(name);
}
})
}, children);
};
var _excluded$g = ["name", "initialValues", "fields", "form", "preserve", "children", "component", "validateMessages", "validateTrigger", "onValuesChange", "onFieldsChange", "onFinish", "onFinishFailed"];
var Form = function Form(_ref, ref) {
var name = _ref.name,
initialValues = _ref.initialValues,
fields = _ref.fields,
form = _ref.form,
preserve = _ref.preserve,
children = _ref.children,
_ref$component = _ref.component,
Component = _ref$component === void 0 ? 'form' : _ref$component,
validateMessages = _ref.validateMessages,
_ref$validateTrigger = _ref.validateTrigger,
validateTrigger = _ref$validateTrigger === void 0 ? 'onChange' : _ref$validateTrigger,
onValuesChange = _ref.onValuesChange,
_onFieldsChange = _ref.onFieldsChange,
_onFinish = _ref.onFinish,
onFinishFailed = _ref.onFinishFailed,
restProps = _objectWithoutProperties(_ref, _excluded$g);
var formContext = React.useContext(FormContext);
// We customize handle event since Context will makes all the consumer re-render:
// https://reactjs.org/docs/context.html#contextprovider
var _useForm = useForm(form),
_useForm2 = _slicedToArray(_useForm, 1),
formInstance = _useForm2[0];
var _formInstance$getInte = formInstance.getInternalHooks(HOOK_MARK),
useSubscribe = _formInstance$getInte.useSubscribe,
setInitialValues = _formInstance$getInte.setInitialValues,
setCallbacks = _formInstance$getInte.setCallbacks,
setValidateMessages = _formInstance$getInte.setValidateMessages,
setPreserve = _formInstance$getInte.setPreserve,
destroyForm = _formInstance$getInte.destroyForm;
// Pass ref with form instance
React.useImperativeHandle(ref, function () {
return formInstance;
});
// Register form into Context
React.useEffect(function () {
formContext.registerForm(name, formInstance);
return function () {
formContext.unregisterForm(name);
};
}, [formContext, formInstance, name]);
// Pass props to store
setValidateMessages(_objectSpread2$1(_objectSpread2$1({}, formContext.validateMessages), validateMessages));
setCallbacks({
onValuesChange: onValuesChange,
onFieldsChange: function onFieldsChange(changedFields) {
formContext.triggerFormChange(name, changedFields);
if (_onFieldsChange) {
for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
_onFieldsChange.apply(void 0, [changedFields].concat(rest));
}
},
onFinish: function onFinish(values) {
formContext.triggerFormFinish(name, values);
if (_onFinish) {
_onFinish(values);
}
},
onFinishFailed: onFinishFailed
});
setPreserve(preserve);
// Set initial value, init store value when first mount
var mountRef = React.useRef(null);
setInitialValues(initialValues, !mountRef.current);
if (!mountRef.current) {
mountRef.current = true;
}
React.useEffect(function () {
return destroyForm;
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]);
// Prepare children by `children` type
var childrenNode;
var childrenRenderProps = typeof children === 'function';
if (childrenRenderProps) {
var values = formInstance.getFieldsValue(true);
childrenNode = children(values, formInstance);
} else {
childrenNode = children;
}
// Not use subscribe when using render props
useSubscribe(!childrenRenderProps);
// Listen if fields provided. We use ref to save prev data here to avoid additional render
var prevFieldsRef = React.useRef();
React.useEffect(function () {
if (!isSimilar(prevFieldsRef.current || [], fields || [])) {
formInstance.setFields(fields || []);
}
prevFieldsRef.current = fields;
}, [fields, formInstance]);
var formContextValue = React.useMemo(function () {
return _objectSpread2$1(_objectSpread2$1({}, formInstance), {}, {
validateTrigger: validateTrigger
});
}, [formInstance, validateTrigger]);
var wrapperNode = /*#__PURE__*/React.createElement(Context$1.Provider, {
value: formContextValue
}, childrenNode);
if (Component === false) {
return wrapperNode;
}
return /*#__PURE__*/React.createElement(Component, _extends$1({}, restProps, {
onSubmit: function onSubmit(event) {
event.preventDefault();
event.stopPropagation();
formInstance.submit();
},
onReset: function onReset(event) {
var _restProps$onReset;
event.preventDefault();
formInstance.resetFields();
(_restProps$onReset = restProps.onReset) === null || _restProps$onReset === void 0 ? void 0 : _restProps$onReset.call(restProps, event);
}
}), wrapperNode);
};
function stringify(value) {
try {
return JSON.stringify(value);
} catch (err) {
return Math.random();
}
}
var useWatchWarning = process.env.NODE_ENV !== 'production' ? function (namePath) {
var fullyStr = namePath.join('__RC_FIELD_FORM_SPLIT__');
var nameStrRef = useRef(fullyStr);
warningOnce(nameStrRef.current === fullyStr, '`useWatch` is not support dynamic `namePath`. Please provide static instead.');
} : function () {};
function useWatch() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var _args$ = args[0],
dependencies = _args$ === void 0 ? [] : _args$,
form = args[1];
var _useState = useState(),
_useState2 = _slicedToArray(_useState, 2),
value = _useState2[0],
setValue = _useState2[1];
var valueStr = useMemo$1(function () {
return stringify(value);
}, [value]);
var valueStrRef = useRef(valueStr);
valueStrRef.current = valueStr;
var fieldContext = useContext(Context$1);
var formInstance = form || fieldContext;
var isValidForm = formInstance && formInstance._init;
// Warning if not exist form instance
if (process.env.NODE_ENV !== 'production') {
warningOnce(args.length === 2 ? form ? isValidForm : true : isValidForm, 'useWatch requires a form instance since it can not auto detect from context.');
}
var namePath = getNamePath(dependencies);
var namePathRef = useRef(namePath);
namePathRef.current = namePath;
useWatchWarning(namePath);
useEffect(function () {
// Skip if not exist form instance
if (!isValidForm) {
return;
}
var getFieldsValue = formInstance.getFieldsValue,
getInternalHooks = formInstance.getInternalHooks;
var _getInternalHooks = getInternalHooks(HOOK_MARK),
registerWatch = _getInternalHooks.registerWatch;
var cancelRegister = registerWatch(function (store) {
var newValue = getValue$1(store, namePathRef.current);
var nextValueStr = stringify(newValue);
// Compare stringify in case it's nest object
if (valueStrRef.current !== nextValueStr) {
valueStrRef.current = nextValueStr;
setValue(newValue);
}
});
// TODO: We can improve this perf in future
var initialValue = getValue$1(getFieldsValue(), namePathRef.current);
setValue(initialValue);
return cancelRegister;
},
// We do not need re-register since namePath content is the same
// eslint-disable-next-line react-hooks/exhaustive-deps
[isValidForm]);
return value;
}
var InternalForm = /*#__PURE__*/React.forwardRef(Form);
var RefForm = InternalForm;
RefForm.FormProvider = FormProvider;
RefForm.Field = WrapperField;
RefForm.List = List;
RefForm.useForm = useForm;
RefForm.useWatch = useWatch;
function noop$2() {}
// eslint-disable-next-line import/no-mutable-exports
var warning$1 = noop$2;
if (process.env.NODE_ENV !== 'production') {
warning$1 = function warning(valid, component, message) {
warningOnce(valid, "[antd: " + component + "] " + message);
// StrictMode will inject console which will not throw warning in React 17.
if (process.env.NODE_ENV === 'test') {
resetWarned();
}
};
}
var warning$2 = warning$1;
var enUS$1 = {
// Options.jsx
items_per_page: '/ page',
jump_to: 'Go to',
jump_to_confirm: 'confirm',
page: 'Page',
// Pagination.jsx
prev_page: 'Previous Page',
next_page: 'Next Page',
prev_5: 'Previous 5 Pages',
next_5: 'Next 5 Pages',
prev_3: 'Previous 3 Pages',
next_3: 'Next 3 Pages',
page_size: 'Page Size'
};
var locale$2 = {
locale: 'en_US',
today: 'Today',
now: 'Now',
backToToday: 'Back to today',
ok: 'OK',
clear: 'Clear',
month: 'Month',
year: 'Year',
timeSelect: 'select time',
dateSelect: 'select date',
weekSelect: 'Choose a week',
monthSelect: 'Choose a month',
yearSelect: 'Choose a year',
decadeSelect: 'Choose a decade',
yearFormat: 'YYYY',
dateFormat: 'M/D/YYYY',
dayFormat: 'D',
dateTimeFormat: 'M/D/YYYY HH:mm:ss',
monthBeforeYear: true,
previousMonth: 'Previous month (PageUp)',
nextMonth: 'Next month (PageDown)',
previousYear: 'Last year (Control + left)',
nextYear: 'Next year (Control + right)',
previousDecade: 'Last decade',
nextDecade: 'Next decade',
previousCentury: 'Last century',
nextCentury: 'Next century'
};
var locale$1 = {
placeholder: 'Select time',
rangePlaceholder: ['Start time', 'End time']
};
var TimePicker = locale$1;
// Merge into a locale object
var locale = {
lang: _extends$1({
placeholder: 'Select date',
yearPlaceholder: 'Select year',
quarterPlaceholder: 'Select quarter',
monthPlaceholder: 'Select month',
weekPlaceholder: 'Select week',
rangePlaceholder: ['Start date', 'End date'],
rangeYearPlaceholder: ['Start year', 'End year'],
rangeQuarterPlaceholder: ['Start quarter', 'End quarter'],
rangeMonthPlaceholder: ['Start month', 'End month'],
rangeWeekPlaceholder: ['Start week', 'End week']
}, locale$2),
timePickerLocale: _extends$1({}, TimePicker)
};
// All settings at:
// https://github.com/ant-design/ant-design/blob/master/components/date-picker/locale/example.json
var enUS = locale;
/* eslint-disable no-template-curly-in-string */
var typeTemplate = '${label} is not a valid ${type}';
var localeValues = {
locale: 'en',
Pagination: enUS$1,
DatePicker: enUS,
TimePicker: TimePicker,
Calendar: enUS,
global: {
placeholder: 'Please select'
},
Table: {
filterTitle: 'Filter menu',
filterConfirm: 'OK',
filterReset: 'Reset',
filterEmptyText: 'No filters',
filterCheckall: 'Select all items',
filterSearchPlaceholder: 'Search in filters',
emptyText: 'No data',
selectAll: 'Select current page',
selectInvert: 'Invert current page',
selectNone: 'Clear all data',
selectionAll: 'Select all data',
sortTitle: 'Sort',
expand: 'Expand row',
collapse: 'Collapse row',
triggerDesc: 'Click to sort descending',
triggerAsc: 'Click to sort ascending',
cancelSort: 'Click to cancel sorting'
},
Tour: {
Next: 'Next',
Previous: 'Previous',
Finish: 'Finish'
},
Modal: {
okText: 'OK',
cancelText: 'Cancel',
justOkText: 'OK'
},
Popconfirm: {
okText: 'OK',
cancelText: 'Cancel'
},
Transfer: {
titles: ['', ''],
searchPlaceholder: 'Search here',
itemUnit: 'item',
itemsUnit: 'items',
remove: 'Remove',
selectCurrent: 'Select current page',
removeCurrent: 'Remove current page',
selectAll: 'Select all data',
removeAll: 'Remove all data',
selectInvert: 'Invert current page'
},
Upload: {
uploading: 'Uploading...',
removeFile: 'Remove file',
uploadError: 'Upload error',
previewFile: 'Preview file',
downloadFile: 'Download file'
},
Empty: {
description: 'No data'
},
Icon: {
icon: 'icon'
},
Text: {
edit: 'Edit',
copy: 'Copy',
copied: 'Copied',
expand: 'Expand'
},
PageHeader: {
back: 'Back'
},
Form: {
optional: '(optional)',
defaultValidateMessages: {
"default": 'Field validation error for ${label}',
required: 'Please enter ${label}',
"enum": '${label} must be one of [${enum}]',
whitespace: '${label} cannot be a blank character',
date: {
format: '${label} date format is invalid',
parse: '${label} cannot be converted to a date',
invalid: '${label} is an invalid date'
},
types: {
string: typeTemplate,
method: typeTemplate,
array: typeTemplate,
object: typeTemplate,
number: typeTemplate,
date: typeTemplate,
"boolean": typeTemplate,
integer: typeTemplate,
"float": typeTemplate,
regexp: typeTemplate,
email: typeTemplate,
url: typeTemplate,
hex: typeTemplate
},
string: {
len: '${label} must be ${len} characters',
min: '${label} must be at least ${min} characters',
max: '${label} must be up to ${max} characters',
range: '${label} must be between ${min}-${max} characters'
},
number: {
len: '${label} must be equal to ${len}',
min: '${label} must be minimum ${min}',
max: '${label} must be maximum ${max}',
range: '${label} must be between ${min}-${max}'
},
array: {
len: 'Must be ${len} ${label}',
min: 'At least ${min} ${label}',
max: 'At most ${max} ${label}',
range: 'The amount of ${label} must be between ${min}-${max}'
},
pattern: {
mismatch: '${label} does not match the pattern ${pattern}'
}
}
},
Image: {
preview: 'Preview'
}
};
var defaultLocale = localeValues;
var runtimeLocale = _extends$1({}, defaultLocale.Modal);
function changeConfirmLocale(newLocale) {
if (newLocale) {
runtimeLocale = _extends$1(_extends$1({}, runtimeLocale), newLocale);
} else {
runtimeLocale = _extends$1({}, defaultLocale.Modal);
}
}
var LocaleContext = /*#__PURE__*/createContext(undefined);
var LocaleContext$1 = LocaleContext;
var ANT_MARK = 'internalMark';
var LocaleProvider = function LocaleProvider(props) {
var _props$locale = props.locale,
locale = _props$locale === void 0 ? {} : _props$locale,
children = props.children,
_ANT_MARK__ = props._ANT_MARK__;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== "production" ? warning$2(_ANT_MARK__ === ANT_MARK, 'LocaleProvider', '`LocaleProvider` is deprecated. Please use `locale` with `ConfigProvider` instead: http://u.ant.design/locale') : void 0;
}
React.useEffect(function () {
changeConfirmLocale(locale && locale.Modal);
return function () {
changeConfirmLocale();
};
}, [locale]);
var getMemoizedContextValue = React.useMemo(function () {
return _extends$1(_extends$1({}, locale), {
exist: true
});
}, [locale]);
return /*#__PURE__*/React.createElement(LocaleContext$1.Provider, {
value: getMemoizedContextValue
}, children);
};
var LocaleProvider$1 = LocaleProvider;
var LocaleReceiver = function LocaleReceiver(props) {
var _props$componentName = props.componentName,
componentName = _props$componentName === void 0 ? 'global' : _props$componentName,
defaultLocale$1 = props.defaultLocale,
children = props.children;
var antLocale = React.useContext(LocaleContext$1);
var getLocale = React.useMemo(function () {
var _a;
var locale = defaultLocale$1 || defaultLocale[componentName];
var localeFromContext = (_a = antLocale === null || antLocale === void 0 ? void 0 : antLocale[componentName]) !== null && _a !== void 0 ? _a : {};
return _extends$1(_extends$1({}, locale instanceof Function ? locale() : locale), localeFromContext || {});
}, [componentName, defaultLocale$1, antLocale]);
var getLocaleCode = React.useMemo(function () {
var localeCode = antLocale && antLocale.locale;
// Had use LocaleProvide but didn't set locale
if (antLocale && antLocale.exist && !localeCode) {
return defaultLocale.locale;
}
return localeCode;
}, [antLocale]);
return children(getLocale, getLocaleCode, antLocale);
};
var LocaleReceiver$1 = LocaleReceiver;
var version = '5.0.5';
var PresetColors = ['blue', 'purple', 'cyan', 'green', 'magenta', 'pink', 'red', 'orange', 'yellow', 'volcano', 'geekblue', 'lime', 'gold'];
var hueStep = 2; // 色相阶梯
var saturationStep = 0.16; // 饱和度阶梯,浅色部分
var saturationStep2 = 0.05; // 饱和度阶梯,深色部分
var brightnessStep1 = 0.05; // 亮度阶梯,浅色部分
var brightnessStep2 = 0.15; // 亮度阶梯,深色部分
var lightColorCount = 5; // 浅色数量,主色上
var darkColorCount = 4; // 深色数量,主色下
// 暗色主题颜色映射关系表
var darkColorMap = [{
index: 7,
opacity: 0.15
}, {
index: 6,
opacity: 0.25
}, {
index: 5,
opacity: 0.3
}, {
index: 5,
opacity: 0.45
}, {
index: 5,
opacity: 0.65
}, {
index: 5,
opacity: 0.85
}, {
index: 4,
opacity: 0.9
}, {
index: 3,
opacity: 0.95
}, {
index: 2,
opacity: 0.97
}, {
index: 1,
opacity: 0.98
}]; // Wrapper function ported from TinyColor.prototype.toHsv
// Keep it here because of `hsv.h * 360`
function toHsv(_ref) {
var r = _ref.r,
g = _ref.g,
b = _ref.b;
var hsv = rgbToHsv(r, g, b);
return {
h: hsv.h * 360,
s: hsv.s,
v: hsv.v
};
} // Wrapper function ported from TinyColor.prototype.toHexString
// Keep it here because of the prefix `#`
function toHex(_ref2) {
var r = _ref2.r,
g = _ref2.g,
b = _ref2.b;
return "#".concat(rgbToHex(r, g, b, false));
} // Wrapper function ported from TinyColor.prototype.mix, not treeshakable.
// Amount in range [0, 1]
// Assume color1 & color2 has no alpha, since the following src code did so.
function mix$1(rgb1, rgb2, amount) {
var p = amount / 100;
var rgb = {
r: (rgb2.r - rgb1.r) * p + rgb1.r,
g: (rgb2.g - rgb1.g) * p + rgb1.g,
b: (rgb2.b - rgb1.b) * p + rgb1.b
};
return rgb;
}
function getHue(hsv, i, light) {
var hue; // 根据色相不同,色相转向不同
if (Math.round(hsv.h) >= 60 && Math.round(hsv.h) <= 240) {
hue = light ? Math.round(hsv.h) - hueStep * i : Math.round(hsv.h) + hueStep * i;
} else {
hue = light ? Math.round(hsv.h) + hueStep * i : Math.round(hsv.h) - hueStep * i;
}
if (hue < 0) {
hue += 360;
} else if (hue >= 360) {
hue -= 360;
}
return hue;
}
function getSaturation(hsv, i, light) {
// grey color don't change saturation
if (hsv.h === 0 && hsv.s === 0) {
return hsv.s;
}
var saturation;
if (light) {
saturation = hsv.s - saturationStep * i;
} else if (i === darkColorCount) {
saturation = hsv.s + saturationStep;
} else {
saturation = hsv.s + saturationStep2 * i;
} // 边界值修正
if (saturation > 1) {
saturation = 1;
} // 第一格的 s 限制在 0.06-0.1 之间
if (light && i === lightColorCount && saturation > 0.1) {
saturation = 0.1;
}
if (saturation < 0.06) {
saturation = 0.06;
}
return Number(saturation.toFixed(2));
}
function getValue(hsv, i, light) {
var value;
if (light) {
value = hsv.v + brightnessStep1 * i;
} else {
value = hsv.v - brightnessStep2 * i;
}
if (value > 1) {
value = 1;
}
return Number(value.toFixed(2));
}
function generate$1(color) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var patterns = [];
var pColor = inputToRGB(color);
for (var i = lightColorCount; i > 0; i -= 1) {
var hsv = toHsv(pColor);
var colorString = toHex(inputToRGB({
h: getHue(hsv, i, true),
s: getSaturation(hsv, i, true),
v: getValue(hsv, i, true)
}));
patterns.push(colorString);
}
patterns.push(toHex(pColor));
for (var _i = 1; _i <= darkColorCount; _i += 1) {
var _hsv = toHsv(pColor);
var _colorString = toHex(inputToRGB({
h: getHue(_hsv, _i),
s: getSaturation(_hsv, _i),
v: getValue(_hsv, _i)
}));
patterns.push(_colorString);
} // dark theme patterns
if (opts.theme === 'dark') {
return darkColorMap.map(function (_ref3) {
var index = _ref3.index,
opacity = _ref3.opacity;
var darkColorString = toHex(mix$1(inputToRGB(opts.backgroundColor || '#141414'), inputToRGB(patterns[index]), opacity * 100));
return darkColorString;
});
}
return patterns;
}
var presetPrimaryColors = {
red: '#F5222D',
volcano: '#FA541C',
orange: '#FA8C16',
gold: '#FAAD14',
yellow: '#FADB14',
lime: '#A0D911',
green: '#52C41A',
cyan: '#13C2C2',
blue: '#1890FF',
geekblue: '#2F54EB',
purple: '#722ED1',
magenta: '#EB2F96',
grey: '#666666'
};
var presetPalettes = {};
var presetDarkPalettes = {};
Object.keys(presetPrimaryColors).forEach(function (key) {
presetPalettes[key] = generate$1(presetPrimaryColors[key]);
presetPalettes[key].primary = presetPalettes[key][5]; // dark presetPalettes
presetDarkPalettes[key] = generate$1(presetPrimaryColors[key], {
theme: 'dark',
backgroundColor: '#141414'
});
presetDarkPalettes[key].primary = presetDarkPalettes[key][5];
});
var genControlHeight = function genControlHeight(token) {
var controlHeight = token.controlHeight;
return {
controlHeightSM: controlHeight * 0.75,
controlHeightXS: controlHeight * 0.5,
controlHeightLG: controlHeight * 1.25
};
};
var genControlHeight$1 = genControlHeight;
function genSizeMapToken(token) {
var sizeUnit = token.sizeUnit,
sizeStep = token.sizeStep;
return {
sizeXXL: sizeUnit * (sizeStep + 8),
sizeXL: sizeUnit * (sizeStep + 4),
sizeLG: sizeUnit * (sizeStep + 2),
sizeMD: sizeUnit * (sizeStep + 1),
sizeMS: sizeUnit * sizeStep,
size: sizeUnit * sizeStep,
sizeSM: sizeUnit * (sizeStep - 1),
sizeXS: sizeUnit * (sizeStep - 2),
sizeXXS: sizeUnit * (sizeStep - 3) // 4
};
}
var defaultPresetColors = {
blue: '#1677ff',
purple: '#722ED1',
cyan: '#13C2C2',
green: '#52C41A',
magenta: '#EB2F96',
pink: '#eb2f96',
red: '#F5222D',
orange: '#FA8C16',
yellow: '#FADB14',
volcano: '#FA541C',
geekblue: '#2F54EB',
gold: '#FAAD14',
lime: '#A0D911'
};
var seedToken = _extends$1(_extends$1({}, defaultPresetColors), {
// Color
colorPrimary: '#1677ff',
colorSuccess: '#52c41a',
colorWarning: '#faad14',
colorError: '#ff4d4f',
colorInfo: '#1677ff',
colorTextBase: '',
colorBgBase: '',
// Font
fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,\n'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',\n'Noto Color Emoji'",
fontSize: 14,
// Line
lineWidth: 1,
lineType: 'solid',
// Motion
motionUnit: 0.1,
motionBase: 0,
motionEaseOutCirc: "cubic-bezier(0.08, 0.82, 0.17, 1)",
motionEaseInOutCirc: "cubic-bezier(0.78, 0.14, 0.15, 0.86)",
motionEaseOut: 'cubic-bezier(0.215, 0.61, 0.355, 1)',
motionEaseInOut: "cubic-bezier(0.645, 0.045, 0.355, 1)",
motionEaseOutBack: "cubic-bezier(0.12, 0.4, 0.29, 1.46)",
motionEaseInBack: "cubic-bezier(0.71, -0.46, 0.88, 0.6)",
motionEaseInQuint: "cubic-bezier(0.645, 0.045, 0.355, 1)",
motionEaseOutQuint: "cubic-bezier(0.23, 1, 0.32, 1)",
// Radius
borderRadius: 6,
// Size
sizeUnit: 4,
sizeStep: 4,
sizePopupArrow: 16,
// Control Base
controlHeight: 32,
// zIndex
zIndexBase: 0,
zIndexPopupBase: 1000,
// Image
opacityImage: 1,
// Wireframe
wireframe: false
});
var defaultSeedToken = seedToken;
function genColorMapToken(seed, _ref) {
var generateColorPalettes = _ref.generateColorPalettes,
generateNeutralColorPalettes = _ref.generateNeutralColorPalettes;
var colorSuccessBase = seed.colorSuccess,
colorWarningBase = seed.colorWarning,
colorErrorBase = seed.colorError,
colorInfoBase = seed.colorInfo,
colorPrimaryBase = seed.colorPrimary,
colorBgBase = seed.colorBgBase,
colorTextBase = seed.colorTextBase;
var primaryColors = generateColorPalettes(colorPrimaryBase);
var successColors = generateColorPalettes(colorSuccessBase);
var warningColors = generateColorPalettes(colorWarningBase);
var errorColors = generateColorPalettes(colorErrorBase);
var infoColors = generateColorPalettes(colorInfoBase);
var neutralColors = generateNeutralColorPalettes(colorBgBase, colorTextBase);
return _extends$1(_extends$1({}, neutralColors), {
colorPrimaryBg: primaryColors[1],
colorPrimaryBgHover: primaryColors[2],
colorPrimaryBorder: primaryColors[3],
colorPrimaryBorderHover: primaryColors[4],
colorPrimaryHover: primaryColors[5],
colorPrimary: primaryColors[6],
colorPrimaryActive: primaryColors[7],
colorPrimaryTextHover: primaryColors[8],
colorPrimaryText: primaryColors[9],
colorPrimaryTextActive: primaryColors[10],
colorSuccessBg: successColors[1],
colorSuccessBgHover: successColors[2],
colorSuccessBorder: successColors[3],
colorSuccessBorderHover: successColors[4],
colorSuccessHover: successColors[4],
colorSuccess: successColors[6],
colorSuccessActive: successColors[7],
colorSuccessTextHover: successColors[8],
colorSuccessText: successColors[9],
colorSuccessTextActive: successColors[10],
colorErrorBg: errorColors[1],
colorErrorBgHover: errorColors[2],
colorErrorBorder: errorColors[3],
colorErrorBorderHover: errorColors[4],
colorErrorHover: errorColors[5],
colorError: errorColors[6],
colorErrorActive: errorColors[7],
colorErrorTextHover: errorColors[8],
colorErrorText: errorColors[9],
colorErrorTextActive: errorColors[10],
colorWarningBg: warningColors[1],
colorWarningBgHover: warningColors[2],
colorWarningBorder: warningColors[3],
colorWarningBorderHover: warningColors[4],
colorWarningHover: warningColors[4],
colorWarning: warningColors[6],
colorWarningActive: warningColors[7],
colorWarningTextHover: warningColors[8],
colorWarningText: warningColors[9],
colorWarningTextActive: warningColors[10],
colorInfoBg: infoColors[1],
colorInfoBgHover: infoColors[2],
colorInfoBorder: infoColors[3],
colorInfoBorderHover: infoColors[4],
colorInfoHover: infoColors[4],
colorInfo: infoColors[6],
colorInfoActive: infoColors[7],
colorInfoTextHover: infoColors[8],
colorInfoText: infoColors[9],
colorInfoTextActive: infoColors[10],
colorBgMask: new TinyColor('#000').setAlpha(0.45).toRgbString(),
colorWhite: '#fff'
});
}
// https://zhuanlan.zhihu.com/p/32746810
function getFontSizes(base) {
var fontSizes = new Array(10).fill(null).map(function (_, index) {
var i = index - 1;
var baseSize = base * Math.pow(2.71828, i / 5);
var intSize = index > 1 ? Math.floor(baseSize) : Math.ceil(baseSize);
// Convert to even
return Math.floor(intSize / 2) * 2;
});
fontSizes[1] = base;
return fontSizes.map(function (size) {
var height = size + 8;
return {
size: size,
lineHeight: height / size
};
});
}
var genRadius = function genRadius(radiusBase) {
var radiusLG = radiusBase;
var radiusSM = radiusBase;
var radiusXS = radiusBase;
var radiusOuter = radiusBase;
// radiusLG
if (radiusBase < 6 && radiusBase >= 5) {
radiusLG = radiusBase + 1;
} else if (radiusBase < 16 && radiusBase >= 6) {
radiusLG = radiusBase + 2;
} else if (radiusBase >= 16) {
radiusLG = 16;
}
// radiusSM
if (radiusBase < 7 && radiusBase >= 5) {
radiusSM = 4;
} else if (radiusBase < 8 && radiusBase >= 7) {
radiusSM = 5;
} else if (radiusBase < 14 && radiusBase >= 8) {
radiusSM = 6;
} else if (radiusBase < 16 && radiusBase >= 14) {
radiusSM = 7;
} else if (radiusBase >= 16) {
radiusSM = 8;
}
// radiusXS
if (radiusBase < 6 && radiusBase >= 2) {
radiusXS = 1;
} else if (radiusBase >= 6) {
radiusXS = 2;
}
// radiusOuter
if (radiusBase > 4 && radiusBase < 8) {
radiusOuter = 4;
} else if (radiusBase >= 8) {
radiusOuter = 6;
}
return {
borderRadius: radiusBase > 16 ? 16 : radiusBase,
borderRadiusXS: radiusXS,
borderRadiusSM: radiusSM,
borderRadiusLG: radiusLG,
borderRadiusOuter: radiusOuter
};
};
var genRadius$1 = genRadius;
function genCommonMapToken(token) {
var motionUnit = token.motionUnit,
motionBase = token.motionBase,
fontSize = token.fontSize,
borderRadius = token.borderRadius,
lineWidth = token.lineWidth;
var fontSizes = getFontSizes(fontSize);
return _extends$1({
// motion
motionDurationFast: (motionBase + motionUnit).toFixed(1) + "s",
motionDurationMid: (motionBase + motionUnit * 2).toFixed(1) + "s",
motionDurationSlow: (motionBase + motionUnit * 3).toFixed(1) + "s",
// font
fontSizes: fontSizes.map(function (fs) {
return fs.size;
}),
lineHeights: fontSizes.map(function (fs) {
return fs.lineHeight;
}),
// line
lineWidthBold: lineWidth + 1
}, genRadius$1(borderRadius));
}
var getAlphaColor$1 = function getAlphaColor(baseColor, alpha) {
return new TinyColor(baseColor).setAlpha(alpha).toRgbString();
};
var getSolidColor = function getSolidColor(baseColor, brightness) {
var instance = new TinyColor(baseColor);
return instance.darken(brightness).toHexString();
};
var generateColorPalettes = function generateColorPalettes(baseColor) {
var colors = generate$1(baseColor);
return {
1: colors[0],
2: colors[1],
3: colors[2],
4: colors[3],
5: colors[4],
6: colors[5],
7: colors[6],
8: colors[4],
9: colors[5],
10: colors[6]
// 8: colors[7],
// 9: colors[8],
// 10: colors[9],
};
};
var generateNeutralColorPalettes = function generateNeutralColorPalettes(bgBaseColor, textBaseColor) {
var colorBgBase = bgBaseColor || '#fff';
var colorTextBase = textBaseColor || '#000';
return {
colorBgBase: colorBgBase,
colorTextBase: colorTextBase,
colorText: getAlphaColor$1(colorTextBase, 0.88),
colorTextSecondary: getAlphaColor$1(colorTextBase, 0.65),
colorTextTertiary: getAlphaColor$1(colorTextBase, 0.45),
colorTextQuaternary: getAlphaColor$1(colorTextBase, 0.25),
colorFill: getAlphaColor$1(colorTextBase, 0.15),
colorFillSecondary: getAlphaColor$1(colorTextBase, 0.06),
colorFillTertiary: getAlphaColor$1(colorTextBase, 0.04),
colorFillQuaternary: getAlphaColor$1(colorTextBase, 0.02),
colorBgLayout: getSolidColor(colorBgBase, 4),
colorBgContainer: getSolidColor(colorBgBase, 0),
colorBgElevated: getSolidColor(colorBgBase, 0),
colorBgSpotlight: getAlphaColor$1(colorTextBase, 0.85),
colorBorder: getSolidColor(colorBgBase, 15),
colorBorderSecondary: getSolidColor(colorBgBase, 6)
};
};
function derivative(token) {
var colorPalettes = Object.keys(defaultPresetColors).map(function (colorKey) {
var colors = generate$1(token[colorKey]);
return new Array(10).fill(1).reduce(function (prev, _, i) {
prev[colorKey + "-" + (i + 1)] = colors[i];
return prev;
}, {});
}).reduce(function (prev, cur) {
prev = _extends$1(_extends$1({}, prev), cur);
return prev;
}, {});
return _extends$1(_extends$1(_extends$1(_extends$1(_extends$1(_extends$1({}, token), colorPalettes), genColorMapToken(token, {
generateColorPalettes: generateColorPalettes,
generateNeutralColorPalettes: generateNeutralColorPalettes
})), genSizeMapToken(token)), genControlHeight$1(token)), genCommonMapToken(token));
}
function isStableColor(color) {
return color >= 0 && color <= 255;
}
function getAlphaColor(frontColor, backgroundColor) {
var _TinyColor$toRgb = new TinyColor(frontColor).toRgb(),
fR = _TinyColor$toRgb.r,
fG = _TinyColor$toRgb.g,
fB = _TinyColor$toRgb.b,
originAlpha = _TinyColor$toRgb.a;
if (originAlpha < 1) {
return frontColor;
}
var _TinyColor$toRgb2 = new TinyColor(backgroundColor).toRgb(),
bR = _TinyColor$toRgb2.r,
bG = _TinyColor$toRgb2.g,
bB = _TinyColor$toRgb2.b;
for (var fA = 0.01; fA <= 1; fA += 0.01) {
var r = Math.round((fR - bR * (1 - fA)) / fA);
var g = Math.round((fG - bG * (1 - fA)) / fA);
var b = Math.round((fB - bB * (1 - fA)) / fA);
if (isStableColor(r) && isStableColor(g) && isStableColor(b)) return new TinyColor({
r: r,
g: g,
b: b,
a: Math.round(fA * 100) / 100
}).toRgbString();
}
// fallback
/* istanbul ignore next */
return new TinyColor({
r: fR,
g: fG,
b: fB,
a: 1
}).toRgbString();
}
var __rest$g = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
/**
* Seed (designer) > Derivative (designer) > Alias (developer).
*
* Merge seed & derivative & override token and generate alias token for developer.
*/
function formatToken(derivativeToken) {
var override = derivativeToken.override,
restToken = __rest$g(derivativeToken, ["override"]);
var overrideTokens = _extends$1({}, override);
Object.keys(defaultSeedToken).forEach(function (token) {
delete overrideTokens[token];
});
var mergedToken = _extends$1(_extends$1({}, restToken), overrideTokens);
var fontSizes = mergedToken.fontSizes,
lineHeights = mergedToken.lineHeights;
var screenXS = 480;
var screenSM = 576;
var screenMD = 768;
var screenLG = 992;
var screenXL = 1200;
var screenXXL = 1600;
var fontSizeSM = fontSizes[0];
// Generate alias token
var aliasToken = _extends$1(_extends$1(_extends$1({}, mergedToken), {
colorLink: mergedToken.colorInfoText,
colorLinkHover: mergedToken.colorInfoHover,
colorLinkActive: mergedToken.colorInfoActive,
// ============== Background ============== //
colorFillContent: mergedToken.colorFillSecondary,
colorFillContentHover: mergedToken.colorFill,
colorFillAlter: mergedToken.colorFillQuaternary,
colorBgContainerDisabled: mergedToken.colorFillTertiary,
// ============== Split ============== //
colorBorderBg: mergedToken.colorBgContainer,
colorSplit: getAlphaColor(mergedToken.colorBorderSecondary, mergedToken.colorBgContainer),
// ============== Text ============== //
colorTextPlaceholder: mergedToken.colorTextQuaternary,
colorTextDisabled: mergedToken.colorTextQuaternary,
colorTextHeading: mergedToken.colorText,
colorTextLabel: mergedToken.colorTextSecondary,
colorTextDescription: mergedToken.colorTextTertiary,
colorTextLightSolid: mergedToken.colorWhite,
colorHighlight: mergedToken.colorError,
colorBgTextHover: mergedToken.colorFillSecondary,
colorBgTextActive: mergedToken.colorFill,
colorIcon: mergedToken.colorTextTertiary,
colorIconHover: mergedToken.colorText,
colorErrorOutline: getAlphaColor(mergedToken.colorErrorBg, mergedToken.colorBgContainer),
colorWarningOutline: getAlphaColor(mergedToken.colorWarningBg, mergedToken.colorBgContainer),
// Font
fontSizeSM: fontSizeSM,
fontSize: fontSizes[1],
fontSizeLG: fontSizes[2],
fontSizeXL: fontSizes[3],
fontSizeHeading1: fontSizes[6],
fontSizeHeading2: fontSizes[5],
fontSizeHeading3: fontSizes[4],
fontSizeHeading4: fontSizes[3],
fontSizeHeading5: fontSizes[2],
fontSizeIcon: fontSizeSM,
lineHeight: lineHeights[1],
lineHeightLG: lineHeights[2],
lineHeightSM: lineHeights[0],
lineHeightHeading1: lineHeights[6],
lineHeightHeading2: lineHeights[5],
lineHeightHeading3: lineHeights[4],
lineHeightHeading4: lineHeights[3],
lineHeightHeading5: lineHeights[2],
// Control
lineWidth: mergedToken.lineWidth,
controlOutlineWidth: mergedToken.lineWidth * 2,
// Checkbox size and expand icon size
controlInteractiveSize: mergedToken.controlHeight / 2,
controlItemBgHover: mergedToken.colorFillTertiary,
controlItemBgActive: mergedToken.colorPrimaryBg,
controlItemBgActiveHover: mergedToken.colorPrimaryBgHover,
controlItemBgActiveDisabled: mergedToken.colorFill,
controlTmpOutline: mergedToken.colorFillQuaternary,
controlOutline: getAlphaColor(mergedToken.colorPrimaryBg, mergedToken.colorBgContainer),
lineType: mergedToken.lineType,
borderRadius: mergedToken.borderRadius,
borderRadiusXS: mergedToken.borderRadiusXS,
borderRadiusSM: mergedToken.borderRadiusSM,
borderRadiusLG: mergedToken.borderRadiusLG,
fontWeightStrong: 600,
opacityLoading: 0.65,
linkDecoration: 'none',
linkHoverDecoration: 'none',
linkFocusDecoration: 'none',
controlPaddingHorizontal: 12,
controlPaddingHorizontalSM: 8,
paddingXXS: mergedToken.sizeXXS,
paddingXS: mergedToken.sizeXS,
paddingSM: mergedToken.sizeSM,
padding: mergedToken.size,
paddingMD: mergedToken.sizeMD,
paddingLG: mergedToken.sizeLG,
paddingXL: mergedToken.sizeXL,
paddingContentHorizontalLG: mergedToken.sizeLG,
paddingContentVerticalLG: mergedToken.sizeMS,
paddingContentHorizontal: mergedToken.sizeMS,
paddingContentVertical: mergedToken.sizeSM,
paddingContentHorizontalSM: mergedToken.size,
paddingContentVerticalSM: mergedToken.sizeXS,
marginXXS: mergedToken.sizeXXS,
marginXS: mergedToken.sizeXS,
marginSM: mergedToken.sizeSM,
margin: mergedToken.size,
marginMD: mergedToken.sizeMD,
marginLG: mergedToken.sizeLG,
marginXL: mergedToken.sizeXL,
marginXXL: mergedToken.sizeXXL,
boxShadow: "\n 0 1px 2px 0 rgba(0, 0, 0, 0.03),\n 0 1px 6px -1px rgba(0, 0, 0, 0.02),\n 0 2px 4px 0 rgba(0, 0, 0, 0.02)\n ",
boxShadowSecondary: "\n 0 6px 16px 0 rgba(0, 0, 0, 0.08),\n 0 3px 6px -4px rgba(0, 0, 0, 0.12),\n 0 9px 28px 8px rgba(0, 0, 0, 0.05)\n ",
screenXS: screenXS,
screenXSMin: screenXS,
screenXSMax: screenSM - 1,
screenSM: screenSM,
screenSMMin: screenSM,
screenSMMax: screenMD - 1,
screenMD: screenMD,
screenMDMin: screenMD,
screenMDMax: screenLG - 1,
screenLG: screenLG,
screenLGMin: screenLG,
screenLGMax: screenXL - 1,
screenXL: screenXL,
screenXLMin: screenXL,
screenXLMax: screenXXL - 1,
screenXXL: screenXXL,
screenXXLMin: screenXXL,
// FIXME: component box-shadow, should be removed
boxShadowPopoverArrow: "3px 3px 7px rgba(0, 0, 0, 0.1)",
boxShadowCard: "\n 0 1px 2px -2px " + new TinyColor('rgba(0, 0, 0, 0.16)').toRgbString() + ",\n 0 3px 6px 0 " + new TinyColor('rgba(0, 0, 0, 0.12)').toRgbString() + ",\n 0 5px 12px 4px " + new TinyColor('rgba(0, 0, 0, 0.09)').toRgbString() + "\n ",
boxShadowDrawerRight: "\n -6px 0 16px 0 rgba(0, 0, 0, 0.08),\n -3px 0 6px -4px rgba(0, 0, 0, 0.12),\n -9px 0 28px 8px rgba(0, 0, 0, 0.05)\n ",
boxShadowDrawerLeft: "\n 6px 0 16px 0 rgba(0, 0, 0, 0.08),\n 3px 0 6px -4px rgba(0, 0, 0, 0.12),\n 9px 0 28px 8px rgba(0, 0, 0, 0.05)\n ",
boxShadowDrawerUp: "\n 0 6px 16px 0 rgba(0, 0, 0, 0.08),\n 0 3px 6px -4px rgba(0, 0, 0, 0.12),\n 0 9px 28px 8px rgba(0, 0, 0, 0.05)\n ",
boxShadowDrawerDown: "\n 0 -6px 16px 0 rgba(0, 0, 0, 0.08),\n 0 -3px 6px -4px rgba(0, 0, 0, 0.12),\n 0 -9px 28px 8px rgba(0, 0, 0, 0.05)\n ",
boxShadowTabsOverflowLeft: "inset 10px 0 8px -8px rgba(0, 0, 0, 0.08)",
boxShadowTabsOverflowRight: "inset -10px 0 8px -8px rgba(0, 0, 0, 0.08)",
boxShadowTabsOverflowTop: "inset 0 10px 8px -8px rgba(0, 0, 0, 0.08)",
boxShadowTabsOverflowBottom: "inset 0 -10px 8px -8px rgba(0, 0, 0, 0.08)"
}), overrideTokens);
return aliasToken;
}
var roundedArrow = function roundedArrow(width, innerRadius, outerRadius, bgColor, boxShadow) {
var unitWidth = width / 2;
var ax = unitWidth - outerRadius * (Math.sqrt(2) - 1);
var ay = unitWidth;
var bx = unitWidth + outerRadius * (1 - 1 / Math.sqrt(2));
var by = unitWidth - outerRadius * (1 - 1 / Math.sqrt(2));
var cx = 2 * unitWidth - innerRadius * (1 / Math.sqrt(2));
var cy = innerRadius * (1 / Math.sqrt(2));
var dx = 4 * unitWidth - cx;
var dy = cy;
var ex = 4 * unitWidth - bx;
var ey = by;
var fx = 4 * unitWidth - ax;
var fy = ay;
return {
borderRadius: {
_skip_check_: true,
value: "0 0 " + innerRadius + "px"
},
pointerEvents: 'none',
width: width * 2,
height: width * 2,
overflow: 'hidden',
'&::after': {
content: '""',
position: 'absolute',
width: width / Math.sqrt(2),
height: width / Math.sqrt(2),
bottom: 0,
insetInline: 0,
margin: 'auto',
borderRadius: {
_skip_check_: true,
value: "0 0 " + innerRadius + "px 0"
},
transform: 'translateY(50%) rotate(-135deg)',
boxShadow: boxShadow,
zIndex: 0,
background: 'transparent'
},
'&::before': {
position: 'absolute',
bottom: 0,
insetInlineStart: 0,
width: width * 2,
height: width / 2,
background: bgColor,
clipPath: "path('M " + ax + " " + ay + " A " + outerRadius + " " + outerRadius + " 0 0 0 " + bx + " " + by + " L " + cx + " " + cy + " A " + innerRadius + " " + innerRadius + " 0 0 1 " + dx + " " + dy + " L " + ex + " " + ey + " A " + outerRadius + " " + outerRadius + " 0 0 0 " + fx + " " + fy + " Z')",
content: '""'
}
};
};
var textEllipsis = {
overflow: 'hidden',
whiteSpace: 'nowrap',
textOverflow: 'ellipsis'
};
var resetComponent = function resetComponent(token) {
return {
boxSizing: 'border-box',
margin: 0,
padding: 0,
color: token.colorText,
fontSize: token.fontSize,
// font-variant: @font-variant-base;
lineHeight: token.lineHeight,
listStyle: 'none',
// font-feature-settings: @font-feature-settings-base;
fontFamily: token.fontFamily
};
};
var resetIcon = function resetIcon() {
return {
display: 'inline-flex',
alignItems: 'center',
color: 'inherit',
fontStyle: 'normal',
lineHeight: 0,
textAlign: 'center',
textTransform: 'none',
// for SVG icon, see https://blog.prototypr.io/align-svg-icons-to-text-and-say-goodbye-to-font-icons-d44b3d7b26b4
verticalAlign: '-0.125em',
textRendering: 'optimizeLegibility',
'-webkit-font-smoothing': 'antialiased',
'-moz-osx-font-smoothing': 'grayscale',
'> *': {
lineHeight: 1
},
svg: {
display: 'inline-block'
},
'& &-icon': {
display: 'block'
}
};
};
var clearFix = function clearFix() {
return {
// https://github.com/ant-design/ant-design/issues/21301#issuecomment-583955229
'&::before': {
display: 'table',
content: '""'
},
'&::after': {
// https://github.com/ant-design/ant-design/issues/21864
display: 'table',
clear: 'both',
content: '""'
}
};
};
var genLinkStyle = function genLinkStyle(token) {
var _a;
return {
a: (_a = {
color: token.colorLink,
textDecoration: token.linkDecoration,
backgroundColor: 'transparent',
outline: 'none',
cursor: 'pointer',
transition: "color " + token.motionDurationSlow,
'-webkit-text-decoration-skip': 'objects',
'&:hover': {
color: token.colorLinkHover
},
'&:active': {
color: token.colorLinkActive
}
}, _defineProperty$1(_a, "&:active,\n &:hover", {
textDecoration: token.linkHoverDecoration,
outline: 0
}), _defineProperty$1(_a, '&:focus', {
textDecoration: token.linkFocusDecoration,
outline: 0
}), _defineProperty$1(_a, '&[disabled]', {
color: token.colorTextDisabled,
cursor: 'not-allowed'
}), _a)
};
};
var genCommonStyle = function genCommonStyle(token, componentPrefixCls) {
var fontFamily = token.fontFamily,
fontSize = token.fontSize;
var rootPrefixSelector = "[class^=\"" + componentPrefixCls + "\"], [class*=\" " + componentPrefixCls + "\"]";
return _defineProperty$1({}, rootPrefixSelector, _defineProperty$1({
fontFamily: fontFamily,
fontSize: fontSize,
boxSizing: 'border-box',
'&::before, &::after': {
boxSizing: 'border-box'
}
}, rootPrefixSelector, {
boxSizing: 'border-box',
'&::before, &::after': {
boxSizing: 'border-box'
}
}));
};
var genFocusOutline = function genFocusOutline(token) {
return {
outline: token.lineWidth * 4 + "px solid " + token.colorPrimaryBorder,
outlineOffset: 1,
transition: 'outline-offset 0s, outline 0s'
};
};
var genFocusStyle = function genFocusStyle(token) {
return {
'&:focus-visible': _extends$1({}, genFocusOutline(token))
};
};
var defaultIconPrefixCls = 'anticon';
var defaultGetPrefixCls = function defaultGetPrefixCls(suffixCls, customizePrefixCls) {
if (customizePrefixCls) return customizePrefixCls;
return suffixCls ? "ant-" + suffixCls : 'ant';
};
// zombieJ: 🚨 Do not pass `defaultRenderEmpty` here since it will cause circular dependency.
var ConfigContext = /*#__PURE__*/React.createContext({
// We provide a default function for Context without provider
getPrefixCls: defaultGetPrefixCls,
iconPrefixCls: defaultIconPrefixCls
});
var ConfigConsumer = ConfigContext.Consumer;
function genComponentStyleHook(component, styleFn, getDefaultToken) {
return function (prefixCls) {
var _useToken = useToken(),
_useToken2 = _slicedToArray(_useToken, 3),
theme = _useToken2[0],
token = _useToken2[1],
hashId = _useToken2[2];
var _useContext = useContext(ConfigContext),
getPrefixCls = _useContext.getPrefixCls,
iconPrefixCls = _useContext.iconPrefixCls;
var rootPrefixCls = getPrefixCls();
// Generate style for all a tags in antd component.
useStyleRegister({
theme: theme,
token: token,
hashId: hashId,
path: ['Shared', rootPrefixCls]
}, function () {
return [{
// Link
'&': genLinkStyle(token)
}];
});
return [useStyleRegister({
theme: theme,
token: token,
hashId: hashId,
path: [component, prefixCls, iconPrefixCls]
}, function () {
var _statisticToken = statisticToken(token),
proxyToken = _statisticToken.token,
flush = _statisticToken.flush;
var defaultComponentToken = typeof getDefaultToken === 'function' ? getDefaultToken(proxyToken) : getDefaultToken;
var mergedComponentToken = _extends$1(_extends$1({}, defaultComponentToken), token[component]);
var componentCls = "." + prefixCls;
var mergedToken = merge(proxyToken, {
componentCls: componentCls,
prefixCls: prefixCls,
iconCls: "." + iconPrefixCls,
antCls: "." + rootPrefixCls
}, mergedComponentToken);
var styleInterpolation = styleFn(mergedToken, {
hashId: hashId,
prefixCls: prefixCls,
rootPrefixCls: rootPrefixCls,
iconPrefixCls: iconPrefixCls,
overrideComponentToken: token[component]
});
flush(component, mergedComponentToken);
return [genCommonStyle(token, prefixCls), styleInterpolation];
}), hashId];
};
}
var enableStatistic = process.env.NODE_ENV !== 'production' || typeof CSSINJS_STATISTIC !== 'undefined';
var recording = true;
/**
* This function will do as `Object.assign` in production. But will use Object.defineProperty:get to
* pass all value access in development. To support statistic field usage with alias token.
*/
function merge() {
for (var _len = arguments.length, objs = new Array(_len), _key = 0; _key < _len; _key++) {
objs[_key] = arguments[_key];
}
/* istanbul ignore next */
if (!enableStatistic) {
return _extends$1.apply(void 0, [{}].concat(objs));
}
recording = false;
var ret = {};
objs.forEach(function (obj) {
var keys = Object.keys(obj);
keys.forEach(function (key) {
Object.defineProperty(ret, key, {
configurable: true,
enumerable: true,
get: function get() {
return obj[key];
}
});
});
});
recording = true;
return ret;
}
/* istanbul ignore next */
function noop$1() {}
/** Statistic token usage case. Should use `merge` function if you do not want spread record. */
function statisticToken(token) {
var tokenKeys;
var proxy = token;
var flush = noop$1;
if (enableStatistic) {
tokenKeys = new Set();
proxy = new Proxy(token, {
get: function get(obj, prop) {
if (recording) {
tokenKeys.add(prop);
}
return obj[prop];
}
});
flush = function flush(componentName, componentToken) {
({
global: Array.from(tokenKeys),
component: componentToken
});
};
}
return {
token: proxy,
keys: tokenKeys,
flush: flush
};
}
var defaultTheme = createTheme(derivative);
// ================================ Context =================================
// To ensure snapshot stable. We disable hashed in test env.
var defaultConfig = {
token: defaultSeedToken,
hashed: true
};
var DesignTokenContext = /*#__PURE__*/React__default.createContext(defaultConfig);
// ================================== Hook ==================================
function useToken() {
var _React$useContext = React__default.useContext(DesignTokenContext),
rootDesignToken = _React$useContext.token,
hashed = _React$useContext.hashed,
theme = _React$useContext.theme,
components = _React$useContext.components;
var salt = version + "-" + (hashed || '');
var mergedTheme = theme || defaultTheme;
var _useCacheToken = useCacheToken(mergedTheme, [defaultSeedToken, rootDesignToken], {
salt: salt,
override: _extends$1({
override: rootDesignToken
}, components),
formatToken: formatToken
}),
_useCacheToken2 = _slicedToArray(_useCacheToken, 2),
token = _useCacheToken2[0],
hashId = _useCacheToken2[1];
return [mergedTheme, token, hashed ? hashId : ''];
}
/* eslint-disable import/prefer-default-export, prefer-destructuring */
var dynamicStyleMark = "-ant-" + Date.now() + "-" + Math.random();
function getStyle(globalPrefixCls, theme) {
var variables = {};
var formatColor = function formatColor(color, updater) {
var clone = color.clone();
clone = (updater === null || updater === void 0 ? void 0 : updater(clone)) || clone;
return clone.toRgbString();
};
var fillColor = function fillColor(colorVal, type) {
var baseColor = new TinyColor(colorVal);
var colorPalettes = generate$1(baseColor.toRgbString());
variables[type + "-color"] = formatColor(baseColor);
variables[type + "-color-disabled"] = colorPalettes[1];
variables[type + "-color-hover"] = colorPalettes[4];
variables[type + "-color-active"] = colorPalettes[6];
variables[type + "-color-outline"] = baseColor.clone().setAlpha(0.2).toRgbString();
variables[type + "-color-deprecated-bg"] = colorPalettes[0];
variables[type + "-color-deprecated-border"] = colorPalettes[2];
};
// ================ Primary Color ================
if (theme.primaryColor) {
fillColor(theme.primaryColor, 'primary');
var primaryColor = new TinyColor(theme.primaryColor);
var primaryColors = generate$1(primaryColor.toRgbString());
// Legacy - We should use semantic naming standard
primaryColors.forEach(function (color, index) {
variables["primary-" + (index + 1)] = color;
});
// Deprecated
variables['primary-color-deprecated-l-35'] = formatColor(primaryColor, function (c) {
return c.lighten(35);
});
variables['primary-color-deprecated-l-20'] = formatColor(primaryColor, function (c) {
return c.lighten(20);
});
variables['primary-color-deprecated-t-20'] = formatColor(primaryColor, function (c) {
return c.tint(20);
});
variables['primary-color-deprecated-t-50'] = formatColor(primaryColor, function (c) {
return c.tint(50);
});
variables['primary-color-deprecated-f-12'] = formatColor(primaryColor, function (c) {
return c.setAlpha(c.getAlpha() * 0.12);
});
var primaryActiveColor = new TinyColor(primaryColors[0]);
variables['primary-color-active-deprecated-f-30'] = formatColor(primaryActiveColor, function (c) {
return c.setAlpha(c.getAlpha() * 0.3);
});
variables['primary-color-active-deprecated-d-02'] = formatColor(primaryActiveColor, function (c) {
return c.darken(2);
});
}
// ================ Success Color ================
if (theme.successColor) {
fillColor(theme.successColor, 'success');
}
// ================ Warning Color ================
if (theme.warningColor) {
fillColor(theme.warningColor, 'warning');
}
// ================= Error Color =================
if (theme.errorColor) {
fillColor(theme.errorColor, 'error');
}
// ================= Info Color ==================
if (theme.infoColor) {
fillColor(theme.infoColor, 'info');
}
// Convert to css variables
var cssList = Object.keys(variables).map(function (key) {
return "--" + globalPrefixCls + "-" + key + ": " + variables[key] + ";";
});
return ("\n :root {\n " + cssList.join('\n') + "\n }\n ").trim();
}
function registerTheme(globalPrefixCls, theme) {
var style = getStyle(globalPrefixCls, theme);
if (canUseDom()) {
updateCSS(style, dynamicStyleMark + "-dynamic-theme");
} else {
process.env.NODE_ENV !== "production" ? warning$2(false, 'ConfigProvider', 'SSR do not support dynamic theme with css variables.') : void 0;
}
}
var DisabledContext = /*#__PURE__*/React.createContext(false);
var DisabledContextProvider = function DisabledContextProvider(_ref) {
var children = _ref.children,
disabled = _ref.disabled;
var originDisabled = React.useContext(DisabledContext);
return /*#__PURE__*/React.createElement(DisabledContext.Provider, {
value: disabled !== null && disabled !== void 0 ? disabled : originDisabled
}, children);
};
var DisabledContext$1 = DisabledContext;
//
var shallowequal = function shallowEqual(objA, objB, compare, compareContext) {
var ret = compare ? compare.call(compareContext, objA, objB) : void 0;
if (ret !== void 0) {
return !!ret;
}
if (objA === objB) {
return true;
}
if (typeof objA !== "object" || !objA || typeof objB !== "object" || !objB) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB);
// Test for A's keys different from B.
for (var idx = 0; idx < keysA.length; idx++) {
var key = keysA[idx];
if (!bHasOwnProperty(key)) {
return false;
}
var valueA = objA[key];
var valueB = objB[key];
ret = compare ? compare.call(compareContext, valueA, valueB, key) : void 0;
if (ret === false || ret === void 0 && valueA !== valueB) {
return false;
}
}
return true;
};
var shallowEqual = /*@__PURE__*/getDefaultExportFromCjs(shallowequal);
function useTheme(theme, parentTheme) {
var themeConfig = theme || {};
var parentThemeConfig = themeConfig.inherit === false || !parentTheme ? defaultConfig : parentTheme;
var mergedTheme = useMemo(function () {
if (!theme) {
return parentTheme;
}
// Override
var mergedComponents = _extends$1({}, parentThemeConfig.components);
Object.keys(theme.components || {}).forEach(function (componentName) {
mergedComponents[componentName] = _extends$1(_extends$1({}, mergedComponents[componentName]), theme.components[componentName]);
});
// Base token
return _extends$1(_extends$1(_extends$1({}, parentThemeConfig), themeConfig), {
token: _extends$1(_extends$1({}, parentThemeConfig.token), themeConfig.token),
components: mergedComponents
});
}, [themeConfig, parentThemeConfig], function (prev, next) {
return prev.some(function (prevTheme, index) {
var nextTheme = next[index];
return !shallowEqual(prevTheme, nextTheme);
});
});
return mergedTheme;
}
var SizeContext = /*#__PURE__*/React.createContext(undefined);
var SizeContextProvider = function SizeContextProvider(_ref) {
var children = _ref.children,
size = _ref.size;
return /*#__PURE__*/React.createElement(SizeContext.Consumer, null, function (originSize) {
return /*#__PURE__*/React.createElement(SizeContext.Provider, {
value: size || originSize
}, children);
});
};
var SizeContext$1 = SizeContext;
var useStyle$8 = function useStyle(iconPrefixCls) {
var _useToken = useToken(),
_useToken2 = _slicedToArray(_useToken, 2),
theme = _useToken2[0],
token = _useToken2[1];
// Generate style for icons
return useStyleRegister({
theme: theme,
token: token,
hashId: '',
path: ['ant-design-icons', iconPrefixCls]
}, function () {
return [_defineProperty$1({}, "." + iconPrefixCls, resetIcon())];
});
};
var useStyle$9 = useStyle$8;
var __rest$f = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
// These props is used by `useContext` directly in sub component
var PASSED_PROPS = ['getTargetContainer', 'getPopupContainer', 'renderEmpty', 'pageHeader', 'input', 'pagination', 'form'];
var defaultPrefixCls = 'ant';
var globalPrefixCls;
function getGlobalPrefixCls() {
return globalPrefixCls || defaultPrefixCls;
}
var setGlobalConfig = function setGlobalConfig(_ref) {
var prefixCls = _ref.prefixCls;
_ref.iconPrefixCls;
var theme = _ref.theme;
if (prefixCls !== undefined) {
globalPrefixCls = prefixCls;
}
if (theme) {
registerTheme(getGlobalPrefixCls(), theme);
}
};
var ProviderChildren = function ProviderChildren(props) {
var _a, _b;
var children = props.children,
customCsp = props.csp,
autoInsertSpaceInButton = props.autoInsertSpaceInButton,
form = props.form,
locale = props.locale,
componentSize = props.componentSize,
direction = props.direction,
space = props.space,
virtual = props.virtual,
dropdownMatchSelectWidth = props.dropdownMatchSelectWidth,
legacyLocale = props.legacyLocale,
parentContext = props.parentContext,
customIconPrefixCls = props.iconPrefixCls,
theme = props.theme,
componentDisabled = props.componentDisabled;
var getPrefixCls = React.useCallback(function (suffixCls, customizePrefixCls) {
var prefixCls = props.prefixCls;
if (customizePrefixCls) return customizePrefixCls;
var mergedPrefixCls = prefixCls || parentContext.getPrefixCls('');
return suffixCls ? mergedPrefixCls + "-" + suffixCls : mergedPrefixCls;
}, [parentContext.getPrefixCls, props.prefixCls]);
var iconPrefixCls = customIconPrefixCls || parentContext.iconPrefixCls || defaultIconPrefixCls;
var shouldWrapSSR = iconPrefixCls !== parentContext.iconPrefixCls;
var csp = customCsp || parentContext.csp;
var wrapSSR = useStyle$9(iconPrefixCls);
var mergedTheme = useTheme(theme, parentContext.theme);
var config = _extends$1(_extends$1({}, parentContext), {
csp: csp,
autoInsertSpaceInButton: autoInsertSpaceInButton,
locale: locale || legacyLocale,
direction: direction,
space: space,
virtual: virtual,
dropdownMatchSelectWidth: dropdownMatchSelectWidth,
getPrefixCls: getPrefixCls,
iconPrefixCls: iconPrefixCls,
theme: mergedTheme
});
// Pass the props used by `useContext` directly with child component.
// These props should merged into `config`.
PASSED_PROPS.forEach(function (propName) {
var propValue = props[propName];
if (propValue) {
config[propName] = propValue;
}
});
// https://github.com/ant-design/ant-design/issues/27617
var memoedConfig = useMemo(function () {
return config;
}, config, function (prevConfig, currentConfig) {
var prevKeys = Object.keys(prevConfig);
var currentKeys = Object.keys(currentConfig);
return prevKeys.length !== currentKeys.length || prevKeys.some(function (key) {
return prevConfig[key] !== currentConfig[key];
});
});
var memoIconContextValue = React.useMemo(function () {
return {
prefixCls: iconPrefixCls,
csp: csp
};
}, [iconPrefixCls, csp]);
var childNode = shouldWrapSSR ? wrapSSR(children) : children;
// Additional Form provider
var validateMessages = {};
if (locale) {
validateMessages = ((_a = locale.Form) === null || _a === void 0 ? void 0 : _a.defaultValidateMessages) || ((_b = defaultLocale.Form) === null || _b === void 0 ? void 0 : _b.defaultValidateMessages) || {};
}
if (form && form.validateMessages) {
validateMessages = _extends$1(_extends$1({}, validateMessages), form.validateMessages);
}
if (Object.keys(validateMessages).length > 0) {
childNode = /*#__PURE__*/React.createElement(FormProvider, {
validateMessages: validateMessages
}, children);
}
if (locale) {
childNode = /*#__PURE__*/React.createElement(LocaleProvider$1, {
locale: locale,
_ANT_MARK__: ANT_MARK
}, childNode);
}
if (iconPrefixCls || csp) {
childNode = /*#__PURE__*/React.createElement(Context$2.Provider, {
value: memoIconContextValue
}, childNode);
}
if (componentSize) {
childNode = /*#__PURE__*/React.createElement(SizeContextProvider, {
size: componentSize
}, childNode);
}
// ================================ Dynamic theme ================================
var memoTheme = React.useMemo(function () {
var _a = mergedTheme || {},
algorithm = _a.algorithm,
token = _a.token,
rest = __rest$f(_a, ["algorithm", "token"]);
var themeObj = algorithm && (!Array.isArray(algorithm) || algorithm.length > 0) ? createTheme(algorithm) : undefined;
return _extends$1(_extends$1({}, rest), {
theme: themeObj,
token: _extends$1(_extends$1({}, defaultSeedToken), token)
});
}, [mergedTheme]);
if (theme) {
childNode = /*#__PURE__*/React.createElement(DesignTokenContext.Provider, {
value: memoTheme
}, childNode);
}
// =================================== Render ===================================
if (componentDisabled !== undefined) {
childNode = /*#__PURE__*/React.createElement(DisabledContextProvider, {
disabled: componentDisabled
}, childNode);
}
return /*#__PURE__*/React.createElement(ConfigContext.Provider, {
value: memoedConfig
}, childNode);
};
var ConfigProvider = function ConfigProvider(props) {
return /*#__PURE__*/React.createElement(LocaleReceiver$1, null, function (_, __, legacyLocale) {
return /*#__PURE__*/React.createElement(ConfigConsumer, null, function (context) {
return /*#__PURE__*/React.createElement(ProviderChildren, _extends$1({
parentContext: context,
legacyLocale: legacyLocale
}, props));
});
});
};
ConfigProvider.ConfigContext = ConfigContext;
ConfigProvider.SizeContext = SizeContext$1;
ConfigProvider.config = setGlobalConfig;
var raf = function raf(callback) {
return +setTimeout(callback, 16);
};
var caf = function caf(num) {
return clearTimeout(num);
};
if (typeof window !== 'undefined' && 'requestAnimationFrame' in window) {
raf = function raf(callback) {
return window.requestAnimationFrame(callback);
};
caf = function caf(handle) {
return window.cancelAnimationFrame(handle);
};
}
var rafUUID = 0;
var rafIds = new Map();
function cleanup(id) {
rafIds.delete(id);
}
var wrapperRaf$1 = function wrapperRaf(callback) {
var times = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
rafUUID += 1;
var id = rafUUID;
function callRef(leftTimes) {
if (leftTimes === 0) {
// Clean up
cleanup(id);
// Trigger
callback();
} else {
// Next raf
var realId = raf(function () {
callRef(leftTimes - 1);
});
// Bind real raf id
rafIds.set(id, realId);
}
}
callRef(times);
return id;
};
wrapperRaf$1.cancel = function (id) {
var realId = rafIds.get(id);
cleanup(id);
return caf(realId);
};
if (process.env.NODE_ENV !== 'production') {
wrapperRaf$1.ids = function () {
return rafIds;
};
}
function addEventListenerWrap(target, eventType, cb, option) {
/* eslint camelcase: 2 */
var callback = ReactDOM.unstable_batchedUpdates ? function run(e) {
ReactDOM.unstable_batchedUpdates(cb, e);
} : cb;
if (target !== null && target !== void 0 && target.addEventListener) {
target.addEventListener(eventType, callback, option);
}
return {
remove: function remove() {
if (target !== null && target !== void 0 && target.removeEventListener) {
target.removeEventListener(eventType, callback, option);
}
}
};
}
/** 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$1 = freeGlobal || freeSelf || Function('return this')();
var _root = root$1;
var root = _root;
/** Built-in value references. */
var Symbol$4 = root.Symbol;
var _Symbol = Symbol$4;
/**
* 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$1(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$1;
/**
* 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$1 = Array.isArray;
var isArray_1 = isArray$1;
var Symbol$3 = _Symbol;
/** Used for built-in method references. */
var objectProto$1 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto$1.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString$1 = objectProto$1.toString;
/** Built-in value references. */
var symToStringTag$1 = Symbol$3 ? Symbol$3.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.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 = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.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$2 = _Symbol,
getRawTag = _getRawTag,
objectToString = _objectToString;
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag = Symbol$2 ? Symbol$2.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$1(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
}
var _baseGetTag = baseGetTag$1;
/**
* 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$1(value) {
return value != null && typeof value == 'object';
}
var isObjectLike_1 = isObjectLike$1;
var baseGetTag = _baseGetTag,
isObjectLike = isObjectLike_1;
/** `Object#toString` result references. */
var symbolTag = '[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$1(value) {
return typeof value == 'symbol' || isObjectLike(value) && baseGetTag(value) == symbolTag;
}
var isSymbol_1 = isSymbol$1;
var Symbol$1 = _Symbol,
arrayMap = _arrayMap,
isArray = isArray_1,
isSymbol = isSymbol_1;
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined,
symbolToString = symbolProto ? symbolProto.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$1(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString$1) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = value + '';
return result == '0' && 1 / value == -INFINITY ? '-0' : result;
}
var _baseToString = baseToString$1;
var baseToString = _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$4(value) {
return value == null ? '' : baseToString(value);
}
var toString_1 = toString$4;
/**
* 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$1(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return !start && end >= length ? array : baseSlice(array, start, end);
}
var _castSlice = castSlice$1;
/** Used to compose unicode character classes. */
var rsAstralRange$2 = '\\ud800-\\udfff',
rsComboMarksRange$3 = '\\u0300-\\u036f',
reComboHalfMarksRange$3 = '\\ufe20-\\ufe2f',
rsComboSymbolsRange$3 = '\\u20d0-\\u20ff',
rsComboRange$3 = rsComboMarksRange$3 + reComboHalfMarksRange$3 + rsComboSymbolsRange$3,
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$3 + 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$2(string) {
return reHasUnicode.test(string);
}
var _hasUnicode = hasUnicode$2;
/**
* 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$2 = '\\u0300-\\u036f',
reComboHalfMarksRange$2 = '\\ufe20-\\ufe2f',
rsComboSymbolsRange$2 = '\\u20d0-\\u20ff',
rsComboRange$2 = rsComboMarksRange$2 + reComboHalfMarksRange$2 + rsComboSymbolsRange$2,
rsVarRange$1 = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsAstral = '[' + rsAstralRange$1 + ']',
rsCombo$2 = '[' + rsComboRange$2 + ']',
rsFitz$1 = '\\ud83c[\\udffb-\\udfff]',
rsModifier$1 = '(?:' + rsCombo$2 + '|' + 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 = '(?:' + [rsNonAstral$1 + rsCombo$2 + '?', rsCombo$2, rsRegional$1, rsSurrPair$1, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz$1 + '(?=' + rsFitz$1 + ')|' + rsSymbol + 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) || [];
}
var _unicodeToArray = unicodeToArray$1;
var asciiToArray = _asciiToArray,
hasUnicode$1 = _hasUnicode,
unicodeToArray = _unicodeToArray;
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray$1(string) {
return hasUnicode$1(string) ? unicodeToArray(string) : asciiToArray(string);
}
var _stringToArray = stringToArray$1;
var castSlice = _castSlice,
hasUnicode = _hasUnicode,
stringToArray = _stringToArray,
toString$3 = 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$3(string);
var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined;
var chr = strSymbols ? strSymbols[0] : string.charAt(0);
var trailing = strSymbols ? castSlice(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 toString$2 = toString_1,
upperFirst = upperFirst_1;
/**
* Converts the first character of `string` to upper case and the remaining
* to lower case.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to capitalize.
* @returns {string} Returns the capitalized string.
* @example
*
* _.capitalize('FRED');
* // => 'Fred'
*/
function capitalize$1(string) {
return upperFirst(toString$2(string).toLowerCase());
}
var capitalize_1 = capitalize$1;
/**
* 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;
var deburrLetter = _deburrLetter,
toString$1 = 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$1 = '\\u0300-\\u036f',
reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f',
rsComboSymbolsRange$1 = '\\u20d0-\\u20ff',
rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1;
/** Used to compose unicode capture groups. */
var rsCombo$1 = '[' + rsComboRange$1 + ']';
/**
* 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$1, '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$1(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 = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
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 = '\\ufe0e\\ufe0f',
rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
/** Used to compose unicode capture groups. */
var rsApos$1 = "['\u2019]",
rsBreak = '[' + rsBreakRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsDigits = '\\d+',
rsDingbat = '[' + rsDingbatRange + ']',
rsLower = '[' + rsLowerRange + ']',
rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsUpper = '[' + rsUpperRange + ']',
rsZWJ = '\\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 = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',
rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq;
/** 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 = 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(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;
var capitalize = capitalize_1,
createCompounder = _createCompounder;
/**
* Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the camel cased string.
* @example
*
* _.camelCase('Foo Bar');
* // => 'fooBar'
*
* _.camelCase('--foo-bar--');
* // => 'fooBar'
*
* _.camelCase('__FOO_BAR__');
* // => 'fooBar'
*/
var camelCase = createCompounder(function (result, word, index) {
word = word.toLowerCase();
return result + (index ? capitalize(word) : word);
});
var camelCase_1 = camelCase;
var camelCase$1 = /*@__PURE__*/getDefaultExportFromCjs(camelCase_1);
function warning(valid, message) {
warningOnce(valid, "[@ant-design/icons] ".concat(message));
}
function isIconDefinition(target) {
return _typeof$1(target) === 'object' && typeof target.name === 'string' && typeof target.theme === 'string' && (_typeof$1(target.icon) === 'object' || typeof target.icon === 'function');
}
function normalizeAttrs() {
var attrs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return Object.keys(attrs).reduce(function (acc, key) {
var val = attrs[key];
switch (key) {
case 'class':
acc.className = val;
delete acc.class;
break;
default:
delete acc[key];
acc[camelCase$1(key)] = val;
}
return acc;
}, {});
}
function generate(node, key, rootProps) {
if (!rootProps) {
return /*#__PURE__*/React__default.createElement(node.tag, _objectSpread2$1({
key: key
}, normalizeAttrs(node.attrs)), (node.children || []).map(function (child, index) {
return generate(child, "".concat(key, "-").concat(node.tag, "-").concat(index));
}));
}
return /*#__PURE__*/React__default.createElement(node.tag, _objectSpread2$1(_objectSpread2$1({
key: key
}, normalizeAttrs(node.attrs)), rootProps), (node.children || []).map(function (child, index) {
return generate(child, "".concat(key, "-").concat(node.tag, "-").concat(index));
}));
}
function getSecondaryColor(primaryColor) {
// choose the second color
return generate$1(primaryColor)[0];
}
function normalizeTwoToneColors(twoToneColor) {
if (!twoToneColor) {
return [];
}
return Array.isArray(twoToneColor) ? twoToneColor : [twoToneColor];
}
var iconStyles = "\n.anticon {\n display: inline-block;\n color: inherit;\n font-style: normal;\n line-height: 0;\n text-align: center;\n text-transform: none;\n vertical-align: -0.125em;\n text-rendering: optimizeLegibility;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n.anticon > * {\n line-height: 1;\n}\n\n.anticon svg {\n display: inline-block;\n}\n\n.anticon::before {\n display: none;\n}\n\n.anticon .anticon-icon {\n display: block;\n}\n\n.anticon[tabindex] {\n cursor: pointer;\n}\n\n.anticon-spin::before,\n.anticon-spin {\n display: inline-block;\n -webkit-animation: loadingCircle 1s infinite linear;\n animation: loadingCircle 1s infinite linear;\n}\n\n@-webkit-keyframes loadingCircle {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n@keyframes loadingCircle {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n";
var useInsertStyles = function useInsertStyles() {
var styleStr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : iconStyles;
var _useContext = useContext(Context$2),
csp = _useContext.csp;
useEffect(function () {
updateCSS(styleStr, '@ant-design-icons', {
prepend: true,
csp: csp
});
}, []);
};
var _excluded$f = ["icon", "className", "onClick", "style", "primaryColor", "secondaryColor"];
var twoToneColorPalette = {
primaryColor: '#333',
secondaryColor: '#E6E6E6',
calculated: false
};
function setTwoToneColors(_ref) {
var primaryColor = _ref.primaryColor,
secondaryColor = _ref.secondaryColor;
twoToneColorPalette.primaryColor = primaryColor;
twoToneColorPalette.secondaryColor = secondaryColor || getSecondaryColor(primaryColor);
twoToneColorPalette.calculated = !!secondaryColor;
}
function getTwoToneColors() {
return _objectSpread2$1({}, twoToneColorPalette);
}
var IconBase = function IconBase(props) {
var icon = props.icon,
className = props.className,
onClick = props.onClick,
style = props.style,
primaryColor = props.primaryColor,
secondaryColor = props.secondaryColor,
restProps = _objectWithoutProperties(props, _excluded$f);
var colors = twoToneColorPalette;
if (primaryColor) {
colors = {
primaryColor: primaryColor,
secondaryColor: secondaryColor || getSecondaryColor(primaryColor)
};
}
useInsertStyles();
warning(isIconDefinition(icon), "icon should be icon definiton, but got ".concat(icon));
if (!isIconDefinition(icon)) {
return null;
}
var target = icon;
if (target && typeof target.icon === 'function') {
target = _objectSpread2$1(_objectSpread2$1({}, target), {}, {
icon: target.icon(colors.primaryColor, colors.secondaryColor)
});
}
return generate(target.icon, "svg-".concat(target.name), _objectSpread2$1({
className: className,
onClick: onClick,
style: style,
'data-icon': target.name,
width: '1em',
height: '1em',
fill: 'currentColor',
'aria-hidden': 'true'
}, restProps));
};
IconBase.displayName = 'IconReact';
IconBase.getTwoToneColors = getTwoToneColors;
IconBase.setTwoToneColors = setTwoToneColors;
var ReactIcon = IconBase;
function setTwoToneColor(twoToneColor) {
var _normalizeTwoToneColo = normalizeTwoToneColors(twoToneColor),
_normalizeTwoToneColo2 = _slicedToArray(_normalizeTwoToneColo, 2),
primaryColor = _normalizeTwoToneColo2[0],
secondaryColor = _normalizeTwoToneColo2[1];
return ReactIcon.setTwoToneColors({
primaryColor: primaryColor,
secondaryColor: secondaryColor
});
}
function getTwoToneColor() {
var colors = ReactIcon.getTwoToneColors();
if (!colors.calculated) {
return colors.primaryColor;
}
return [colors.primaryColor, colors.secondaryColor];
}
var _excluded$e = ["className", "icon", "spin", "rotate", "tabIndex", "onClick", "twoToneColor"];
// Initial setting
// should move it to antd main repo?
setTwoToneColor('#1890ff');
var Icon$1 = /*#__PURE__*/React.forwardRef(function (props, ref) {
var _classNames;
var className = props.className,
icon = props.icon,
spin = props.spin,
rotate = props.rotate,
tabIndex = props.tabIndex,
onClick = props.onClick,
twoToneColor = props.twoToneColor,
restProps = _objectWithoutProperties(props, _excluded$e);
var _React$useContext = React.useContext(Context$2),
_React$useContext$pre = _React$useContext.prefixCls,
prefixCls = _React$useContext$pre === void 0 ? 'anticon' : _React$useContext$pre,
rootClassName = _React$useContext.rootClassName;
var classString = classNames(rootClassName, prefixCls, (_classNames = {}, _defineProperty$1(_classNames, "".concat(prefixCls, "-").concat(icon.name), !!icon.name), _defineProperty$1(_classNames, "".concat(prefixCls, "-spin"), !!spin || icon.name === 'loading'), _classNames), className);
var iconTabIndex = tabIndex;
if (iconTabIndex === undefined && onClick) {
iconTabIndex = -1;
}
var svgStyle = rotate ? {
msTransform: "rotate(".concat(rotate, "deg)"),
transform: "rotate(".concat(rotate, "deg)")
} : undefined;
var _normalizeTwoToneColo = normalizeTwoToneColors(twoToneColor),
_normalizeTwoToneColo2 = _slicedToArray(_normalizeTwoToneColo, 2),
primaryColor = _normalizeTwoToneColo2[0],
secondaryColor = _normalizeTwoToneColo2[1];
return /*#__PURE__*/React.createElement("span", _objectSpread2$1(_objectSpread2$1({
role: "img",
"aria-label": icon.name
}, restProps), {}, {
ref: ref,
tabIndex: iconTabIndex,
onClick: onClick,
className: classString
}), /*#__PURE__*/React.createElement(ReactIcon, {
icon: icon,
primaryColor: primaryColor,
secondaryColor: secondaryColor,
style: svgStyle
}));
});
Icon$1.displayName = 'AntdIcon';
Icon$1.getTwoToneColor = getTwoToneColor;
Icon$1.setTwoToneColor = setTwoToneColor;
var AntdIcon = Icon$1;
var Context = /*#__PURE__*/React.createContext({});
var DomWrapper = /*#__PURE__*/function (_React$Component) {
_inherits(DomWrapper, _React$Component);
var _super = _createSuper(DomWrapper);
function DomWrapper() {
_classCallCheck(this, DomWrapper);
return _super.apply(this, arguments);
}
_createClass(DomWrapper, [{
key: "render",
value: function render() {
return this.props.children;
}
}]);
return DomWrapper;
}(React.Component);
/**
* Same as React.useState but `setState` accept `ignoreDestroy` param to not to setState after destroyed.
* We do not make this auto is to avoid real memory leak.
* Developer should confirm it's safe to ignore themselves.
*/
function useSafeState(defaultValue) {
var destroyRef = React.useRef(false);
var _React$useState = React.useState(defaultValue),
_React$useState2 = _slicedToArray(_React$useState, 2),
value = _React$useState2[0],
setValue = _React$useState2[1];
React.useEffect(function () {
destroyRef.current = false;
return function () {
destroyRef.current = true;
};
}, []);
function safeSetState(updater, ignoreDestroy) {
if (ignoreDestroy && destroyRef.current) {
return;
}
setValue(updater);
}
return [value, safeSetState];
}
var STATUS_NONE = 'none';
var STATUS_APPEAR = 'appear';
var STATUS_ENTER = 'enter';
var STATUS_LEAVE = 'leave';
var STEP_NONE = 'none';
var STEP_PREPARE = 'prepare';
var STEP_START = 'start';
var STEP_ACTIVE = 'active';
var STEP_ACTIVATED = 'end';
/**
* Used for disabled motion case.
* Prepare stage will still work but start & active will be skipped.
*/
var STEP_PREPARED = 'prepared';
// ================= Transition =================
// Event wrapper. Copy from react source code
function makePrefixMap(styleProp, eventName) {
var prefixes = {};
prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
prefixes["Webkit".concat(styleProp)] = "webkit".concat(eventName);
prefixes["Moz".concat(styleProp)] = "moz".concat(eventName);
prefixes["ms".concat(styleProp)] = "MS".concat(eventName);
prefixes["O".concat(styleProp)] = "o".concat(eventName.toLowerCase());
return prefixes;
}
function getVendorPrefixes(domSupport, win) {
var prefixes = {
animationend: makePrefixMap('Animation', 'AnimationEnd'),
transitionend: makePrefixMap('Transition', 'TransitionEnd')
};
if (domSupport) {
if (!('AnimationEvent' in win)) {
delete prefixes.animationend.animation;
}
if (!('TransitionEvent' in win)) {
delete prefixes.transitionend.transition;
}
}
return prefixes;
}
var vendorPrefixes = getVendorPrefixes(canUseDom(), typeof window !== 'undefined' ? window : {});
var style = {};
if (canUseDom()) {
var _document$createEleme = document.createElement('div');
style = _document$createEleme.style;
}
var prefixedEventNames = {};
function getVendorPrefixedEventName(eventName) {
if (prefixedEventNames[eventName]) {
return prefixedEventNames[eventName];
}
var prefixMap = vendorPrefixes[eventName];
if (prefixMap) {
var stylePropList = Object.keys(prefixMap);
var len = stylePropList.length;
for (var i = 0; i < len; i += 1) {
var styleProp = stylePropList[i];
if (Object.prototype.hasOwnProperty.call(prefixMap, styleProp) && styleProp in style) {
prefixedEventNames[eventName] = prefixMap[styleProp];
return prefixedEventNames[eventName];
}
}
}
return '';
}
var internalAnimationEndName = getVendorPrefixedEventName('animationend');
var internalTransitionEndName = getVendorPrefixedEventName('transitionend');
var supportTransition = !!(internalAnimationEndName && internalTransitionEndName);
var animationEndName = internalAnimationEndName || 'animationend';
var transitionEndName = internalTransitionEndName || 'transitionend';
function getTransitionName$2(transitionName, transitionType) {
if (!transitionName) return null;
if (_typeof$1(transitionName) === 'object') {
var type = transitionType.replace(/-\w/g, function (match) {
return match[1].toUpperCase();
});
return transitionName[type];
}
return "".concat(transitionName, "-").concat(transitionType);
}
var useDomMotionEvents = (function (callback) {
var cacheElementRef = useRef();
// Cache callback
var callbackRef = useRef(callback);
callbackRef.current = callback;
// Internal motion event handler
var onInternalMotionEnd = React.useCallback(function (event) {
callbackRef.current(event);
}, []);
// Remove events
function removeMotionEvents(element) {
if (element) {
element.removeEventListener(transitionEndName, onInternalMotionEnd);
element.removeEventListener(animationEndName, onInternalMotionEnd);
}
}
// Patch events
function patchMotionEvents(element) {
if (cacheElementRef.current && cacheElementRef.current !== element) {
removeMotionEvents(cacheElementRef.current);
}
if (element && element !== cacheElementRef.current) {
element.addEventListener(transitionEndName, onInternalMotionEnd);
element.addEventListener(animationEndName, onInternalMotionEnd);
// Save as cache in case dom removed trigger by `motionDeadline`
cacheElementRef.current = element;
}
}
// Clean up when removed
React.useEffect(function () {
return function () {
removeMotionEvents(cacheElementRef.current);
};
}, []);
return [patchMotionEvents, removeMotionEvents];
});
// It's safe to use `useLayoutEffect` but the warning is annoying
var useIsomorphicLayoutEffect = canUseDom() ? useLayoutEffect$1 : useEffect;
var useNextFrame = (function () {
var nextFrameRef = React.useRef(null);
function cancelNextFrame() {
wrapperRaf$1.cancel(nextFrameRef.current);
}
function nextFrame(callback) {
var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
cancelNextFrame();
var nextFrameId = wrapperRaf$1(function () {
if (delay <= 1) {
callback({
isCanceled: function isCanceled() {
return nextFrameId !== nextFrameRef.current;
}
});
} else {
nextFrame(callback, delay - 1);
}
});
nextFrameRef.current = nextFrameId;
}
React.useEffect(function () {
return function () {
cancelNextFrame();
};
}, []);
return [nextFrame, cancelNextFrame];
});
var FULL_STEP_QUEUE = [STEP_PREPARE, STEP_START, STEP_ACTIVE, STEP_ACTIVATED];
var SIMPLE_STEP_QUEUE = [STEP_PREPARE, STEP_PREPARED];
/** Skip current step */
var SkipStep = false;
/** Current step should be update in */
var DoStep = true;
function isActive(step) {
return step === STEP_ACTIVE || step === STEP_ACTIVATED;
}
var useStepQueue = (function (status, prepareOnly, callback) {
var _useState = useSafeState(STEP_NONE),
_useState2 = _slicedToArray(_useState, 2),
step = _useState2[0],
setStep = _useState2[1];
var _useNextFrame = useNextFrame(),
_useNextFrame2 = _slicedToArray(_useNextFrame, 2),
nextFrame = _useNextFrame2[0],
cancelNextFrame = _useNextFrame2[1];
function startQueue() {
setStep(STEP_PREPARE, true);
}
var STEP_QUEUE = prepareOnly ? SIMPLE_STEP_QUEUE : FULL_STEP_QUEUE;
useIsomorphicLayoutEffect(function () {
if (step !== STEP_NONE && step !== STEP_ACTIVATED) {
var index = STEP_QUEUE.indexOf(step);
var nextStep = STEP_QUEUE[index + 1];
var result = callback(step);
if (result === SkipStep) {
// Skip when no needed
setStep(nextStep, true);
} else if (nextStep) {
// Do as frame for step update
nextFrame(function (info) {
function doNext() {
// Skip since current queue is ood
if (info.isCanceled()) return;
setStep(nextStep, true);
}
if (result === true) {
doNext();
} else {
// Only promise should be async
Promise.resolve(result).then(doNext);
}
});
}
}
}, [status, step]);
React.useEffect(function () {
return function () {
cancelNextFrame();
};
}, []);
return [startQueue, step];
});
function useStatus(supportMotion, visible, getElement, _ref) {
var _ref$motionEnter = _ref.motionEnter,
motionEnter = _ref$motionEnter === void 0 ? true : _ref$motionEnter,
_ref$motionAppear = _ref.motionAppear,
motionAppear = _ref$motionAppear === void 0 ? true : _ref$motionAppear,
_ref$motionLeave = _ref.motionLeave,
motionLeave = _ref$motionLeave === void 0 ? true : _ref$motionLeave,
motionDeadline = _ref.motionDeadline,
motionLeaveImmediately = _ref.motionLeaveImmediately,
onAppearPrepare = _ref.onAppearPrepare,
onEnterPrepare = _ref.onEnterPrepare,
onLeavePrepare = _ref.onLeavePrepare,
onAppearStart = _ref.onAppearStart,
onEnterStart = _ref.onEnterStart,
onLeaveStart = _ref.onLeaveStart,
onAppearActive = _ref.onAppearActive,
onEnterActive = _ref.onEnterActive,
onLeaveActive = _ref.onLeaveActive,
onAppearEnd = _ref.onAppearEnd,
onEnterEnd = _ref.onEnterEnd,
onLeaveEnd = _ref.onLeaveEnd,
onVisibleChanged = _ref.onVisibleChanged;
// Used for outer render usage to avoid `visible: false & status: none` to render nothing
var _useState = useSafeState(),
_useState2 = _slicedToArray(_useState, 2),
asyncVisible = _useState2[0],
setAsyncVisible = _useState2[1];
var _useState3 = useSafeState(STATUS_NONE),
_useState4 = _slicedToArray(_useState3, 2),
status = _useState4[0],
setStatus = _useState4[1];
var _useState5 = useSafeState(null),
_useState6 = _slicedToArray(_useState5, 2),
style = _useState6[0],
setStyle = _useState6[1];
var mountedRef = useRef(false);
var deadlineRef = useRef(null);
// =========================== Dom Node ===========================
function getDomElement() {
return getElement();
}
// ========================== Motion End ==========================
var activeRef = useRef(false);
/**
* Clean up status & style
*/
function updateMotionEndStatus() {
setStatus(STATUS_NONE, true);
setStyle(null, true);
}
function onInternalMotionEnd(event) {
var element = getDomElement();
if (event && !event.deadline && event.target !== element) {
// event exists
// not initiated by deadline
// transitionEnd not fired by inner elements
return;
}
var currentActive = activeRef.current;
var canEnd;
if (status === STATUS_APPEAR && currentActive) {
canEnd = onAppearEnd === null || onAppearEnd === void 0 ? void 0 : onAppearEnd(element, event);
} else if (status === STATUS_ENTER && currentActive) {
canEnd = onEnterEnd === null || onEnterEnd === void 0 ? void 0 : onEnterEnd(element, event);
} else if (status === STATUS_LEAVE && currentActive) {
canEnd = onLeaveEnd === null || onLeaveEnd === void 0 ? void 0 : onLeaveEnd(element, event);
}
// Only update status when `canEnd` and not destroyed
if (status !== STATUS_NONE && currentActive && canEnd !== false) {
updateMotionEndStatus();
}
}
var _useDomMotionEvents = useDomMotionEvents(onInternalMotionEnd),
_useDomMotionEvents2 = _slicedToArray(_useDomMotionEvents, 1),
patchMotionEvents = _useDomMotionEvents2[0];
// ============================= Step =============================
var getEventHandlers = function getEventHandlers(targetStatus) {
var _ref2, _ref3, _ref4;
switch (targetStatus) {
case STATUS_APPEAR:
return _ref2 = {}, _defineProperty$1(_ref2, STEP_PREPARE, onAppearPrepare), _defineProperty$1(_ref2, STEP_START, onAppearStart), _defineProperty$1(_ref2, STEP_ACTIVE, onAppearActive), _ref2;
case STATUS_ENTER:
return _ref3 = {}, _defineProperty$1(_ref3, STEP_PREPARE, onEnterPrepare), _defineProperty$1(_ref3, STEP_START, onEnterStart), _defineProperty$1(_ref3, STEP_ACTIVE, onEnterActive), _ref3;
case STATUS_LEAVE:
return _ref4 = {}, _defineProperty$1(_ref4, STEP_PREPARE, onLeavePrepare), _defineProperty$1(_ref4, STEP_START, onLeaveStart), _defineProperty$1(_ref4, STEP_ACTIVE, onLeaveActive), _ref4;
default:
return {};
}
};
var eventHandlers = React.useMemo(function () {
return getEventHandlers(status);
}, [status]);
var _useStepQueue = useStepQueue(status, !supportMotion, function (newStep) {
// Only prepare step can be skip
if (newStep === STEP_PREPARE) {
var onPrepare = eventHandlers[STEP_PREPARE];
if (!onPrepare) {
return SkipStep;
}
return onPrepare(getDomElement());
}
// Rest step is sync update
if (step in eventHandlers) {
var _eventHandlers$step;
setStyle(((_eventHandlers$step = eventHandlers[step]) === null || _eventHandlers$step === void 0 ? void 0 : _eventHandlers$step.call(eventHandlers, getDomElement(), null)) || null);
}
if (step === STEP_ACTIVE) {
// Patch events when motion needed
patchMotionEvents(getDomElement());
if (motionDeadline > 0) {
clearTimeout(deadlineRef.current);
deadlineRef.current = setTimeout(function () {
onInternalMotionEnd({
deadline: true
});
}, motionDeadline);
}
}
if (step === STEP_PREPARED) {
updateMotionEndStatus();
}
return DoStep;
}),
_useStepQueue2 = _slicedToArray(_useStepQueue, 2),
startStep = _useStepQueue2[0],
step = _useStepQueue2[1];
var active = isActive(step);
activeRef.current = active;
// ============================ Status ============================
// Update with new status
useIsomorphicLayoutEffect(function () {
setAsyncVisible(visible);
var isMounted = mountedRef.current;
mountedRef.current = true;
// if (!supportMotion) {
// return;
// }
var nextStatus;
// Appear
if (!isMounted && visible && motionAppear) {
nextStatus = STATUS_APPEAR;
}
// Enter
if (isMounted && visible && motionEnter) {
nextStatus = STATUS_ENTER;
}
// Leave
if (isMounted && !visible && motionLeave || !isMounted && motionLeaveImmediately && !visible && motionLeave) {
nextStatus = STATUS_LEAVE;
}
var nextEventHandlers = getEventHandlers(nextStatus);
// Update to next status
if (nextStatus && (supportMotion || nextEventHandlers[STEP_PREPARE])) {
setStatus(nextStatus);
startStep();
} else {
// Set back in case no motion but prev status has prepare step
setStatus(STATUS_NONE);
}
}, [visible]);
// ============================ Effect ============================
// Reset when motion changed
useEffect(function () {
if (
// Cancel appear
status === STATUS_APPEAR && !motionAppear ||
// Cancel enter
status === STATUS_ENTER && !motionEnter ||
// Cancel leave
status === STATUS_LEAVE && !motionLeave) {
setStatus(STATUS_NONE);
}
}, [motionAppear, motionEnter, motionLeave]);
useEffect(function () {
return function () {
mountedRef.current = false;
clearTimeout(deadlineRef.current);
};
}, []);
// Trigger `onVisibleChanged`
var firstMountChangeRef = React.useRef(false);
useEffect(function () {
// [visible & motion not end] => [!visible & motion end] still need trigger onVisibleChanged
if (asyncVisible) {
firstMountChangeRef.current = true;
}
if (asyncVisible !== undefined && status === STATUS_NONE) {
// Skip first render is invisible since it's nothing changed
if (firstMountChangeRef.current || asyncVisible) {
onVisibleChanged === null || onVisibleChanged === void 0 ? void 0 : onVisibleChanged(asyncVisible);
}
firstMountChangeRef.current = true;
}
}, [asyncVisible, status]);
// ============================ Styles ============================
var mergedStyle = style;
if (eventHandlers[STEP_PREPARE] && step === STEP_START) {
mergedStyle = _objectSpread2$1({
transition: 'none'
}, mergedStyle);
}
return [status, step, mergedStyle, asyncVisible !== null && asyncVisible !== void 0 ? asyncVisible : visible];
}
/**
* `transitionSupport` is used for none transition test case.
* Default we use browser transition event support check.
*/
function genCSSMotion(config) {
var transitionSupport = config;
if (_typeof$1(config) === 'object') {
transitionSupport = config.transitionSupport;
}
function isSupportTransition(props, contextMotion) {
return !!(props.motionName && transitionSupport && contextMotion !== false);
}
var CSSMotion = /*#__PURE__*/React.forwardRef(function (props, ref) {
var _props$visible = props.visible,
visible = _props$visible === void 0 ? true : _props$visible,
_props$removeOnLeave = props.removeOnLeave,
removeOnLeave = _props$removeOnLeave === void 0 ? true : _props$removeOnLeave,
forceRender = props.forceRender,
children = props.children,
motionName = props.motionName,
leavedClassName = props.leavedClassName,
eventProps = props.eventProps;
var _React$useContext = React.useContext(Context),
contextMotion = _React$useContext.motion;
var supportMotion = isSupportTransition(props, contextMotion);
// Ref to the react node, it may be a HTMLElement
var nodeRef = useRef();
// Ref to the dom wrapper in case ref can not pass to HTMLElement
var wrapperNodeRef = useRef();
function getDomElement() {
try {
// Here we're avoiding call for findDOMNode since it's deprecated
// in strict mode. We're calling it only when node ref is not
// an instance of DOM HTMLElement. Otherwise use
// findDOMNode as a final resort
return nodeRef.current instanceof HTMLElement ? nodeRef.current : findDOMNode(wrapperNodeRef.current);
} catch (e) {
// Only happen when `motionDeadline` trigger but element removed.
return null;
}
}
var _useStatus = useStatus(supportMotion, visible, getDomElement, props),
_useStatus2 = _slicedToArray(_useStatus, 4),
status = _useStatus2[0],
statusStep = _useStatus2[1],
statusStyle = _useStatus2[2],
mergedVisible = _useStatus2[3];
// Record whether content has rendered
// Will return null for un-rendered even when `removeOnLeave={false}`
var renderedRef = React.useRef(mergedVisible);
if (mergedVisible) {
renderedRef.current = true;
}
// ====================== Refs ======================
var setNodeRef = React.useCallback(function (node) {
nodeRef.current = node;
fillRef(ref, node);
}, [ref]);
// ===================== Render =====================
var motionChildren;
var mergedProps = _objectSpread2$1(_objectSpread2$1({}, eventProps), {}, {
visible: visible
});
if (!children) {
// No children
motionChildren = null;
} else if (status === STATUS_NONE) {
// Stable children
if (mergedVisible) {
motionChildren = children(_objectSpread2$1({}, mergedProps), setNodeRef);
} else if (!removeOnLeave && renderedRef.current && leavedClassName) {
motionChildren = children(_objectSpread2$1(_objectSpread2$1({}, mergedProps), {}, {
className: leavedClassName
}), setNodeRef);
} else if (forceRender || !removeOnLeave && !leavedClassName) {
motionChildren = children(_objectSpread2$1(_objectSpread2$1({}, mergedProps), {}, {
style: {
display: 'none'
}
}), setNodeRef);
} else {
motionChildren = null;
}
} else {
var _classNames;
// In motion
var statusSuffix;
if (statusStep === STEP_PREPARE) {
statusSuffix = 'prepare';
} else if (isActive(statusStep)) {
statusSuffix = 'active';
} else if (statusStep === STEP_START) {
statusSuffix = 'start';
}
var motionCls = getTransitionName$2(motionName, "".concat(status, "-").concat(statusSuffix));
motionChildren = children(_objectSpread2$1(_objectSpread2$1({}, mergedProps), {}, {
className: classNames(getTransitionName$2(motionName, status), (_classNames = {}, _defineProperty$1(_classNames, motionCls, motionCls && statusSuffix), _defineProperty$1(_classNames, motionName, typeof motionName === 'string'), _classNames)),
style: statusStyle
}), setNodeRef);
}
// Auto inject ref if child node not have `ref` props
if ( /*#__PURE__*/React.isValidElement(motionChildren) && supportRef(motionChildren)) {
var _ref = motionChildren,
originNodeRef = _ref.ref;
if (!originNodeRef) {
motionChildren = /*#__PURE__*/React.cloneElement(motionChildren, {
ref: setNodeRef
});
}
}
return /*#__PURE__*/React.createElement(DomWrapper, {
ref: wrapperNodeRef
}, motionChildren);
});
CSSMotion.displayName = 'CSSMotion';
return CSSMotion;
}
var CSSMotion = genCSSMotion(supportTransition);
var STATUS_ADD = 'add';
var STATUS_KEEP = 'keep';
var STATUS_REMOVE = 'remove';
var STATUS_REMOVED = 'removed';
function wrapKeyToObject(key) {
var keyObj;
if (key && _typeof$1(key) === 'object' && 'key' in key) {
keyObj = key;
} else {
keyObj = {
key: key
};
}
return _objectSpread2$1(_objectSpread2$1({}, keyObj), {}, {
key: String(keyObj.key)
});
}
function parseKeys() {
var keys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
return keys.map(wrapKeyToObject);
}
function diffKeys() {
var prevKeys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var currentKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var list = [];
var currentIndex = 0;
var currentLen = currentKeys.length;
var prevKeyObjects = parseKeys(prevKeys);
var currentKeyObjects = parseKeys(currentKeys);
// Check prev keys to insert or keep
prevKeyObjects.forEach(function (keyObj) {
var hit = false;
for (var i = currentIndex; i < currentLen; i += 1) {
var currentKeyObj = currentKeyObjects[i];
if (currentKeyObj.key === keyObj.key) {
// New added keys should add before current key
if (currentIndex < i) {
list = list.concat(currentKeyObjects.slice(currentIndex, i).map(function (obj) {
return _objectSpread2$1(_objectSpread2$1({}, obj), {}, {
status: STATUS_ADD
});
}));
currentIndex = i;
}
list.push(_objectSpread2$1(_objectSpread2$1({}, currentKeyObj), {}, {
status: STATUS_KEEP
}));
currentIndex += 1;
hit = true;
break;
}
}
// If not hit, it means key is removed
if (!hit) {
list.push(_objectSpread2$1(_objectSpread2$1({}, keyObj), {}, {
status: STATUS_REMOVE
}));
}
});
// Add rest to the list
if (currentIndex < currentLen) {
list = list.concat(currentKeyObjects.slice(currentIndex).map(function (obj) {
return _objectSpread2$1(_objectSpread2$1({}, obj), {}, {
status: STATUS_ADD
});
}));
}
/**
* Merge same key when it remove and add again:
* [1 - add, 2 - keep, 1 - remove] -> [1 - keep, 2 - keep]
*/
var keys = {};
list.forEach(function (_ref) {
var key = _ref.key;
keys[key] = (keys[key] || 0) + 1;
});
var duplicatedKeys = Object.keys(keys).filter(function (key) {
return keys[key] > 1;
});
duplicatedKeys.forEach(function (matchKey) {
// Remove `STATUS_REMOVE` node.
list = list.filter(function (_ref2) {
var key = _ref2.key,
status = _ref2.status;
return key !== matchKey || status !== STATUS_REMOVE;
});
// Update `STATUS_ADD` to `STATUS_KEEP`
list.forEach(function (node) {
if (node.key === matchKey) {
// eslint-disable-next-line no-param-reassign
node.status = STATUS_KEEP;
}
});
});
return list;
}
var _excluded$d = ["component", "children", "onVisibleChanged", "onAllRemoved"],
_excluded2$4 = ["status"];
var MOTION_PROP_NAMES = ['eventProps', 'visible', 'children', 'motionName', 'motionAppear', 'motionEnter', 'motionLeave', 'motionLeaveImmediately', 'motionDeadline', 'removeOnLeave', 'leavedClassName', 'onAppearPrepare', 'onAppearStart', 'onAppearActive', 'onAppearEnd', 'onEnterStart', 'onEnterActive', 'onEnterEnd', 'onLeaveStart', 'onLeaveActive', 'onLeaveEnd'];
/**
* Generate a CSSMotionList component with config
* @param transitionSupport No need since CSSMotionList no longer depends on transition support
* @param CSSMotion CSSMotion component
*/
function genCSSMotionList(transitionSupport) {
var CSSMotion$1 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CSSMotion;
var CSSMotionList = /*#__PURE__*/function (_React$Component) {
_inherits(CSSMotionList, _React$Component);
var _super = _createSuper(CSSMotionList);
function CSSMotionList() {
var _this;
_classCallCheck(this, CSSMotionList);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_defineProperty$1(_assertThisInitialized(_this), "state", {
keyEntities: []
});
// ZombieJ: Return the count of rest keys. It's safe to refactor if need more info.
_defineProperty$1(_assertThisInitialized(_this), "removeKey", function (removeKey) {
var keyEntities = _this.state.keyEntities;
var nextKeyEntities = keyEntities.map(function (entity) {
if (entity.key !== removeKey) return entity;
return _objectSpread2$1(_objectSpread2$1({}, entity), {}, {
status: STATUS_REMOVED
});
});
_this.setState({
keyEntities: nextKeyEntities
});
return nextKeyEntities.filter(function (_ref) {
var status = _ref.status;
return status !== STATUS_REMOVED;
}).length;
});
return _this;
}
_createClass(CSSMotionList, [{
key: "render",
value: function render() {
var _this2 = this;
var keyEntities = this.state.keyEntities;
var _this$props = this.props,
component = _this$props.component,
children = _this$props.children,
_onVisibleChanged = _this$props.onVisibleChanged,
onAllRemoved = _this$props.onAllRemoved,
restProps = _objectWithoutProperties(_this$props, _excluded$d);
var Component = component || React.Fragment;
var motionProps = {};
MOTION_PROP_NAMES.forEach(function (prop) {
motionProps[prop] = restProps[prop];
delete restProps[prop];
});
delete restProps.keys;
return /*#__PURE__*/React.createElement(Component, restProps, keyEntities.map(function (_ref2, index) {
var status = _ref2.status,
eventProps = _objectWithoutProperties(_ref2, _excluded2$4);
var visible = status === STATUS_ADD || status === STATUS_KEEP;
return /*#__PURE__*/React.createElement(CSSMotion$1, _extends$1({}, motionProps, {
key: eventProps.key,
visible: visible,
eventProps: eventProps,
onVisibleChanged: function onVisibleChanged(changedVisible) {
_onVisibleChanged === null || _onVisibleChanged === void 0 ? void 0 : _onVisibleChanged(changedVisible, {
key: eventProps.key
});
if (!changedVisible) {
var restKeysCount = _this2.removeKey(eventProps.key);
if (restKeysCount === 0 && onAllRemoved) {
onAllRemoved();
}
}
}
}), function (props, ref) {
return children(_objectSpread2$1(_objectSpread2$1({}, props), {}, {
index: index
}), ref);
});
}));
}
}], [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(_ref3, _ref4) {
var keys = _ref3.keys;
var keyEntities = _ref4.keyEntities;
var parsedKeyObjects = parseKeys(keys);
var mixedKeyEntities = diffKeys(keyEntities, parsedKeyObjects);
return {
keyEntities: mixedKeyEntities.filter(function (entity) {
var prevEntity = keyEntities.find(function (_ref5) {
var key = _ref5.key;
return entity.key === key;
});
// Remove if already mark as removed
if (prevEntity && prevEntity.status === STATUS_REMOVED && entity.status === STATUS_REMOVE) {
return false;
}
return true;
})
};
}
}]);
return CSSMotionList;
}(React.Component);
_defineProperty$1(CSSMotionList, "defaultProps", {
component: 'div'
});
return CSSMotionList;
}
genCSSMotionList(supportTransition);
var isValidElement = React.isValidElement;
function isFragment(child) {
return child && isValidElement(child) && child.type === React.Fragment;
}
function replaceElement(element, replacement, props) {
if (!isValidElement(element)) {
return replacement;
}
return /*#__PURE__*/React.cloneElement(element, typeof props === 'function' ? props(element.props || {}) : props);
}
function cloneElement(element, props) {
return replaceElement(element, element, props);
}
function useEvent(callback) {
var fnRef = React.useRef();
fnRef.current = callback;
var memoFn = React.useCallback(function () {
var _fnRef$current;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return (_fnRef$current = fnRef.current) === null || _fnRef$current === void 0 ? void 0 : _fnRef$current.call.apply(_fnRef$current, [fnRef].concat(args));
}, []);
return memoFn;
}
/** We only think `undefined` is empty */
function hasValue(value) {
return value !== undefined;
}
/**
* Similar to `useState` but will use props value if provided.
* Note that internal use rc-util `useState` hook.
*/
function useMergedState(defaultStateValue, option) {
var _ref = option || {},
defaultValue = _ref.defaultValue,
value = _ref.value,
onChange = _ref.onChange,
postState = _ref.postState;
// ======================= Init =======================
var _useState = useSafeState(function () {
if (hasValue(value)) {
return value;
} else if (hasValue(defaultValue)) {
return typeof defaultValue === 'function' ? defaultValue() : defaultValue;
} else {
return typeof defaultStateValue === 'function' ? defaultStateValue() : defaultStateValue;
}
}),
_useState2 = _slicedToArray(_useState, 2),
innerValue = _useState2[0],
setInnerValue = _useState2[1];
var mergedValue = value !== undefined ? value : innerValue;
var postMergedValue = postState ? postState(mergedValue) : mergedValue;
// ====================== Change ======================
var onChangeFn = useEvent(onChange);
var _useState3 = useSafeState([mergedValue]),
_useState4 = _slicedToArray(_useState3, 2),
prevValue = _useState4[0],
setPrevValue = _useState4[1];
useLayoutUpdateEffect(function () {
var prev = prevValue[0];
if (innerValue !== prev) {
onChangeFn(innerValue, prev);
}
}, [prevValue]);
// Sync value back to `undefined` when it from control to un-control
useLayoutUpdateEffect(function () {
if (!hasValue(value)) {
setInnerValue(value);
}
}, [value]);
// ====================== Update ======================
var triggerChange = useEvent(function (updater, ignoreDestroy) {
setInnerValue(updater, ignoreDestroy);
setPrevValue([mergedValue], ignoreDestroy);
});
return [postMergedValue, triggerChange];
}
var isMobile = (function () {
if (typeof navigator === 'undefined' || typeof window === 'undefined') {
return false;
}
var agent = navigator.userAgent || navigator.vendor || window.opera;
return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(agent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(agent === null || agent === void 0 ? void 0 : agent.substr(0, 4));
});
/**
* @ignore
* some key-codes definition and utils from closure-library
* @author yiminghe@gmail.com
*/
var KeyCode = {
/**
* MAC_ENTER
*/
MAC_ENTER: 3,
/**
* BACKSPACE
*/
BACKSPACE: 8,
/**
* TAB
*/
TAB: 9,
/**
* NUMLOCK on FF/Safari Mac
*/
NUM_CENTER: 12,
// NUMLOCK on FF/Safari Mac
/**
* ENTER
*/
ENTER: 13,
/**
* SHIFT
*/
SHIFT: 16,
/**
* CTRL
*/
CTRL: 17,
/**
* ALT
*/
ALT: 18,
/**
* PAUSE
*/
PAUSE: 19,
/**
* CAPS_LOCK
*/
CAPS_LOCK: 20,
/**
* ESC
*/
ESC: 27,
/**
* SPACE
*/
SPACE: 32,
/**
* PAGE_UP
*/
PAGE_UP: 33,
// also NUM_NORTH_EAST
/**
* PAGE_DOWN
*/
PAGE_DOWN: 34,
// also NUM_SOUTH_EAST
/**
* END
*/
END: 35,
// also NUM_SOUTH_WEST
/**
* HOME
*/
HOME: 36,
// also NUM_NORTH_WEST
/**
* LEFT
*/
LEFT: 37,
// also NUM_WEST
/**
* UP
*/
UP: 38,
// also NUM_NORTH
/**
* RIGHT
*/
RIGHT: 39,
// also NUM_EAST
/**
* DOWN
*/
DOWN: 40,
// also NUM_SOUTH
/**
* PRINT_SCREEN
*/
PRINT_SCREEN: 44,
/**
* INSERT
*/
INSERT: 45,
// also NUM_INSERT
/**
* DELETE
*/
DELETE: 46,
// also NUM_DELETE
/**
* ZERO
*/
ZERO: 48,
/**
* ONE
*/
ONE: 49,
/**
* TWO
*/
TWO: 50,
/**
* THREE
*/
THREE: 51,
/**
* FOUR
*/
FOUR: 52,
/**
* FIVE
*/
FIVE: 53,
/**
* SIX
*/
SIX: 54,
/**
* SEVEN
*/
SEVEN: 55,
/**
* EIGHT
*/
EIGHT: 56,
/**
* NINE
*/
NINE: 57,
/**
* QUESTION_MARK
*/
QUESTION_MARK: 63,
// needs localization
/**
* A
*/
A: 65,
/**
* B
*/
B: 66,
/**
* C
*/
C: 67,
/**
* D
*/
D: 68,
/**
* E
*/
E: 69,
/**
* F
*/
F: 70,
/**
* G
*/
G: 71,
/**
* H
*/
H: 72,
/**
* I
*/
I: 73,
/**
* J
*/
J: 74,
/**
* K
*/
K: 75,
/**
* L
*/
L: 76,
/**
* M
*/
M: 77,
/**
* N
*/
N: 78,
/**
* O
*/
O: 79,
/**
* P
*/
P: 80,
/**
* Q
*/
Q: 81,
/**
* R
*/
R: 82,
/**
* S
*/
S: 83,
/**
* T
*/
T: 84,
/**
* U
*/
U: 85,
/**
* V
*/
V: 86,
/**
* W
*/
W: 87,
/**
* X
*/
X: 88,
/**
* Y
*/
Y: 89,
/**
* Z
*/
Z: 90,
/**
* META
*/
META: 91,
// WIN_KEY_LEFT
/**
* WIN_KEY_RIGHT
*/
WIN_KEY_RIGHT: 92,
/**
* CONTEXT_MENU
*/
CONTEXT_MENU: 93,
/**
* NUM_ZERO
*/
NUM_ZERO: 96,
/**
* NUM_ONE
*/
NUM_ONE: 97,
/**
* NUM_TWO
*/
NUM_TWO: 98,
/**
* NUM_THREE
*/
NUM_THREE: 99,
/**
* NUM_FOUR
*/
NUM_FOUR: 100,
/**
* NUM_FIVE
*/
NUM_FIVE: 101,
/**
* NUM_SIX
*/
NUM_SIX: 102,
/**
* NUM_SEVEN
*/
NUM_SEVEN: 103,
/**
* NUM_EIGHT
*/
NUM_EIGHT: 104,
/**
* NUM_NINE
*/
NUM_NINE: 105,
/**
* NUM_MULTIPLY
*/
NUM_MULTIPLY: 106,
/**
* NUM_PLUS
*/
NUM_PLUS: 107,
/**
* NUM_MINUS
*/
NUM_MINUS: 109,
/**
* NUM_PERIOD
*/
NUM_PERIOD: 110,
/**
* NUM_DIVISION
*/
NUM_DIVISION: 111,
/**
* F1
*/
F1: 112,
/**
* F2
*/
F2: 113,
/**
* F3
*/
F3: 114,
/**
* F4
*/
F4: 115,
/**
* F5
*/
F5: 116,
/**
* F6
*/
F6: 117,
/**
* F7
*/
F7: 118,
/**
* F8
*/
F8: 119,
/**
* F9
*/
F9: 120,
/**
* F10
*/
F10: 121,
/**
* F11
*/
F11: 122,
/**
* F12
*/
F12: 123,
/**
* NUMLOCK
*/
NUMLOCK: 144,
/**
* SEMICOLON
*/
SEMICOLON: 186,
// needs localization
/**
* DASH
*/
DASH: 189,
// needs localization
/**
* EQUALS
*/
EQUALS: 187,
// needs localization
/**
* COMMA
*/
COMMA: 188,
// needs localization
/**
* PERIOD
*/
PERIOD: 190,
// needs localization
/**
* SLASH
*/
SLASH: 191,
// needs localization
/**
* APOSTROPHE
*/
APOSTROPHE: 192,
// needs localization
/**
* SINGLE_QUOTE
*/
SINGLE_QUOTE: 222,
// needs localization
/**
* OPEN_SQUARE_BRACKET
*/
OPEN_SQUARE_BRACKET: 219,
// needs localization
/**
* BACKSLASH
*/
BACKSLASH: 220,
// needs localization
/**
* CLOSE_SQUARE_BRACKET
*/
CLOSE_SQUARE_BRACKET: 221,
// needs localization
/**
* WIN_KEY
*/
WIN_KEY: 224,
/**
* MAC_FF_META
*/
MAC_FF_META: 224,
// Firefox (Gecko) fires this for the meta key instead of 91
/**
* WIN_IME
*/
WIN_IME: 229,
// ======================== Function ========================
/**
* whether text and modified key is entered at the same time.
*/
isTextModifyingKeyEvent: function isTextModifyingKeyEvent(e) {
var keyCode = e.keyCode;
if (e.altKey && !e.ctrlKey || e.metaKey ||
// Function keys don't generate text
keyCode >= KeyCode.F1 && keyCode <= KeyCode.F12) {
return false;
}
// The following keys are quite harmless, even in combination with
// CTRL, ALT or SHIFT.
switch (keyCode) {
case KeyCode.ALT:
case KeyCode.CAPS_LOCK:
case KeyCode.CONTEXT_MENU:
case KeyCode.CTRL:
case KeyCode.DOWN:
case KeyCode.END:
case KeyCode.ESC:
case KeyCode.HOME:
case KeyCode.INSERT:
case KeyCode.LEFT:
case KeyCode.MAC_FF_META:
case KeyCode.META:
case KeyCode.NUMLOCK:
case KeyCode.NUM_CENTER:
case KeyCode.PAGE_DOWN:
case KeyCode.PAGE_UP:
case KeyCode.PAUSE:
case KeyCode.PRINT_SCREEN:
case KeyCode.RIGHT:
case KeyCode.SHIFT:
case KeyCode.UP:
case KeyCode.WIN_KEY:
case KeyCode.WIN_KEY_RIGHT:
return false;
default:
return true;
}
},
/**
* whether character is entered.
*/
isCharacterKey: function isCharacterKey(keyCode) {
if (keyCode >= KeyCode.ZERO && keyCode <= KeyCode.NINE) {
return true;
}
if (keyCode >= KeyCode.NUM_ZERO && keyCode <= KeyCode.NUM_MULTIPLY) {
return true;
}
if (keyCode >= KeyCode.A && keyCode <= KeyCode.Z) {
return true;
}
// Safari sends zero key code for non-latin characters.
if (window.navigator.userAgent.indexOf('WebKit') !== -1 && keyCode === 0) {
return true;
}
switch (keyCode) {
case KeyCode.SPACE:
case KeyCode.QUESTION_MARK:
case KeyCode.NUM_PLUS:
case KeyCode.NUM_MINUS:
case KeyCode.NUM_PERIOD:
case KeyCode.NUM_DIVISION:
case KeyCode.SEMICOLON:
case KeyCode.DASH:
case KeyCode.EQUALS:
case KeyCode.COMMA:
case KeyCode.PERIOD:
case KeyCode.SLASH:
case KeyCode.APOSTROPHE:
case KeyCode.SINGLE_QUOTE:
case KeyCode.OPEN_SQUARE_BRACKET:
case KeyCode.BACKSLASH:
case KeyCode.CLOSE_SQUARE_BRACKET:
return true;
default:
return false;
}
}
};
var _excluded$c = ["prefixCls", "invalidate", "item", "renderItem", "responsive", "responsiveDisabled", "registerSize", "itemKey", "className", "style", "children", "display", "order", "component"];
// Use shared variable to save bundle size
var UNDEFINED = undefined;
function InternalItem(props, ref) {
var prefixCls = props.prefixCls,
invalidate = props.invalidate,
item = props.item,
renderItem = props.renderItem,
responsive = props.responsive,
responsiveDisabled = props.responsiveDisabled,
registerSize = props.registerSize,
itemKey = props.itemKey,
className = props.className,
style = props.style,
children = props.children,
display = props.display,
order = props.order,
_props$component = props.component,
Component = _props$component === void 0 ? 'div' : _props$component,
restProps = _objectWithoutProperties(props, _excluded$c);
var mergedHidden = responsive && !display;
// ================================ Effect ================================
function internalRegisterSize(width) {
registerSize(itemKey, width);
}
React.useEffect(function () {
return function () {
internalRegisterSize(null);
};
}, []);
// ================================ Render ================================
var childNode = renderItem && item !== UNDEFINED ? renderItem(item) : children;
var overflowStyle;
if (!invalidate) {
overflowStyle = {
opacity: mergedHidden ? 0 : 1,
height: mergedHidden ? 0 : UNDEFINED,
overflowY: mergedHidden ? 'hidden' : UNDEFINED,
order: responsive ? order : UNDEFINED,
pointerEvents: mergedHidden ? 'none' : UNDEFINED,
position: mergedHidden ? 'absolute' : UNDEFINED
};
}
var overflowProps = {};
if (mergedHidden) {
overflowProps['aria-hidden'] = true;
}
var itemNode = /*#__PURE__*/React.createElement(Component, _extends$1({
className: classNames(!invalidate && prefixCls, className),
style: _objectSpread2$1(_objectSpread2$1({}, overflowStyle), style)
}, overflowProps, restProps, {
ref: ref
}), childNode);
if (responsive) {
itemNode = /*#__PURE__*/React.createElement(RefResizeObserver, {
onResize: function onResize(_ref) {
var offsetWidth = _ref.offsetWidth;
internalRegisterSize(offsetWidth);
},
disabled: responsiveDisabled
}, itemNode);
}
return itemNode;
}
var Item$1 = /*#__PURE__*/React.forwardRef(InternalItem);
Item$1.displayName = 'Item';
function channelUpdate(callback) {
if (typeof MessageChannel === 'undefined') {
wrapperRaf$1(callback);
} else {
var channel = new MessageChannel();
channel.port1.onmessage = function () {
return callback();
};
channel.port2.postMessage(undefined);
}
}
/**
* Batcher for record any `useEffectState` need update.
*/
function useBatcher() {
// Updater Trigger
var updateFuncRef = React.useRef(null);
// Notify update
var notifyEffectUpdate = function notifyEffectUpdate(callback) {
if (!updateFuncRef.current) {
updateFuncRef.current = [];
channelUpdate(function () {
unstable_batchedUpdates(function () {
updateFuncRef.current.forEach(function (fn) {
fn();
});
updateFuncRef.current = null;
});
});
}
updateFuncRef.current.push(callback);
};
return notifyEffectUpdate;
}
/**
* Trigger state update by `useLayoutEffect` to save perf.
*/
function useEffectState(notifyEffectUpdate, defaultValue) {
// Value
var _React$useState = React.useState(defaultValue),
_React$useState2 = _slicedToArray(_React$useState, 2),
stateValue = _React$useState2[0],
setStateValue = _React$useState2[1];
// Set State
var setEffectVal = useEvent(function (nextValue) {
notifyEffectUpdate(function () {
setStateValue(nextValue);
});
});
return [stateValue, setEffectVal];
}
var OverflowContext = /*#__PURE__*/React__default.createContext(null);
var _excluded$b = ["component"],
_excluded2$3 = ["className"],
_excluded3$1 = ["className"];
var InternalRawItem = function InternalRawItem(props, ref) {
var context = React.useContext(OverflowContext);
// Render directly when context not provided
if (!context) {
var _props$component = props.component,
Component = _props$component === void 0 ? 'div' : _props$component,
_restProps = _objectWithoutProperties(props, _excluded$b);
return /*#__PURE__*/React.createElement(Component, _extends$1({}, _restProps, {
ref: ref
}));
}
var contextClassName = context.className,
restContext = _objectWithoutProperties(context, _excluded2$3);
var className = props.className,
restProps = _objectWithoutProperties(props, _excluded3$1);
// Do not pass context to sub item to avoid multiple measure
return /*#__PURE__*/React.createElement(OverflowContext.Provider, {
value: null
}, /*#__PURE__*/React.createElement(Item$1, _extends$1({
ref: ref,
className: classNames(contextClassName, className)
}, restContext, restProps)));
};
var RawItem = /*#__PURE__*/React.forwardRef(InternalRawItem);
RawItem.displayName = 'RawItem';
var _excluded$a = ["prefixCls", "data", "renderItem", "renderRawItem", "itemKey", "itemWidth", "ssr", "style", "className", "maxCount", "renderRest", "renderRawRest", "suffix", "component", "itemComponent", "onVisibleChange"];
var RESPONSIVE = 'responsive';
var INVALIDATE = 'invalidate';
function defaultRenderRest(omittedItems) {
return "+ ".concat(omittedItems.length, " ...");
}
function Overflow(props, ref) {
var _props$prefixCls = props.prefixCls,
prefixCls = _props$prefixCls === void 0 ? 'rc-overflow' : _props$prefixCls,
_props$data = props.data,
data = _props$data === void 0 ? [] : _props$data,
renderItem = props.renderItem,
renderRawItem = props.renderRawItem,
itemKey = props.itemKey,
_props$itemWidth = props.itemWidth,
itemWidth = _props$itemWidth === void 0 ? 10 : _props$itemWidth,
ssr = props.ssr,
style = props.style,
className = props.className,
maxCount = props.maxCount,
renderRest = props.renderRest,
renderRawRest = props.renderRawRest,
suffix = props.suffix,
_props$component = props.component,
Component = _props$component === void 0 ? 'div' : _props$component,
itemComponent = props.itemComponent,
onVisibleChange = props.onVisibleChange,
restProps = _objectWithoutProperties(props, _excluded$a);
var fullySSR = ssr === 'full';
var notifyEffectUpdate = useBatcher();
var _useEffectState = useEffectState(notifyEffectUpdate, null),
_useEffectState2 = _slicedToArray(_useEffectState, 2),
containerWidth = _useEffectState2[0],
setContainerWidth = _useEffectState2[1];
var mergedContainerWidth = containerWidth || 0;
var _useEffectState3 = useEffectState(notifyEffectUpdate, new Map()),
_useEffectState4 = _slicedToArray(_useEffectState3, 2),
itemWidths = _useEffectState4[0],
setItemWidths = _useEffectState4[1];
var _useEffectState5 = useEffectState(notifyEffectUpdate, 0),
_useEffectState6 = _slicedToArray(_useEffectState5, 2),
prevRestWidth = _useEffectState6[0],
setPrevRestWidth = _useEffectState6[1];
var _useEffectState7 = useEffectState(notifyEffectUpdate, 0),
_useEffectState8 = _slicedToArray(_useEffectState7, 2),
restWidth = _useEffectState8[0],
setRestWidth = _useEffectState8[1];
var _useEffectState9 = useEffectState(notifyEffectUpdate, 0),
_useEffectState10 = _slicedToArray(_useEffectState9, 2),
suffixWidth = _useEffectState10[0],
setSuffixWidth = _useEffectState10[1];
var _useState = useState(null),
_useState2 = _slicedToArray(_useState, 2),
suffixFixedStart = _useState2[0],
setSuffixFixedStart = _useState2[1];
var _useState3 = useState(null),
_useState4 = _slicedToArray(_useState3, 2),
displayCount = _useState4[0],
setDisplayCount = _useState4[1];
var mergedDisplayCount = React.useMemo(function () {
if (displayCount === null && fullySSR) {
return Number.MAX_SAFE_INTEGER;
}
return displayCount || 0;
}, [displayCount, containerWidth]);
var _useState5 = useState(false),
_useState6 = _slicedToArray(_useState5, 2),
restReady = _useState6[0],
setRestReady = _useState6[1];
var itemPrefixCls = "".concat(prefixCls, "-item");
// Always use the max width to avoid blink
var mergedRestWidth = Math.max(prevRestWidth, restWidth);
// ================================= Data =================================
var isResponsive = maxCount === RESPONSIVE;
var shouldResponsive = data.length && isResponsive;
var invalidate = maxCount === INVALIDATE;
/**
* When is `responsive`, we will always render rest node to get the real width of it for calculation
*/
var showRest = shouldResponsive || typeof maxCount === 'number' && data.length > maxCount;
var mergedData = useMemo$1(function () {
var items = data;
if (shouldResponsive) {
if (containerWidth === null && fullySSR) {
items = data;
} else {
items = data.slice(0, Math.min(data.length, mergedContainerWidth / itemWidth));
}
} else if (typeof maxCount === 'number') {
items = data.slice(0, maxCount);
}
return items;
}, [data, itemWidth, containerWidth, maxCount, shouldResponsive]);
var omittedItems = useMemo$1(function () {
if (shouldResponsive) {
return data.slice(mergedDisplayCount + 1);
}
return data.slice(mergedData.length);
}, [data, mergedData, shouldResponsive, mergedDisplayCount]);
// ================================= Item =================================
var getKey = useCallback(function (item, index) {
var _ref;
if (typeof itemKey === 'function') {
return itemKey(item);
}
return (_ref = itemKey && (item === null || item === void 0 ? void 0 : item[itemKey])) !== null && _ref !== void 0 ? _ref : index;
}, [itemKey]);
var mergedRenderItem = useCallback(renderItem || function (item) {
return item;
}, [renderItem]);
function updateDisplayCount(count, suffixFixedStartVal, notReady) {
// React 18 will sync render even when the value is same in some case.
// We take `mergedData` as deps which may cause dead loop if it's dynamic generate.
// ref: https://github.com/ant-design/ant-design/issues/36559
if (displayCount === count && (suffixFixedStartVal === undefined || suffixFixedStartVal === suffixFixedStart)) {
return;
}
setDisplayCount(count);
if (!notReady) {
setRestReady(count < data.length - 1);
onVisibleChange === null || onVisibleChange === void 0 ? void 0 : onVisibleChange(count);
}
if (suffixFixedStartVal !== undefined) {
setSuffixFixedStart(suffixFixedStartVal);
}
}
// ================================= Size =================================
function onOverflowResize(_, element) {
setContainerWidth(element.clientWidth);
}
function registerSize(key, width) {
setItemWidths(function (origin) {
var clone = new Map(origin);
if (width === null) {
clone.delete(key);
} else {
clone.set(key, width);
}
return clone;
});
}
function registerOverflowSize(_, width) {
setRestWidth(width);
setPrevRestWidth(restWidth);
}
function registerSuffixSize(_, width) {
setSuffixWidth(width);
}
// ================================ Effect ================================
function getItemWidth(index) {
return itemWidths.get(getKey(mergedData[index], index));
}
useLayoutEffect(function () {
if (mergedContainerWidth && typeof mergedRestWidth === 'number' && mergedData) {
var totalWidth = suffixWidth;
var len = mergedData.length;
var lastIndex = len - 1;
// When data count change to 0, reset this since not loop will reach
if (!len) {
updateDisplayCount(0, null);
return;
}
for (var i = 0; i < len; i += 1) {
var currentItemWidth = getItemWidth(i);
// Fully will always render
if (fullySSR) {
currentItemWidth = currentItemWidth || 0;
}
// Break since data not ready
if (currentItemWidth === undefined) {
updateDisplayCount(i - 1, undefined, true);
break;
}
// Find best match
totalWidth += currentItemWidth;
if (
// Only one means `totalWidth` is the final width
lastIndex === 0 && totalWidth <= mergedContainerWidth ||
// Last two width will be the final width
i === lastIndex - 1 && totalWidth + getItemWidth(lastIndex) <= mergedContainerWidth) {
// Additional check if match the end
updateDisplayCount(lastIndex, null);
break;
} else if (totalWidth + mergedRestWidth > mergedContainerWidth) {
// Can not hold all the content to show rest
updateDisplayCount(i - 1, totalWidth - currentItemWidth - suffixWidth + restWidth);
break;
}
}
if (suffix && getItemWidth(0) + suffixWidth > mergedContainerWidth) {
setSuffixFixedStart(null);
}
}
}, [mergedContainerWidth, itemWidths, restWidth, suffixWidth, getKey, mergedData]);
// ================================ Render ================================
var displayRest = restReady && !!omittedItems.length;
var suffixStyle = {};
if (suffixFixedStart !== null && shouldResponsive) {
suffixStyle = {
position: 'absolute',
left: suffixFixedStart,
top: 0
};
}
var itemSharedProps = {
prefixCls: itemPrefixCls,
responsive: shouldResponsive,
component: itemComponent,
invalidate: invalidate
};
// >>>>> Choice render fun by `renderRawItem`
var internalRenderItemNode = renderRawItem ? function (item, index) {
var key = getKey(item, index);
return /*#__PURE__*/React.createElement(OverflowContext.Provider, {
key: key,
value: _objectSpread2$1(_objectSpread2$1({}, itemSharedProps), {}, {
order: index,
item: item,
itemKey: key,
registerSize: registerSize,
display: index <= mergedDisplayCount
})
}, renderRawItem(item, index));
} : function (item, index) {
var key = getKey(item, index);
return /*#__PURE__*/React.createElement(Item$1, _extends$1({}, itemSharedProps, {
order: index,
key: key,
item: item,
renderItem: mergedRenderItem,
itemKey: key,
registerSize: registerSize,
display: index <= mergedDisplayCount
}));
};
// >>>>> Rest node
var restNode;
var restContextProps = {
order: displayRest ? mergedDisplayCount : Number.MAX_SAFE_INTEGER,
className: "".concat(itemPrefixCls, "-rest"),
registerSize: registerOverflowSize,
display: displayRest
};
if (!renderRawRest) {
var mergedRenderRest = renderRest || defaultRenderRest;
restNode = /*#__PURE__*/React.createElement(Item$1, _extends$1({}, itemSharedProps, restContextProps), typeof mergedRenderRest === 'function' ? mergedRenderRest(omittedItems) : mergedRenderRest);
} else if (renderRawRest) {
restNode = /*#__PURE__*/React.createElement(OverflowContext.Provider, {
value: _objectSpread2$1(_objectSpread2$1({}, itemSharedProps), restContextProps)
}, renderRawRest(omittedItems));
}
var overflowNode = /*#__PURE__*/React.createElement(Component, _extends$1({
className: classNames(!invalidate && prefixCls, className),
style: style,
ref: ref
}, restProps), mergedData.map(internalRenderItemNode), showRest ? restNode : null, suffix && /*#__PURE__*/React.createElement(Item$1, _extends$1({}, itemSharedProps, {
responsive: isResponsive,
responsiveDisabled: !shouldResponsive,
order: mergedDisplayCount,
className: "".concat(itemPrefixCls, "-suffix"),
registerSize: registerSuffixSize,
display: true,
style: suffixStyle
}), suffix));
if (isResponsive) {
overflowNode = /*#__PURE__*/React.createElement(RefResizeObserver, {
onResize: onOverflowResize,
disabled: !shouldResponsive
}, overflowNode);
}
return overflowNode;
}
var ForwardOverflow = /*#__PURE__*/React.forwardRef(Overflow);
ForwardOverflow.displayName = 'Overflow';
ForwardOverflow.Item = RawItem;
ForwardOverflow.RESPONSIVE = RESPONSIVE;
ForwardOverflow.INVALIDATE = INVALIDATE;
var Portal = /*#__PURE__*/forwardRef(function (props, ref) {
var didUpdate = props.didUpdate,
getContainer = props.getContainer,
children = props.children;
var parentRef = useRef();
var containerRef = useRef();
// Ref return nothing, only for wrapper check exist
useImperativeHandle(ref, function () {
return {};
});
// Create container in client side with sync to avoid useEffect not get ref
var initRef = useRef(false);
if (!initRef.current && canUseDom()) {
containerRef.current = getContainer();
parentRef.current = containerRef.current.parentNode;
initRef.current = true;
}
// [Legacy] Used by `rc-trigger`
useEffect(function () {
didUpdate === null || didUpdate === void 0 || didUpdate(props);
});
useEffect(function () {
// Restore container to original place
// React 18 StrictMode will unmount first and mount back for effect test:
// https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors
if (containerRef.current.parentNode === null && parentRef.current !== null) {
parentRef.current.appendChild(containerRef.current);
}
return function () {
var _containerRef$current;
// [Legacy] This should not be handle by Portal but parent PortalWrapper instead.
// Since some component use `Portal` directly, we have to keep the logic here.
(_containerRef$current = containerRef.current) === null || _containerRef$current === void 0 || (_containerRef$current = _containerRef$current.parentNode) === null || _containerRef$current === void 0 || _containerRef$current.removeChild(containerRef.current);
};
}, []);
return containerRef.current ? /*#__PURE__*/ReactDOM.createPortal(children, containerRef.current) : null;
});
function isPointsEq(a1, a2, isAlignPoint) {
if (isAlignPoint) {
return a1[0] === a2[0];
}
return a1[0] === a2[0] && a1[1] === a2[1];
}
function getAlignFromPlacement(builtinPlacements, placementStr, align) {
var baseAlign = builtinPlacements[placementStr] || {};
return _objectSpread2$1(_objectSpread2$1({}, baseAlign), align);
}
function getAlignPopupClassName(builtinPlacements, prefixCls, align, isAlignPoint) {
var points = align.points;
var placements = Object.keys(builtinPlacements);
for (var i = 0; i < placements.length; i += 1) {
var placement = placements[i];
if (isPointsEq(builtinPlacements[placement].points, points, isAlignPoint)) {
return "".concat(prefixCls, "-placement-").concat(placement);
}
}
return '';
}
function getMotion$1(_ref) {
var prefixCls = _ref.prefixCls,
motion = _ref.motion,
animation = _ref.animation,
transitionName = _ref.transitionName;
if (motion) {
return motion;
}
if (animation) {
return {
motionName: "".concat(prefixCls, "-").concat(animation)
};
}
if (transitionName) {
return {
motionName: transitionName
};
}
return null;
}
function Mask(props) {
var prefixCls = props.prefixCls,
visible = props.visible,
zIndex = props.zIndex,
mask = props.mask,
maskMotion = props.maskMotion,
maskAnimation = props.maskAnimation,
maskTransitionName = props.maskTransitionName;
if (!mask) {
return null;
}
var motion = {};
if (maskMotion || maskTransitionName || maskAnimation) {
motion = _objectSpread2$1({
motionAppear: true
}, getMotion$1({
motion: maskMotion,
prefixCls: prefixCls,
transitionName: maskTransitionName,
animation: maskAnimation
}));
}
return /*#__PURE__*/React.createElement(CSSMotion, _extends$1({}, motion, {
visible: visible,
removeOnLeave: true
}), function (_ref) {
var className = _ref.className;
return /*#__PURE__*/React.createElement("div", {
style: {
zIndex: zIndex
},
className: classNames("".concat(prefixCls, "-mask"), className)
});
});
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
_defineProperty(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "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(obj);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var vendorPrefix;
var jsCssMap = {
Webkit: '-webkit-',
Moz: '-moz-',
// IE did it wrong again ...
ms: '-ms-',
O: '-o-'
};
function getVendorPrefix() {
if (vendorPrefix !== undefined) {
return vendorPrefix;
}
vendorPrefix = '';
var style = document.createElement('p').style;
var testProp = 'Transform';
for (var key in jsCssMap) {
if (key + testProp in style) {
vendorPrefix = key;
}
}
return vendorPrefix;
}
function getTransitionName$1() {
return getVendorPrefix() ? "".concat(getVendorPrefix(), "TransitionProperty") : 'transitionProperty';
}
function getTransformName() {
return getVendorPrefix() ? "".concat(getVendorPrefix(), "Transform") : 'transform';
}
function setTransitionProperty(node, value) {
var name = getTransitionName$1();
if (name) {
node.style[name] = value;
if (name !== 'transitionProperty') {
node.style.transitionProperty = value;
}
}
}
function setTransform(node, value) {
var name = getTransformName();
if (name) {
node.style[name] = value;
if (name !== 'transform') {
node.style.transform = value;
}
}
}
function getTransitionProperty(node) {
return node.style.transitionProperty || node.style[getTransitionName$1()];
}
function getTransformXY(node) {
var style = window.getComputedStyle(node, null);
var transform = style.getPropertyValue('transform') || style.getPropertyValue(getTransformName());
if (transform && transform !== 'none') {
var matrix = transform.replace(/[^0-9\-.,]/g, '').split(',');
return {
x: parseFloat(matrix[12] || matrix[4], 0),
y: parseFloat(matrix[13] || matrix[5], 0)
};
}
return {
x: 0,
y: 0
};
}
var matrix2d = /matrix\((.*)\)/;
var matrix3d = /matrix3d\((.*)\)/;
function setTransformXY(node, xy) {
var style = window.getComputedStyle(node, null);
var transform = style.getPropertyValue('transform') || style.getPropertyValue(getTransformName());
if (transform && transform !== 'none') {
var arr;
var match2d = transform.match(matrix2d);
if (match2d) {
match2d = match2d[1];
arr = match2d.split(',').map(function (item) {
return parseFloat(item, 10);
});
arr[4] = xy.x;
arr[5] = xy.y;
setTransform(node, "matrix(".concat(arr.join(','), ")"));
} else {
var match3d = transform.match(matrix3d)[1];
arr = match3d.split(',').map(function (item) {
return parseFloat(item, 10);
});
arr[12] = xy.x;
arr[13] = xy.y;
setTransform(node, "matrix3d(".concat(arr.join(','), ")"));
}
} else {
setTransform(node, "translateX(".concat(xy.x, "px) translateY(").concat(xy.y, "px) translateZ(0)"));
}
}
var RE_NUM = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source;
var getComputedStyleX;
// https://stackoverflow.com/a/3485654/3040605
function forceRelayout(elem) {
var originalStyle = elem.style.display;
elem.style.display = 'none';
elem.offsetHeight; // eslint-disable-line
elem.style.display = originalStyle;
}
function css(el, name, v) {
var value = v;
if (_typeof(name) === 'object') {
for (var i in name) {
if (name.hasOwnProperty(i)) {
css(el, i, name[i]);
}
}
return undefined;
}
if (typeof value !== 'undefined') {
if (typeof value === 'number') {
value = "".concat(value, "px");
}
el.style[name] = value;
return undefined;
}
return getComputedStyleX(el, name);
}
function getClientPosition(elem) {
var box;
var x;
var y;
var doc = elem.ownerDocument;
var body = doc.body;
var docElem = doc && doc.documentElement;
// 根据 GBS 最新数据,A-Grade Browsers 都已支持 getBoundingClientRect 方法,不用再考虑传统的实现方式
box = elem.getBoundingClientRect();
// 注:jQuery 还考虑减去 docElem.clientLeft/clientTop
// 但测试发现,这样反而会导致当 html 和 body 有边距/边框样式时,获取的值不正确
// 此外,ie6 会忽略 html 的 margin 值,幸运地是没有谁会去设置 html 的 margin
x = Math.floor(box.left);
y = Math.floor(box.top);
// In IE, most of the time, 2 extra pixels are added to the top and left
// due to the implicit 2-pixel inset border. In IE6/7 quirks mode and
// IE6 standards mode, this border can be overridden by setting the
// document element's border to zero -- thus, we cannot rely on the
// offset always being 2 pixels.
// In quirks mode, the offset can be determined by querying the body's
// clientLeft/clientTop, but in standards mode, it is found by querying
// the document element's clientLeft/clientTop. Since we already called
// getClientBoundingRect we have already forced a reflow, so it is not
// too expensive just to query them all.
// ie 下应该减去窗口的边框吧,毕竟默认 absolute 都是相对窗口定位的
// 窗口边框标准是设 documentElement ,quirks 时设置 body
// 最好禁止在 body 和 html 上边框 ,但 ie < 9 html 默认有 2px ,减去
// 但是非 ie 不可能设置窗口边框,body html 也不是窗口 ,ie 可以通过 html,body 设置
// 标准 ie 下 docElem.clientTop 就是 border-top
// ie7 html 即窗口边框改变不了。永远为 2
// 但标准 firefox/chrome/ie9 下 docElem.clientTop 是窗口边框,即使设了 border-top 也为 0
x -= docElem.clientLeft || body.clientLeft || 0;
y -= docElem.clientTop || body.clientTop || 0;
return {
left: x,
top: y
};
}
function getScroll(w, top) {
var ret = w["page".concat(top ? 'Y' : 'X', "Offset")];
var method = "scroll".concat(top ? 'Top' : 'Left');
if (typeof ret !== 'number') {
var d = w.document;
// ie6,7,8 standard mode
ret = d.documentElement[method];
if (typeof ret !== 'number') {
// quirks mode
ret = d.body[method];
}
}
return ret;
}
function getScrollLeft(w) {
return getScroll(w);
}
function getScrollTop(w) {
return getScroll(w, true);
}
function getOffset$2(el) {
var pos = getClientPosition(el);
var doc = el.ownerDocument;
var w = doc.defaultView || doc.parentWindow;
pos.left += getScrollLeft(w);
pos.top += getScrollTop(w);
return pos;
}
/**
* A crude way of determining if an object is a window
* @member util
*/
function isWindow(obj) {
// must use == for ie8
/* eslint eqeqeq:0 */
return obj !== null && obj !== undefined && obj == obj.window;
}
function getDocument(node) {
if (isWindow(node)) {
return node.document;
}
if (node.nodeType === 9) {
return node;
}
return node.ownerDocument;
}
function _getComputedStyle(elem, name, cs) {
var computedStyle = cs;
var val = '';
var d = getDocument(elem);
computedStyle = computedStyle || d.defaultView.getComputedStyle(elem, null);
// https://github.com/kissyteam/kissy/issues/61
if (computedStyle) {
val = computedStyle.getPropertyValue(name) || computedStyle[name];
}
return val;
}
var _RE_NUM_NO_PX = new RegExp("^(".concat(RE_NUM, ")(?!px)[a-z%]+$"), 'i');
var RE_POS = /^(top|right|bottom|left)$/;
var CURRENT_STYLE = 'currentStyle';
var RUNTIME_STYLE = 'runtimeStyle';
var LEFT$1 = 'left';
var PX = 'px';
function _getComputedStyleIE(elem, name) {
// currentStyle maybe null
// http://msdn.microsoft.com/en-us/library/ms535231.aspx
var ret = elem[CURRENT_STYLE] && elem[CURRENT_STYLE][name];
// 当 width/height 设置为百分比时,通过 pixelLeft 方式转换的 width/height 值
// 一开始就处理了! CUSTOM_STYLE.height,CUSTOM_STYLE.width ,cssHook 解决@2011-08-19
// 在 ie 下不对,需要直接用 offset 方式
// borderWidth 等值也有问题,但考虑到 borderWidth 设为百分比的概率很小,这里就不考虑了
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// exclude left right for relativity
if (_RE_NUM_NO_PX.test(ret) && !RE_POS.test(name)) {
// Remember the original values
var style = elem.style;
var left = style[LEFT$1];
var rsLeft = elem[RUNTIME_STYLE][LEFT$1];
// prevent flashing of content
elem[RUNTIME_STYLE][LEFT$1] = elem[CURRENT_STYLE][LEFT$1];
// Put in the new values to get a computed value out
style[LEFT$1] = name === 'fontSize' ? '1em' : ret || 0;
ret = style.pixelLeft + PX;
// Revert the changed values
style[LEFT$1] = left;
elem[RUNTIME_STYLE][LEFT$1] = rsLeft;
}
return ret === '' ? 'auto' : ret;
}
if (typeof window !== 'undefined') {
getComputedStyleX = window.getComputedStyle ? _getComputedStyle : _getComputedStyleIE;
}
function getOffsetDirection(dir, option) {
if (dir === 'left') {
return option.useCssRight ? 'right' : dir;
}
return option.useCssBottom ? 'bottom' : dir;
}
function oppositeOffsetDirection(dir) {
if (dir === 'left') {
return 'right';
} else if (dir === 'right') {
return 'left';
} else if (dir === 'top') {
return 'bottom';
} else if (dir === 'bottom') {
return 'top';
}
}
// 设置 elem 相对 elem.ownerDocument 的坐标
function setLeftTop(elem, offset, option) {
// set position first, in-case top/left are set even on static elem
if (css(elem, 'position') === 'static') {
elem.style.position = 'relative';
}
var presetH = -999;
var presetV = -999;
var horizontalProperty = getOffsetDirection('left', option);
var verticalProperty = getOffsetDirection('top', option);
var oppositeHorizontalProperty = oppositeOffsetDirection(horizontalProperty);
var oppositeVerticalProperty = oppositeOffsetDirection(verticalProperty);
if (horizontalProperty !== 'left') {
presetH = 999;
}
if (verticalProperty !== 'top') {
presetV = 999;
}
var originalTransition = '';
var originalOffset = getOffset$2(elem);
if ('left' in offset || 'top' in offset) {
originalTransition = getTransitionProperty(elem) || '';
setTransitionProperty(elem, 'none');
}
if ('left' in offset) {
elem.style[oppositeHorizontalProperty] = '';
elem.style[horizontalProperty] = "".concat(presetH, "px");
}
if ('top' in offset) {
elem.style[oppositeVerticalProperty] = '';
elem.style[verticalProperty] = "".concat(presetV, "px");
}
// force relayout
forceRelayout(elem);
var old = getOffset$2(elem);
var originalStyle = {};
for (var key in offset) {
if (offset.hasOwnProperty(key)) {
var dir = getOffsetDirection(key, option);
var preset = key === 'left' ? presetH : presetV;
var off = originalOffset[key] - old[key];
if (dir === key) {
originalStyle[dir] = preset + off;
} else {
originalStyle[dir] = preset - off;
}
}
}
css(elem, originalStyle);
// force relayout
forceRelayout(elem);
if ('left' in offset || 'top' in offset) {
setTransitionProperty(elem, originalTransition);
}
var ret = {};
for (var _key in offset) {
if (offset.hasOwnProperty(_key)) {
var _dir = getOffsetDirection(_key, option);
var _off = offset[_key] - originalOffset[_key];
if (_key === _dir) {
ret[_dir] = originalStyle[_dir] + _off;
} else {
ret[_dir] = originalStyle[_dir] - _off;
}
}
}
css(elem, ret);
}
function setTransform$1(elem, offset) {
var originalOffset = getOffset$2(elem);
var originalXY = getTransformXY(elem);
var resultXY = {
x: originalXY.x,
y: originalXY.y
};
if ('left' in offset) {
resultXY.x = originalXY.x + offset.left - originalOffset.left;
}
if ('top' in offset) {
resultXY.y = originalXY.y + offset.top - originalOffset.top;
}
setTransformXY(elem, resultXY);
}
function setOffset(elem, offset, option) {
if (option.ignoreShake) {
var oriOffset = getOffset$2(elem);
var oLeft = oriOffset.left.toFixed(0);
var oTop = oriOffset.top.toFixed(0);
var tLeft = offset.left.toFixed(0);
var tTop = offset.top.toFixed(0);
if (oLeft === tLeft && oTop === tTop) {
return;
}
}
if (option.useCssRight || option.useCssBottom) {
setLeftTop(elem, offset, option);
} else if (option.useCssTransform && getTransformName() in document.body.style) {
setTransform$1(elem, offset);
} else {
setLeftTop(elem, offset, option);
}
}
function each(arr, fn) {
for (var i = 0; i < arr.length; i++) {
fn(arr[i]);
}
}
function isBorderBoxFn(elem) {
return getComputedStyleX(elem, 'boxSizing') === 'border-box';
}
var BOX_MODELS = ['margin', 'border', 'padding'];
var CONTENT_INDEX = -1;
var PADDING_INDEX = 2;
var BORDER_INDEX = 1;
var MARGIN_INDEX = 0;
function swap(elem, options, callback) {
var old = {};
var style = elem.style;
var name;
// Remember the old values, and insert the new ones
for (name in options) {
if (options.hasOwnProperty(name)) {
old[name] = style[name];
style[name] = options[name];
}
}
callback.call(elem);
// Revert the old values
for (name in options) {
if (options.hasOwnProperty(name)) {
style[name] = old[name];
}
}
}
function getPBMWidth(elem, props, which) {
var value = 0;
var prop;
var j;
var i;
for (j = 0; j < props.length; j++) {
prop = props[j];
if (prop) {
for (i = 0; i < which.length; i++) {
var cssProp = void 0;
if (prop === 'border') {
cssProp = "".concat(prop).concat(which[i], "Width");
} else {
cssProp = prop + which[i];
}
value += parseFloat(getComputedStyleX(elem, cssProp)) || 0;
}
}
}
return value;
}
var domUtils = {
getParent: function getParent(element) {
var parent = element;
do {
if (parent.nodeType === 11 && parent.host) {
parent = parent.host;
} else {
parent = parent.parentNode;
}
} while (parent && parent.nodeType !== 1 && parent.nodeType !== 9);
return parent;
}
};
each(['Width', 'Height'], function (name) {
domUtils["doc".concat(name)] = function (refWin) {
var d = refWin.document;
return Math.max(
// firefox chrome documentElement.scrollHeight< body.scrollHeight
// ie standard mode : documentElement.scrollHeight> body.scrollHeight
d.documentElement["scroll".concat(name)],
// quirks : documentElement.scrollHeight 最大等于可视窗口多一点?
d.body["scroll".concat(name)], domUtils["viewport".concat(name)](d));
};
domUtils["viewport".concat(name)] = function (win) {
// pc browser includes scrollbar in window.innerWidth
var prop = "client".concat(name);
var doc = win.document;
var body = doc.body;
var documentElement = doc.documentElement;
var documentElementProp = documentElement[prop];
// 标准模式取 documentElement
// backcompat 取 body
return doc.compatMode === 'CSS1Compat' && documentElementProp || body && body[prop] || documentElementProp;
};
});
/*
得到元素的大小信息
@param elem
@param name
@param {String} [extra] 'padding' : (css width) + padding
'border' : (css width) + padding + border
'margin' : (css width) + padding + border + margin
*/
function getWH(elem, name, ex) {
var extra = ex;
if (isWindow(elem)) {
return name === 'width' ? domUtils.viewportWidth(elem) : domUtils.viewportHeight(elem);
} else if (elem.nodeType === 9) {
return name === 'width' ? domUtils.docWidth(elem) : domUtils.docHeight(elem);
}
var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'];
var borderBoxValue = name === 'width' ? Math.floor(elem.getBoundingClientRect().width) : Math.floor(elem.getBoundingClientRect().height);
var isBorderBox = isBorderBoxFn(elem);
var cssBoxValue = 0;
if (borderBoxValue === null || borderBoxValue === undefined || borderBoxValue <= 0) {
borderBoxValue = undefined;
// Fall back to computed then un computed css if necessary
cssBoxValue = getComputedStyleX(elem, name);
if (cssBoxValue === null || cssBoxValue === undefined || Number(cssBoxValue) < 0) {
cssBoxValue = elem.style[name] || 0;
}
// Normalize '', auto, and prepare for extra
cssBoxValue = Math.floor(parseFloat(cssBoxValue)) || 0;
}
if (extra === undefined) {
extra = isBorderBox ? BORDER_INDEX : CONTENT_INDEX;
}
var borderBoxValueOrIsBorderBox = borderBoxValue !== undefined || isBorderBox;
var val = borderBoxValue || cssBoxValue;
if (extra === CONTENT_INDEX) {
if (borderBoxValueOrIsBorderBox) {
return val - getPBMWidth(elem, ['border', 'padding'], which);
}
return cssBoxValue;
} else if (borderBoxValueOrIsBorderBox) {
if (extra === BORDER_INDEX) {
return val;
}
return val + (extra === PADDING_INDEX ? -getPBMWidth(elem, ['border'], which) : getPBMWidth(elem, ['margin'], which));
}
return cssBoxValue + getPBMWidth(elem, BOX_MODELS.slice(extra), which);
}
var cssShow = {
position: 'absolute',
visibility: 'hidden',
display: 'block'
};
// fix #119 : https://github.com/kissyteam/kissy/issues/119
function getWHIgnoreDisplay() {
for (var _len = arguments.length, args = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
args[_key2] = arguments[_key2];
}
var val;
var elem = args[0];
// in case elem is window
// elem.offsetWidth === undefined
if (elem.offsetWidth !== 0) {
val = getWH.apply(undefined, args);
} else {
swap(elem, cssShow, function () {
val = getWH.apply(undefined, args);
});
}
return val;
}
each(['width', 'height'], function (name) {
var first = name.charAt(0).toUpperCase() + name.slice(1);
domUtils["outer".concat(first)] = function (el, includeMargin) {
return el && getWHIgnoreDisplay(el, name, includeMargin ? MARGIN_INDEX : BORDER_INDEX);
};
var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'];
domUtils[name] = function (elem, v) {
var val = v;
if (val !== undefined) {
if (elem) {
var isBorderBox = isBorderBoxFn(elem);
if (isBorderBox) {
val += getPBMWidth(elem, ['padding', 'border'], which);
}
return css(elem, name, val);
}
return undefined;
}
return elem && getWHIgnoreDisplay(elem, name, CONTENT_INDEX);
};
});
function mix(to, from) {
for (var i in from) {
if (from.hasOwnProperty(i)) {
to[i] = from[i];
}
}
return to;
}
var utils = {
getWindow: function getWindow(node) {
if (node && node.document && node.setTimeout) {
return node;
}
var doc = node.ownerDocument || node;
return doc.defaultView || doc.parentWindow;
},
getDocument: getDocument,
offset: function offset(el, value, option) {
if (typeof value !== 'undefined') {
setOffset(el, value, option || {});
} else {
return getOffset$2(el);
}
},
isWindow: isWindow,
each: each,
css: css,
clone: function clone(obj) {
var i;
var ret = {};
for (i in obj) {
if (obj.hasOwnProperty(i)) {
ret[i] = obj[i];
}
}
var overflow = obj.overflow;
if (overflow) {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
ret.overflow[i] = obj.overflow[i];
}
}
}
return ret;
},
mix: mix,
getWindowScrollLeft: function getWindowScrollLeft(w) {
return getScrollLeft(w);
},
getWindowScrollTop: function getWindowScrollTop(w) {
return getScrollTop(w);
},
merge: function merge() {
var ret = {};
for (var i = 0; i < arguments.length; i++) {
utils.mix(ret, i < 0 || arguments.length <= i ? undefined : arguments[i]);
}
return ret;
},
viewportWidth: 0,
viewportHeight: 0
};
mix(utils, domUtils);
/**
* 得到会导致元素显示不全的祖先元素
*/
var getParent = utils.getParent;
function getOffsetParent(element) {
if (utils.isWindow(element) || element.nodeType === 9) {
return null;
}
// ie 这个也不是完全可行
/*
<div style="width: 50px;height: 100px;overflow: hidden">
<div style="width: 50px;height: 100px;position: relative;" id="d6">
元素 6 高 100px 宽 50px<br/>
</div>
</div>
*/
// element.offsetParent does the right thing in ie7 and below. Return parent with layout!
// In other browsers it only includes elements with position absolute, relative or
// fixed, not elements with overflow set to auto or scroll.
// if (UA.ie && ieMode < 8) {
// return element.offsetParent;
// }
// 统一的 offsetParent 方法
var doc = utils.getDocument(element);
var body = doc.body;
var parent;
var positionStyle = utils.css(element, 'position');
var skipStatic = positionStyle === 'fixed' || positionStyle === 'absolute';
if (!skipStatic) {
return element.nodeName.toLowerCase() === 'html' ? null : getParent(element);
}
for (parent = getParent(element); parent && parent !== body && parent.nodeType !== 9; parent = getParent(parent)) {
positionStyle = utils.css(parent, 'position');
if (positionStyle !== 'static') {
return parent;
}
}
return null;
}
var getParent$1 = utils.getParent;
function isAncestorFixed(element) {
if (utils.isWindow(element) || element.nodeType === 9) {
return false;
}
var doc = utils.getDocument(element);
var body = doc.body;
var parent = null;
for (parent = getParent$1(element);
// 修复元素位于 document.documentElement 下导致崩溃问题
parent && parent !== body && parent !== doc; parent = getParent$1(parent)) {
var positionStyle = utils.css(parent, 'position');
if (positionStyle === 'fixed') {
return true;
}
}
return false;
}
/**
* 获得元素的显示部分的区域
*/
function getVisibleRectForElement(element, alwaysByViewport) {
var visibleRect = {
left: 0,
right: Infinity,
top: 0,
bottom: Infinity
};
var el = getOffsetParent(element);
var doc = utils.getDocument(element);
var win = doc.defaultView || doc.parentWindow;
var body = doc.body;
var documentElement = doc.documentElement;
// Determine the size of the visible rect by climbing the dom accounting for
// all scrollable containers.
while (el) {
// clientWidth is zero for inline block elements in ie.
if ((navigator.userAgent.indexOf('MSIE') === -1 || el.clientWidth !== 0) &&
// body may have overflow set on it, yet we still get the entire
// viewport. In some browsers, el.offsetParent may be
// document.documentElement, so check for that too.
el !== body && el !== documentElement && utils.css(el, 'overflow') !== 'visible') {
var pos = utils.offset(el);
// add border
pos.left += el.clientLeft;
pos.top += el.clientTop;
visibleRect.top = Math.max(visibleRect.top, pos.top);
visibleRect.right = Math.min(visibleRect.right,
// consider area without scrollBar
pos.left + el.clientWidth);
visibleRect.bottom = Math.min(visibleRect.bottom, pos.top + el.clientHeight);
visibleRect.left = Math.max(visibleRect.left, pos.left);
} else if (el === body || el === documentElement) {
break;
}
el = getOffsetParent(el);
}
// Set element position to fixed
// make sure absolute element itself don't affect it's visible area
// https://github.com/ant-design/ant-design/issues/7601
var originalPosition = null;
if (!utils.isWindow(element) && element.nodeType !== 9) {
originalPosition = element.style.position;
var position = utils.css(element, 'position');
if (position === 'absolute') {
element.style.position = 'fixed';
}
}
var scrollX = utils.getWindowScrollLeft(win);
var scrollY = utils.getWindowScrollTop(win);
var viewportWidth = utils.viewportWidth(win);
var viewportHeight = utils.viewportHeight(win);
var documentWidth = documentElement.scrollWidth;
var documentHeight = documentElement.scrollHeight;
// scrollXXX on html is sync with body which means overflow: hidden on body gets wrong scrollXXX.
// We should cut this ourself.
var bodyStyle = window.getComputedStyle(body);
if (bodyStyle.overflowX === 'hidden') {
documentWidth = win.innerWidth;
}
if (bodyStyle.overflowY === 'hidden') {
documentHeight = win.innerHeight;
}
// Reset element position after calculate the visible area
if (element.style) {
element.style.position = originalPosition;
}
if (alwaysByViewport || isAncestorFixed(element)) {
// Clip by viewport's size.
visibleRect.left = Math.max(visibleRect.left, scrollX);
visibleRect.top = Math.max(visibleRect.top, scrollY);
visibleRect.right = Math.min(visibleRect.right, scrollX + viewportWidth);
visibleRect.bottom = Math.min(visibleRect.bottom, scrollY + viewportHeight);
} else {
// Clip by document's size.
var maxVisibleWidth = Math.max(documentWidth, scrollX + viewportWidth);
visibleRect.right = Math.min(visibleRect.right, maxVisibleWidth);
var maxVisibleHeight = Math.max(documentHeight, scrollY + viewportHeight);
visibleRect.bottom = Math.min(visibleRect.bottom, maxVisibleHeight);
}
return visibleRect.top >= 0 && visibleRect.left >= 0 && visibleRect.bottom > visibleRect.top && visibleRect.right > visibleRect.left ? visibleRect : null;
}
function adjustForViewport(elFuturePos, elRegion, visibleRect, overflow) {
var pos = utils.clone(elFuturePos);
var size = {
width: elRegion.width,
height: elRegion.height
};
if (overflow.adjustX && pos.left < visibleRect.left) {
pos.left = visibleRect.left;
}
// Left edge inside and right edge outside viewport, try to resize it.
if (overflow.resizeWidth && pos.left >= visibleRect.left && pos.left + size.width > visibleRect.right) {
size.width -= pos.left + size.width - visibleRect.right;
}
// Right edge outside viewport, try to move it.
if (overflow.adjustX && pos.left + size.width > visibleRect.right) {
// 保证左边界和可视区域左边界对齐
pos.left = Math.max(visibleRect.right - size.width, visibleRect.left);
}
// Top edge outside viewport, try to move it.
if (overflow.adjustY && pos.top < visibleRect.top) {
pos.top = visibleRect.top;
}
// Top edge inside and bottom edge outside viewport, try to resize it.
if (overflow.resizeHeight && pos.top >= visibleRect.top && pos.top + size.height > visibleRect.bottom) {
size.height -= pos.top + size.height - visibleRect.bottom;
}
// Bottom edge outside viewport, try to move it.
if (overflow.adjustY && pos.top + size.height > visibleRect.bottom) {
// 保证上边界和可视区域上边界对齐
pos.top = Math.max(visibleRect.bottom - size.height, visibleRect.top);
}
return utils.mix(pos, size);
}
function getRegion(node) {
var offset;
var w;
var h;
if (!utils.isWindow(node) && node.nodeType !== 9) {
offset = utils.offset(node);
w = utils.outerWidth(node);
h = utils.outerHeight(node);
} else {
var win = utils.getWindow(node);
offset = {
left: utils.getWindowScrollLeft(win),
top: utils.getWindowScrollTop(win)
};
w = utils.viewportWidth(win);
h = utils.viewportHeight(win);
}
offset.width = w;
offset.height = h;
return offset;
}
/**
* 获取 node 上的 align 对齐点 相对于页面的坐标
*/
function getAlignOffset(region, align) {
var V = align.charAt(0);
var H = align.charAt(1);
var w = region.width;
var h = region.height;
var x = region.left;
var y = region.top;
if (V === 'c') {
y += h / 2;
} else if (V === 'b') {
y += h;
}
if (H === 'c') {
x += w / 2;
} else if (H === 'r') {
x += w;
}
return {
left: x,
top: y
};
}
function getElFuturePos(elRegion, refNodeRegion, points, offset, targetOffset) {
var p1 = getAlignOffset(refNodeRegion, points[1]);
var p2 = getAlignOffset(elRegion, points[0]);
var diff = [p2.left - p1.left, p2.top - p1.top];
return {
left: Math.round(elRegion.left - diff[0] + offset[0] - targetOffset[0]),
top: Math.round(elRegion.top - diff[1] + offset[1] - targetOffset[1])
};
}
/**
* align dom node flexibly
* @author yiminghe@gmail.com
*/
// http://yiminghe.iteye.com/blog/1124720
function isFailX(elFuturePos, elRegion, visibleRect) {
return elFuturePos.left < visibleRect.left || elFuturePos.left + elRegion.width > visibleRect.right;
}
function isFailY(elFuturePos, elRegion, visibleRect) {
return elFuturePos.top < visibleRect.top || elFuturePos.top + elRegion.height > visibleRect.bottom;
}
function isCompleteFailX(elFuturePos, elRegion, visibleRect) {
return elFuturePos.left > visibleRect.right || elFuturePos.left + elRegion.width < visibleRect.left;
}
function isCompleteFailY(elFuturePos, elRegion, visibleRect) {
return elFuturePos.top > visibleRect.bottom || elFuturePos.top + elRegion.height < visibleRect.top;
}
function flip(points, reg, map) {
var ret = [];
utils.each(points, function (p) {
ret.push(p.replace(reg, function (m) {
return map[m];
}));
});
return ret;
}
function flipOffset(offset, index) {
offset[index] = -offset[index];
return offset;
}
function convertOffset(str, offsetLen) {
var n;
if (/%$/.test(str)) {
n = parseInt(str.substring(0, str.length - 1), 10) / 100 * offsetLen;
} else {
n = parseInt(str, 10);
}
return n || 0;
}
function normalizeOffset(offset, el) {
offset[0] = convertOffset(offset[0], el.width);
offset[1] = convertOffset(offset[1], el.height);
}
/**
* @param el
* @param tgtRegion 参照节点所占的区域: { left, top, width, height }
* @param align
*/
function doAlign(el, tgtRegion, align, isTgtRegionVisible) {
var points = align.points;
var offset = align.offset || [0, 0];
var targetOffset = align.targetOffset || [0, 0];
var overflow = align.overflow;
var source = align.source || el;
offset = [].concat(offset);
targetOffset = [].concat(targetOffset);
overflow = overflow || {};
var newOverflowCfg = {};
var fail = 0;
var alwaysByViewport = !!(overflow && overflow.alwaysByViewport);
// 当前节点可以被放置的显示区域
var visibleRect = getVisibleRectForElement(source, alwaysByViewport);
// 当前节点所占的区域, left/top/width/height
var elRegion = getRegion(source);
// 将 offset 转换成数值,支持百分比
normalizeOffset(offset, elRegion);
normalizeOffset(targetOffset, tgtRegion);
// 当前节点将要被放置的位置
var elFuturePos = getElFuturePos(elRegion, tgtRegion, points, offset, targetOffset);
// 当前节点将要所处的区域
var newElRegion = utils.merge(elRegion, elFuturePos);
// 如果可视区域不能完全放置当前节点时允许调整
if (visibleRect && (overflow.adjustX || overflow.adjustY) && isTgtRegionVisible) {
if (overflow.adjustX) {
// 如果横向不能放下
if (isFailX(elFuturePos, elRegion, visibleRect)) {
// 对齐位置反下
var newPoints = flip(points, /[lr]/gi, {
l: 'r',
r: 'l'
});
// 偏移量也反下
var newOffset = flipOffset(offset, 0);
var newTargetOffset = flipOffset(targetOffset, 0);
var newElFuturePos = getElFuturePos(elRegion, tgtRegion, newPoints, newOffset, newTargetOffset);
if (!isCompleteFailX(newElFuturePos, elRegion, visibleRect)) {
fail = 1;
points = newPoints;
offset = newOffset;
targetOffset = newTargetOffset;
}
}
}
if (overflow.adjustY) {
// 如果纵向不能放下
if (isFailY(elFuturePos, elRegion, visibleRect)) {
// 对齐位置反下
var _newPoints = flip(points, /[tb]/gi, {
t: 'b',
b: 't'
});
// 偏移量也反下
var _newOffset = flipOffset(offset, 1);
var _newTargetOffset = flipOffset(targetOffset, 1);
var _newElFuturePos = getElFuturePos(elRegion, tgtRegion, _newPoints, _newOffset, _newTargetOffset);
if (!isCompleteFailY(_newElFuturePos, elRegion, visibleRect)) {
fail = 1;
points = _newPoints;
offset = _newOffset;
targetOffset = _newTargetOffset;
}
}
}
// 如果失败,重新计算当前节点将要被放置的位置
if (fail) {
elFuturePos = getElFuturePos(elRegion, tgtRegion, points, offset, targetOffset);
utils.mix(newElRegion, elFuturePos);
}
var isStillFailX = isFailX(elFuturePos, elRegion, visibleRect);
var isStillFailY = isFailY(elFuturePos, elRegion, visibleRect);
// 检查反下后的位置是否可以放下了,如果仍然放不下:
// 1. 复原修改过的定位参数
if (isStillFailX || isStillFailY) {
var _newPoints2 = points;
// 重置对应部分的翻转逻辑
if (isStillFailX) {
_newPoints2 = flip(points, /[lr]/gi, {
l: 'r',
r: 'l'
});
}
if (isStillFailY) {
_newPoints2 = flip(points, /[tb]/gi, {
t: 'b',
b: 't'
});
}
points = _newPoints2;
offset = align.offset || [0, 0];
targetOffset = align.targetOffset || [0, 0];
}
// 2. 只有指定了可以调整当前方向才调整
newOverflowCfg.adjustX = overflow.adjustX && isStillFailX;
newOverflowCfg.adjustY = overflow.adjustY && isStillFailY;
// 确实要调整,甚至可能会调整高度宽度
if (newOverflowCfg.adjustX || newOverflowCfg.adjustY) {
newElRegion = adjustForViewport(elFuturePos, elRegion, visibleRect, newOverflowCfg);
}
}
// need judge to in case set fixed with in css on height auto element
if (newElRegion.width !== elRegion.width) {
utils.css(source, 'width', utils.width(source) + newElRegion.width - elRegion.width);
}
if (newElRegion.height !== elRegion.height) {
utils.css(source, 'height', utils.height(source) + newElRegion.height - elRegion.height);
}
// https://github.com/kissyteam/kissy/issues/190
// 相对于屏幕位置没变,而 left/top 变了
// 例如 <div 'relative'><el absolute></div>
utils.offset(source, {
left: newElRegion.left,
top: newElRegion.top
}, {
useCssRight: align.useCssRight,
useCssBottom: align.useCssBottom,
useCssTransform: align.useCssTransform,
ignoreShake: align.ignoreShake
});
return {
points: points,
offset: offset,
targetOffset: targetOffset,
overflow: newOverflowCfg
};
}
/**
* 2012-04-26 yiminghe@gmail.com
* - 优化智能对齐算法
* - 慎用 resizeXX
*
* 2011-07-13 yiminghe@gmail.com note:
* - 增加智能对齐,以及大小调整选项
**/
function isOutOfVisibleRect(target, alwaysByViewport) {
var visibleRect = getVisibleRectForElement(target, alwaysByViewport);
var targetRegion = getRegion(target);
return !visibleRect || targetRegion.left + targetRegion.width <= visibleRect.left || targetRegion.top + targetRegion.height <= visibleRect.top || targetRegion.left >= visibleRect.right || targetRegion.top >= visibleRect.bottom;
}
function alignElement(el, refNode, align) {
var target = align.target || refNode;
var refNodeRegion = getRegion(target);
var isTargetNotOutOfVisible = !isOutOfVisibleRect(target, align.overflow && align.overflow.alwaysByViewport);
return doAlign(el, refNodeRegion, align, isTargetNotOutOfVisible);
}
alignElement.__getOffsetParent = getOffsetParent;
alignElement.__getVisibleRectForElement = getVisibleRectForElement;
/**
* `tgtPoint`: { pageX, pageY } or { clientX, clientY }.
* If client position provided, will internal convert to page position.
*/
function alignPoint(el, tgtPoint, align) {
var pageX;
var pageY;
var doc = utils.getDocument(el);
var win = doc.defaultView || doc.parentWindow;
var scrollX = utils.getWindowScrollLeft(win);
var scrollY = utils.getWindowScrollTop(win);
var viewportWidth = utils.viewportWidth(win);
var viewportHeight = utils.viewportHeight(win);
if ('pageX' in tgtPoint) {
pageX = tgtPoint.pageX;
} else {
pageX = scrollX + tgtPoint.clientX;
}
if ('pageY' in tgtPoint) {
pageY = tgtPoint.pageY;
} else {
pageY = scrollY + tgtPoint.clientY;
}
var tgtRegion = {
left: pageX,
top: pageY,
width: 0,
height: 0
};
var pointInView = pageX >= 0 && pageX <= scrollX + viewportWidth && pageY >= 0 && pageY <= scrollY + viewportHeight;
// Provide default target point
var points = [align.points[0], 'cc'];
return doAlign(el, tgtRegion, _objectSpread2(_objectSpread2({}, align), {}, {
points: points
}), pointInView);
}
var isVisible = (function (element) {
if (!element) {
return false;
}
if (element instanceof Element) {
if (element.offsetParent) {
return true;
}
if (element.getBBox) {
var _getBBox = element.getBBox(),
width = _getBBox.width,
height = _getBBox.height;
if (width || height) {
return true;
}
}
if (element.getBoundingClientRect) {
var _element$getBoundingC = element.getBoundingClientRect(),
_width = _element$getBoundingC.width,
_height = _element$getBoundingC.height;
if (_width || _height) {
return true;
}
}
}
return false;
});
var useBuffer = (function (callback, buffer) {
var calledRef = React__default.useRef(false);
var timeoutRef = React__default.useRef(null);
function cancelTrigger() {
window.clearTimeout(timeoutRef.current);
}
function trigger(force) {
cancelTrigger();
if (!calledRef.current || force === true) {
if (callback(force) === false) {
// Not delay since callback cancelled self
return;
}
calledRef.current = true;
timeoutRef.current = window.setTimeout(function () {
calledRef.current = false;
}, buffer);
} else {
timeoutRef.current = window.setTimeout(function () {
calledRef.current = false;
trigger();
}, buffer);
}
}
return [trigger, function () {
calledRef.current = false;
cancelTrigger();
}];
});
function isSamePoint(prev, next) {
if (prev === next) return true;
if (!prev || !next) return false;
if ('pageX' in next && 'pageY' in next) {
return prev.pageX === next.pageX && prev.pageY === next.pageY;
}
if ('clientX' in next && 'clientY' in next) {
return prev.clientX === next.clientX && prev.clientY === next.clientY;
}
return false;
}
function restoreFocus(activeElement, container) {
// Focus back if is in the container
if (activeElement !== document.activeElement && contains(container, activeElement) && typeof activeElement.focus === 'function') {
activeElement.focus();
}
}
function monitorResize(element, callback) {
var prevWidth = null;
var prevHeight = null;
function onResize(_ref) {
var _ref2 = _slicedToArray(_ref, 1),
target = _ref2[0].target;
if (!document.documentElement.contains(target)) return;
var _target$getBoundingCl = target.getBoundingClientRect(),
width = _target$getBoundingCl.width,
height = _target$getBoundingCl.height;
var fixedWidth = Math.floor(width);
var fixedHeight = Math.floor(height);
if (prevWidth !== fixedWidth || prevHeight !== fixedHeight) {
// https://webkit.org/blog/9997/resizeobserver-in-webkit/
Promise.resolve().then(function () {
callback({
width: fixedWidth,
height: fixedHeight
});
});
}
prevWidth = fixedWidth;
prevHeight = fixedHeight;
}
var resizeObserver = new index(onResize);
if (element) {
resizeObserver.observe(element);
}
return function () {
resizeObserver.disconnect();
};
}
function getElement(func) {
if (typeof func !== 'function') return null;
return func();
}
function getPoint(point) {
if (_typeof$1(point) !== 'object' || !point) return null;
return point;
}
var Align = function Align(_ref, ref) {
var children = _ref.children,
disabled = _ref.disabled,
target = _ref.target,
align = _ref.align,
onAlign = _ref.onAlign,
monitorWindowResize = _ref.monitorWindowResize,
_ref$monitorBufferTim = _ref.monitorBufferTime,
monitorBufferTime = _ref$monitorBufferTim === void 0 ? 0 : _ref$monitorBufferTim;
var cacheRef = React__default.useRef({});
/** Popup node ref */
var nodeRef = React__default.useRef();
var childNode = React__default.Children.only(children); // ===================== Align ======================
// We save the props here to avoid closure makes props ood
var forceAlignPropsRef = React__default.useRef({});
forceAlignPropsRef.current.disabled = disabled;
forceAlignPropsRef.current.target = target;
forceAlignPropsRef.current.align = align;
forceAlignPropsRef.current.onAlign = onAlign;
var _useBuffer = useBuffer(function () {
var _forceAlignPropsRef$c = forceAlignPropsRef.current,
latestDisabled = _forceAlignPropsRef$c.disabled,
latestTarget = _forceAlignPropsRef$c.target,
latestAlign = _forceAlignPropsRef$c.align,
latestOnAlign = _forceAlignPropsRef$c.onAlign;
var source = nodeRef.current;
if (!latestDisabled && latestTarget && source) {
var _result;
var _element = getElement(latestTarget);
var _point = getPoint(latestTarget);
cacheRef.current.element = _element;
cacheRef.current.point = _point;
cacheRef.current.align = latestAlign; // IE lose focus after element realign
// We should record activeElement and restore later
var _document = document,
activeElement = _document.activeElement; // We only align when element is visible
if (_element && isVisible(_element)) {
_result = alignElement(source, _element, latestAlign);
} else if (_point) {
_result = alignPoint(source, _point, latestAlign);
}
restoreFocus(activeElement, source);
if (latestOnAlign && _result) {
latestOnAlign(source, _result);
}
return true;
}
return false;
}, monitorBufferTime),
_useBuffer2 = _slicedToArray(_useBuffer, 2),
_forceAlign = _useBuffer2[0],
cancelForceAlign = _useBuffer2[1]; // ===================== Effect =====================
// Handle props change
var _React$useState = React__default.useState(),
_React$useState2 = _slicedToArray(_React$useState, 2),
element = _React$useState2[0],
setElement = _React$useState2[1];
var _React$useState3 = React__default.useState(),
_React$useState4 = _slicedToArray(_React$useState3, 2),
point = _React$useState4[0],
setPoint = _React$useState4[1];
useLayoutEffect(function () {
setElement(getElement(target));
setPoint(getPoint(target));
});
React__default.useEffect(function () {
if (cacheRef.current.element !== element || !isSamePoint(cacheRef.current.point, point) || !isEqual(cacheRef.current.align, align)) {
_forceAlign();
}
}); // Watch popup element resize
React__default.useEffect(function () {
var cancelFn = monitorResize(nodeRef.current, _forceAlign);
return cancelFn;
}, [nodeRef.current]); // Watch target element resize
React__default.useEffect(function () {
var cancelFn = monitorResize(element, _forceAlign);
return cancelFn;
}, [element]); // Listen for disabled change
React__default.useEffect(function () {
if (!disabled) {
_forceAlign();
} else {
cancelForceAlign();
}
}, [disabled]); // Listen for window resize
React__default.useEffect(function () {
if (monitorWindowResize) {
var cancelFn = addEventListenerWrap(window, 'resize', _forceAlign);
return cancelFn.remove;
}
}, [monitorWindowResize]); // Clear all if unmount
React__default.useEffect(function () {
return function () {
cancelForceAlign();
};
}, []); // ====================== Ref =======================
React__default.useImperativeHandle(ref, function () {
return {
forceAlign: function forceAlign() {
return _forceAlign(true);
}
};
}); // ===================== Render =====================
if ( /*#__PURE__*/React__default.isValidElement(childNode)) {
childNode = /*#__PURE__*/React__default.cloneElement(childNode, {
ref: composeRef(childNode.ref, nodeRef)
});
}
return childNode;
};
var RcAlign = /*#__PURE__*/React__default.forwardRef(Align);
RcAlign.displayName = 'Align';
/**
* Popup should follow the steps for each component work correctly:
* measure - check for the current stretch size
* align - let component align the position
* aligned - re-align again in case additional className changed the size
* afterAlign - choice next step is trigger motion or finished
* beforeMotion - should reset motion to invisible so that CSSMotion can do normal motion
* motion - play the motion
* stable - everything is done
*/
var StatusQueue = ['measure', 'alignPre', 'align', null, 'motion'];
var useVisibleStatus = (function (visible, doMeasure) {
var _useState = useSafeState(null),
_useState2 = _slicedToArray(_useState, 2),
status = _useState2[0],
setInternalStatus = _useState2[1];
var rafRef = useRef();
function setStatus(nextStatus) {
setInternalStatus(nextStatus, true);
}
function cancelRaf() {
wrapperRaf$1.cancel(rafRef.current);
}
function goNextStatus(callback) {
cancelRaf();
rafRef.current = wrapperRaf$1(function () {
// Only align should be manually trigger
setStatus(function (prev) {
switch (status) {
case 'align':
return 'motion';
case 'motion':
return 'stable';
}
return prev;
});
callback === null || callback === void 0 ? void 0 : callback();
});
} // Init status
useEffect(function () {
setStatus('measure');
}, [visible]); // Go next status
useEffect(function () {
switch (status) {
case 'measure':
doMeasure();
break;
}
if (status) {
rafRef.current = wrapperRaf$1( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var index, nextStatus;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
index = StatusQueue.indexOf(status);
nextStatus = StatusQueue[index + 1];
if (nextStatus && index !== -1) {
setStatus(nextStatus);
}
case 3:
case "end":
return _context.stop();
}
}
}, _callee);
})));
}
}, [status]);
useEffect(function () {
return function () {
cancelRaf();
};
}, []);
return [status, goNextStatus];
});
var useStretchStyle = (function (stretch) {
var _React$useState = React.useState({
width: 0,
height: 0
}),
_React$useState2 = _slicedToArray(_React$useState, 2),
targetSize = _React$useState2[0],
setTargetSize = _React$useState2[1];
function measureStretch(element) {
var tgtWidth = element.offsetWidth,
tgtHeight = element.offsetHeight;
var _element$getBoundingC = element.getBoundingClientRect(),
width = _element$getBoundingC.width,
height = _element$getBoundingC.height; // Rect is more accurate than offset, use if near
if (Math.abs(tgtWidth - width) < 1 && Math.abs(tgtHeight - height) < 1) {
tgtWidth = width;
tgtHeight = height;
}
setTargetSize({
width: tgtWidth,
height: tgtHeight
});
} // Merge stretch style
var style = React.useMemo(function () {
var sizeStyle = {};
if (stretch) {
var width = targetSize.width,
height = targetSize.height; // Stretch with target
if (stretch.indexOf('height') !== -1 && height) {
sizeStyle.height = height;
} else if (stretch.indexOf('minHeight') !== -1 && height) {
sizeStyle.minHeight = height;
}
if (stretch.indexOf('width') !== -1 && width) {
sizeStyle.width = width;
} else if (stretch.indexOf('minWidth') !== -1 && width) {
sizeStyle.minWidth = width;
}
}
return sizeStyle;
}, [stretch, targetSize]);
return [style, measureStretch];
});
var PopupInner = /*#__PURE__*/React.forwardRef(function (props, ref) {
var visible = props.visible,
prefixCls = props.prefixCls,
className = props.className,
style = props.style,
children = props.children,
zIndex = props.zIndex,
stretch = props.stretch,
destroyPopupOnHide = props.destroyPopupOnHide,
forceRender = props.forceRender,
align = props.align,
point = props.point,
getRootDomNode = props.getRootDomNode,
getClassNameFromAlign = props.getClassNameFromAlign,
onAlign = props.onAlign,
onMouseEnter = props.onMouseEnter,
onMouseLeave = props.onMouseLeave,
onMouseDown = props.onMouseDown,
onTouchStart = props.onTouchStart,
onClick = props.onClick;
var alignRef = useRef();
var elementRef = useRef();
var _useState = useState(),
_useState2 = _slicedToArray(_useState, 2),
alignedClassName = _useState2[0],
setAlignedClassName = _useState2[1]; // ======================= Measure ========================
var _useStretchStyle = useStretchStyle(stretch),
_useStretchStyle2 = _slicedToArray(_useStretchStyle, 2),
stretchStyle = _useStretchStyle2[0],
measureStretchStyle = _useStretchStyle2[1];
function doMeasure() {
if (stretch) {
measureStretchStyle(getRootDomNode());
}
} // ======================== Status ========================
var _useVisibleStatus = useVisibleStatus(visible, doMeasure),
_useVisibleStatus2 = _slicedToArray(_useVisibleStatus, 2),
status = _useVisibleStatus2[0],
goNextStatus = _useVisibleStatus2[1]; // ======================== Aligns ========================
/**
* `alignedClassName` may modify `source` size,
* which means one time align may not move to the correct position at once.
*
* We will reset `alignTimes` for each status switch to `alignPre`
* and let `rc-align` to align for multiple times to ensure get final stable place.
* Currently we mark `alignTimes < 2` repeat align, it will increase if user report for align issue.
*
* Update:
* In React 18. `rc-align` effect of align may faster than ref called trigger `forceAlign`.
* We adjust this to `alignTimes < 2`.
* We need refactor `rc-align` to support mark of `forceAlign` call if this still happen.
*/
var _useState3 = useState(0),
_useState4 = _slicedToArray(_useState3, 2),
alignTimes = _useState4[0],
setAlignTimes = _useState4[1];
var prepareResolveRef = useRef();
useLayoutEffect(function () {
if (status === 'alignPre') {
setAlignTimes(0);
}
}, [status]); // `target` on `rc-align` can accept as a function to get the bind element or a point.
// ref: https://www.npmjs.com/package/rc-align
function getAlignTarget() {
if (point) {
return point;
}
return getRootDomNode;
}
function forceAlign() {
var _alignRef$current;
(_alignRef$current = alignRef.current) === null || _alignRef$current === void 0 ? void 0 : _alignRef$current.forceAlign();
}
function onInternalAlign(popupDomNode, matchAlign) {
var nextAlignedClassName = getClassNameFromAlign(matchAlign);
if (alignedClassName !== nextAlignedClassName) {
setAlignedClassName(nextAlignedClassName);
} // We will retry multi times to make sure that the element has been align in the right position.
setAlignTimes(function (val) {
return val + 1;
});
if (status === 'align') {
onAlign === null || onAlign === void 0 ? void 0 : onAlign(popupDomNode, matchAlign);
}
} // Delay to go to next status
useLayoutEffect(function () {
if (status === 'align') {
// Repeat until not more align needed
if (alignTimes < 3) {
forceAlign();
} else {
goNextStatus(function () {
var _prepareResolveRef$cu;
(_prepareResolveRef$cu = prepareResolveRef.current) === null || _prepareResolveRef$cu === void 0 ? void 0 : _prepareResolveRef$cu.call(prepareResolveRef);
});
}
}
}, [alignTimes]); // ======================== Motion ========================
var motion = _objectSpread2$1({}, getMotion$1(props));
['onAppearEnd', 'onEnterEnd', 'onLeaveEnd'].forEach(function (eventName) {
var originHandler = motion[eventName];
motion[eventName] = function (element, event) {
goNextStatus();
return originHandler === null || originHandler === void 0 ? void 0 : originHandler(element, event);
};
});
function onShowPrepare() {
return new Promise(function (resolve) {
prepareResolveRef.current = resolve;
});
} // Go to stable directly when motion not provided
React.useEffect(function () {
if (!motion.motionName && status === 'motion') {
goNextStatus();
}
}, [motion.motionName, status]); // ========================= Refs =========================
React.useImperativeHandle(ref, function () {
return {
forceAlign: forceAlign,
getElement: function getElement() {
return elementRef.current;
}
};
}); // ======================== Render ========================
var mergedStyle = _objectSpread2$1(_objectSpread2$1({}, stretchStyle), {}, {
zIndex: zIndex,
opacity: status === 'motion' || status === 'stable' || !visible ? undefined : 0,
// Cannot interact with disappearing elements
// https://github.com/ant-design/ant-design/issues/35051#issuecomment-1101340714
pointerEvents: !visible && status !== 'stable' ? 'none' : undefined
}, style); // Align status
var alignDisabled = true;
if (align !== null && align !== void 0 && align.points && (status === 'align' || status === 'stable')) {
alignDisabled = false;
}
var childNode = children; // Wrapper when multiple children
if (React.Children.count(children) > 1) {
childNode = /*#__PURE__*/React.createElement("div", {
className: "".concat(prefixCls, "-content")
}, children);
}
return /*#__PURE__*/React.createElement(CSSMotion, _extends$1({
visible: visible,
ref: elementRef,
leavedClassName: "".concat(prefixCls, "-hidden")
}, motion, {
onAppearPrepare: onShowPrepare,
onEnterPrepare: onShowPrepare,
removeOnLeave: destroyPopupOnHide,
forceRender: forceRender
}), function (_ref, motionRef) {
var motionClassName = _ref.className,
motionStyle = _ref.style;
var mergedClassName = classNames(prefixCls, className, alignedClassName, motionClassName);
return /*#__PURE__*/React.createElement(RcAlign, {
target: getAlignTarget(),
key: "popup",
ref: alignRef,
monitorWindowResize: true,
disabled: alignDisabled,
align: align,
onAlign: onInternalAlign
}, /*#__PURE__*/React.createElement("div", {
ref: motionRef,
className: mergedClassName,
onMouseEnter: onMouseEnter,
onMouseLeave: onMouseLeave,
onMouseDownCapture: onMouseDown,
onTouchStartCapture: onTouchStart,
onClick: onClick,
style: _objectSpread2$1(_objectSpread2$1({}, motionStyle), mergedStyle)
}, childNode));
});
});
PopupInner.displayName = 'PopupInner';
var MobilePopupInner = /*#__PURE__*/React.forwardRef(function (props, ref) {
var prefixCls = props.prefixCls,
visible = props.visible,
zIndex = props.zIndex,
children = props.children,
_props$mobile = props.mobile;
_props$mobile = _props$mobile === void 0 ? {} : _props$mobile;
var popupClassName = _props$mobile.popupClassName,
popupStyle = _props$mobile.popupStyle,
_props$mobile$popupMo = _props$mobile.popupMotion,
popupMotion = _props$mobile$popupMo === void 0 ? {} : _props$mobile$popupMo,
popupRender = _props$mobile.popupRender,
onClick = props.onClick;
var elementRef = React.useRef(); // ========================= Refs =========================
React.useImperativeHandle(ref, function () {
return {
forceAlign: function forceAlign() {},
getElement: function getElement() {
return elementRef.current;
}
};
}); // ======================== Render ========================
var mergedStyle = _objectSpread2$1({
zIndex: zIndex
}, popupStyle);
var childNode = children; // Wrapper when multiple children
if (React.Children.count(children) > 1) {
childNode = /*#__PURE__*/React.createElement("div", {
className: "".concat(prefixCls, "-content")
}, children);
} // Mobile support additional render
if (popupRender) {
childNode = popupRender(childNode);
}
return /*#__PURE__*/React.createElement(CSSMotion, _extends$1({
visible: visible,
ref: elementRef,
removeOnLeave: true
}, popupMotion), function (_ref, motionRef) {
var motionClassName = _ref.className,
motionStyle = _ref.style;
var mergedClassName = classNames(prefixCls, popupClassName, motionClassName);
return /*#__PURE__*/React.createElement("div", {
ref: motionRef,
className: mergedClassName,
onClick: onClick,
style: _objectSpread2$1(_objectSpread2$1({}, motionStyle), mergedStyle)
}, childNode);
});
});
MobilePopupInner.displayName = 'MobilePopupInner';
var _excluded$9 = ["visible", "mobile"];
var Popup$1 = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
var visible = _ref.visible,
mobile = _ref.mobile,
props = _objectWithoutProperties(_ref, _excluded$9);
var _useState = useState(visible),
_useState2 = _slicedToArray(_useState, 2),
innerVisible = _useState2[0],
serInnerVisible = _useState2[1];
var _useState3 = useState(false),
_useState4 = _slicedToArray(_useState3, 2),
inMobile = _useState4[0],
setInMobile = _useState4[1];
var cloneProps = _objectSpread2$1(_objectSpread2$1({}, props), {}, {
visible: innerVisible
}); // We check mobile in visible changed here.
// And this also delay set `innerVisible` to avoid popup component render flash
useEffect(function () {
serInnerVisible(visible);
if (visible && mobile) {
setInMobile(isMobile());
}
}, [visible, mobile]);
var popupNode = inMobile ? /*#__PURE__*/React.createElement(MobilePopupInner, _extends$1({}, cloneProps, {
mobile: mobile,
ref: ref
})) : /*#__PURE__*/React.createElement(PopupInner, _extends$1({}, cloneProps, {
ref: ref
})); // We can use fragment directly but this may failed some selector usage. Keep as origin logic
return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Mask, cloneProps), popupNode);
});
Popup$1.displayName = 'Popup';
var TriggerContext = /*#__PURE__*/React.createContext(null);
function noop() {}
function returnEmptyString() {
return '';
}
function returnDocument(element) {
if (element) {
return element.ownerDocument;
}
return window.document;
}
var ALL_HANDLERS = ['onClick', 'onMouseDown', 'onTouchStart', 'onMouseEnter', 'onMouseLeave', 'onFocus', 'onBlur', 'onContextMenu'];
/**
* Internal usage. Do not use in your code since this will be removed.
*/
function generateTrigger(PortalComponent) {
var Trigger = /*#__PURE__*/function (_React$Component) {
_inherits(Trigger, _React$Component);
var _super = _createSuper(Trigger);
// ensure `getContainer` will be called only once
function Trigger(props) {
var _this;
_classCallCheck(this, Trigger);
_this = _super.call(this, props);
_defineProperty$1(_assertThisInitialized(_this), "popupRef", /*#__PURE__*/React.createRef());
_defineProperty$1(_assertThisInitialized(_this), "triggerRef", /*#__PURE__*/React.createRef());
_defineProperty$1(_assertThisInitialized(_this), "portalContainer", void 0);
_defineProperty$1(_assertThisInitialized(_this), "attachId", void 0);
_defineProperty$1(_assertThisInitialized(_this), "clickOutsideHandler", void 0);
_defineProperty$1(_assertThisInitialized(_this), "touchOutsideHandler", void 0);
_defineProperty$1(_assertThisInitialized(_this), "contextMenuOutsideHandler1", void 0);
_defineProperty$1(_assertThisInitialized(_this), "contextMenuOutsideHandler2", void 0);
_defineProperty$1(_assertThisInitialized(_this), "mouseDownTimeout", void 0);
_defineProperty$1(_assertThisInitialized(_this), "focusTime", void 0);
_defineProperty$1(_assertThisInitialized(_this), "preClickTime", void 0);
_defineProperty$1(_assertThisInitialized(_this), "preTouchTime", void 0);
_defineProperty$1(_assertThisInitialized(_this), "delayTimer", void 0);
_defineProperty$1(_assertThisInitialized(_this), "hasPopupMouseDown", void 0);
_defineProperty$1(_assertThisInitialized(_this), "onMouseEnter", function (e) {
var mouseEnterDelay = _this.props.mouseEnterDelay;
_this.fireEvents('onMouseEnter', e);
_this.delaySetPopupVisible(true, mouseEnterDelay, mouseEnterDelay ? null : e);
});
_defineProperty$1(_assertThisInitialized(_this), "onMouseMove", function (e) {
_this.fireEvents('onMouseMove', e);
_this.setPoint(e);
});
_defineProperty$1(_assertThisInitialized(_this), "onMouseLeave", function (e) {
_this.fireEvents('onMouseLeave', e);
_this.delaySetPopupVisible(false, _this.props.mouseLeaveDelay);
});
_defineProperty$1(_assertThisInitialized(_this), "onPopupMouseEnter", function () {
_this.clearDelayTimer();
});
_defineProperty$1(_assertThisInitialized(_this), "onPopupMouseLeave", function (e) {
var _this$popupRef$curren;
// https://github.com/react-component/trigger/pull/13
// react bug?
if (e.relatedTarget && !e.relatedTarget.setTimeout && contains((_this$popupRef$curren = _this.popupRef.current) === null || _this$popupRef$curren === void 0 ? void 0 : _this$popupRef$curren.getElement(), e.relatedTarget)) {
return;
}
_this.delaySetPopupVisible(false, _this.props.mouseLeaveDelay);
});
_defineProperty$1(_assertThisInitialized(_this), "onFocus", function (e) {
_this.fireEvents('onFocus', e); // incase focusin and focusout
_this.clearDelayTimer();
if (_this.isFocusToShow()) {
_this.focusTime = Date.now();
_this.delaySetPopupVisible(true, _this.props.focusDelay);
}
});
_defineProperty$1(_assertThisInitialized(_this), "onMouseDown", function (e) {
_this.fireEvents('onMouseDown', e);
_this.preClickTime = Date.now();
});
_defineProperty$1(_assertThisInitialized(_this), "onTouchStart", function (e) {
_this.fireEvents('onTouchStart', e);
_this.preTouchTime = Date.now();
});
_defineProperty$1(_assertThisInitialized(_this), "onBlur", function (e) {
_this.fireEvents('onBlur', e);
_this.clearDelayTimer();
if (_this.isBlurToHide()) {
_this.delaySetPopupVisible(false, _this.props.blurDelay);
}
});
_defineProperty$1(_assertThisInitialized(_this), "onContextMenu", function (e) {
e.preventDefault();
_this.fireEvents('onContextMenu', e);
_this.setPopupVisible(true, e);
});
_defineProperty$1(_assertThisInitialized(_this), "onContextMenuClose", function () {
if (_this.isContextMenuToShow()) {
_this.close();
}
});
_defineProperty$1(_assertThisInitialized(_this), "onClick", function (event) {
_this.fireEvents('onClick', event); // focus will trigger click
if (_this.focusTime) {
var preTime;
if (_this.preClickTime && _this.preTouchTime) {
preTime = Math.min(_this.preClickTime, _this.preTouchTime);
} else if (_this.preClickTime) {
preTime = _this.preClickTime;
} else if (_this.preTouchTime) {
preTime = _this.preTouchTime;
}
if (Math.abs(preTime - _this.focusTime) < 20) {
return;
}
_this.focusTime = 0;
}
_this.preClickTime = 0;
_this.preTouchTime = 0; // Only prevent default when all the action is click.
// https://github.com/ant-design/ant-design/issues/17043
// https://github.com/ant-design/ant-design/issues/17291
if (_this.isClickToShow() && (_this.isClickToHide() || _this.isBlurToHide()) && event && event.preventDefault) {
event.preventDefault();
}
var nextVisible = !_this.state.popupVisible;
if (_this.isClickToHide() && !nextVisible || nextVisible && _this.isClickToShow()) {
_this.setPopupVisible(!_this.state.popupVisible, event);
}
});
_defineProperty$1(_assertThisInitialized(_this), "onPopupMouseDown", function () {
_this.hasPopupMouseDown = true;
clearTimeout(_this.mouseDownTimeout);
_this.mouseDownTimeout = window.setTimeout(function () {
_this.hasPopupMouseDown = false;
}, 0);
if (_this.context) {
var _this$context;
(_this$context = _this.context).onPopupMouseDown.apply(_this$context, arguments);
}
});
_defineProperty$1(_assertThisInitialized(_this), "onDocumentClick", function (event) {
if (_this.props.mask && !_this.props.maskClosable) {
return;
}
var target = event.target;
var root = _this.getRootDomNode();
var popupNode = _this.getPopupDomNode();
if (
// mousedown on the target should also close popup when action is contextMenu.
// https://github.com/ant-design/ant-design/issues/29853
(!contains(root, target) || _this.isContextMenuOnly()) && !contains(popupNode, target) && !_this.hasPopupMouseDown) {
_this.close();
}
});
_defineProperty$1(_assertThisInitialized(_this), "getRootDomNode", function () {
var getTriggerDOMNode = _this.props.getTriggerDOMNode;
if (getTriggerDOMNode) {
return getTriggerDOMNode(_this.triggerRef.current);
}
try {
var domNode = findDOMNode(_this.triggerRef.current);
if (domNode) {
return domNode;
}
} catch (err) {// Do nothing
}
return ReactDOM.findDOMNode(_assertThisInitialized(_this));
});
_defineProperty$1(_assertThisInitialized(_this), "getPopupClassNameFromAlign", function (align) {
var className = [];
var _this$props = _this.props,
popupPlacement = _this$props.popupPlacement,
builtinPlacements = _this$props.builtinPlacements,
prefixCls = _this$props.prefixCls,
alignPoint = _this$props.alignPoint,
getPopupClassNameFromAlign = _this$props.getPopupClassNameFromAlign;
if (popupPlacement && builtinPlacements) {
className.push(getAlignPopupClassName(builtinPlacements, prefixCls, align, alignPoint));
}
if (getPopupClassNameFromAlign) {
className.push(getPopupClassNameFromAlign(align));
}
return className.join(' ');
});
_defineProperty$1(_assertThisInitialized(_this), "getComponent", function () {
var _this$props2 = _this.props,
prefixCls = _this$props2.prefixCls,
destroyPopupOnHide = _this$props2.destroyPopupOnHide,
popupClassName = _this$props2.popupClassName,
onPopupAlign = _this$props2.onPopupAlign,
popupMotion = _this$props2.popupMotion,
popupAnimation = _this$props2.popupAnimation,
popupTransitionName = _this$props2.popupTransitionName,
popupStyle = _this$props2.popupStyle,
mask = _this$props2.mask,
maskAnimation = _this$props2.maskAnimation,
maskTransitionName = _this$props2.maskTransitionName,
maskMotion = _this$props2.maskMotion,
zIndex = _this$props2.zIndex,
popup = _this$props2.popup,
stretch = _this$props2.stretch,
alignPoint = _this$props2.alignPoint,
mobile = _this$props2.mobile,
forceRender = _this$props2.forceRender,
onPopupClick = _this$props2.onPopupClick;
var _this$state = _this.state,
popupVisible = _this$state.popupVisible,
point = _this$state.point;
var align = _this.getPopupAlign();
var mouseProps = {};
if (_this.isMouseEnterToShow()) {
mouseProps.onMouseEnter = _this.onPopupMouseEnter;
}
if (_this.isMouseLeaveToHide()) {
mouseProps.onMouseLeave = _this.onPopupMouseLeave;
}
mouseProps.onMouseDown = _this.onPopupMouseDown;
mouseProps.onTouchStart = _this.onPopupMouseDown;
return /*#__PURE__*/React.createElement(Popup$1, _extends$1({
prefixCls: prefixCls,
destroyPopupOnHide: destroyPopupOnHide,
visible: popupVisible,
point: alignPoint && point,
className: popupClassName,
align: align,
onAlign: onPopupAlign,
animation: popupAnimation,
getClassNameFromAlign: _this.getPopupClassNameFromAlign
}, mouseProps, {
stretch: stretch,
getRootDomNode: _this.getRootDomNode,
style: popupStyle,
mask: mask,
zIndex: zIndex,
transitionName: popupTransitionName,
maskAnimation: maskAnimation,
maskTransitionName: maskTransitionName,
maskMotion: maskMotion,
ref: _this.popupRef,
motion: popupMotion,
mobile: mobile,
forceRender: forceRender,
onClick: onPopupClick
}), typeof popup === 'function' ? popup() : popup);
});
_defineProperty$1(_assertThisInitialized(_this), "attachParent", function (popupContainer) {
wrapperRaf$1.cancel(_this.attachId);
var _this$props3 = _this.props,
getPopupContainer = _this$props3.getPopupContainer,
getDocument = _this$props3.getDocument;
var domNode = _this.getRootDomNode();
var mountNode;
if (!getPopupContainer) {
mountNode = getDocument(_this.getRootDomNode()).body;
} else if (domNode || getPopupContainer.length === 0) {
// Compatible for legacy getPopupContainer with domNode argument.
// If no need `domNode` argument, will call directly.
// https://codesandbox.io/s/eloquent-mclean-ss93m?file=/src/App.js
mountNode = getPopupContainer(domNode);
}
if (mountNode) {
mountNode.appendChild(popupContainer);
} else {
// Retry after frame render in case parent not ready
_this.attachId = wrapperRaf$1(function () {
_this.attachParent(popupContainer);
});
}
});
_defineProperty$1(_assertThisInitialized(_this), "getContainer", function () {
if (!_this.portalContainer) {
// In React.StrictMode component will call render multiple time in first mount.
// When you want to refactor with FC, useRef will also init multiple time and
// point to different useRef instance which will create multiple element
// (This multiple render will not trigger effect so you can not clean up this
// in effect). But this is safe with class component since it always point to same class instance.
var getDocument = _this.props.getDocument;
var popupContainer = getDocument(_this.getRootDomNode()).createElement('div'); // Make sure default popup container will never cause scrollbar appearing
// https://github.com/react-component/trigger/issues/41
popupContainer.style.position = 'absolute';
popupContainer.style.top = '0';
popupContainer.style.left = '0';
popupContainer.style.width = '100%';
_this.portalContainer = popupContainer;
}
_this.attachParent(_this.portalContainer);
return _this.portalContainer;
});
_defineProperty$1(_assertThisInitialized(_this), "setPoint", function (point) {
var alignPoint = _this.props.alignPoint;
if (!alignPoint || !point) return;
_this.setState({
point: {
pageX: point.pageX,
pageY: point.pageY
}
});
});
_defineProperty$1(_assertThisInitialized(_this), "handlePortalUpdate", function () {
if (_this.state.prevPopupVisible !== _this.state.popupVisible) {
_this.props.afterPopupVisibleChange(_this.state.popupVisible);
}
});
_defineProperty$1(_assertThisInitialized(_this), "triggerContextValue", {
onPopupMouseDown: _this.onPopupMouseDown
});
var _popupVisible;
if ('popupVisible' in props) {
_popupVisible = !!props.popupVisible;
} else {
_popupVisible = !!props.defaultPopupVisible;
}
_this.state = {
prevPopupVisible: _popupVisible,
popupVisible: _popupVisible
};
ALL_HANDLERS.forEach(function (h) {
_this["fire".concat(h)] = function (e) {
_this.fireEvents(h, e);
};
});
return _this;
}
_createClass(Trigger, [{
key: "componentDidMount",
value: function componentDidMount() {
this.componentDidUpdate();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
var props = this.props;
var state = this.state; // We must listen to `mousedown` or `touchstart`, edge case:
// https://github.com/ant-design/ant-design/issues/5804
// https://github.com/react-component/calendar/issues/250
// https://github.com/react-component/trigger/issues/50
if (state.popupVisible) {
var currentDocument;
if (!this.clickOutsideHandler && (this.isClickToHide() || this.isContextMenuToShow())) {
currentDocument = props.getDocument(this.getRootDomNode());
this.clickOutsideHandler = addEventListenerWrap(currentDocument, 'mousedown', this.onDocumentClick);
} // always hide on mobile
if (!this.touchOutsideHandler) {
currentDocument = currentDocument || props.getDocument(this.getRootDomNode());
this.touchOutsideHandler = addEventListenerWrap(currentDocument, 'touchstart', this.onDocumentClick);
} // close popup when trigger type contains 'onContextMenu' and document is scrolling.
if (!this.contextMenuOutsideHandler1 && this.isContextMenuToShow()) {
currentDocument = currentDocument || props.getDocument(this.getRootDomNode());
this.contextMenuOutsideHandler1 = addEventListenerWrap(currentDocument, 'scroll', this.onContextMenuClose);
} // close popup when trigger type contains 'onContextMenu' and window is blur.
if (!this.contextMenuOutsideHandler2 && this.isContextMenuToShow()) {
this.contextMenuOutsideHandler2 = addEventListenerWrap(window, 'blur', this.onContextMenuClose);
}
return;
}
this.clearOutsideHandler();
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.clearDelayTimer();
this.clearOutsideHandler();
clearTimeout(this.mouseDownTimeout);
wrapperRaf$1.cancel(this.attachId);
}
}, {
key: "getPopupDomNode",
value: function getPopupDomNode() {
var _this$popupRef$curren2;
// for test
return ((_this$popupRef$curren2 = this.popupRef.current) === null || _this$popupRef$curren2 === void 0 ? void 0 : _this$popupRef$curren2.getElement()) || null;
}
}, {
key: "getPopupAlign",
value: function getPopupAlign() {
var props = this.props;
var popupPlacement = props.popupPlacement,
popupAlign = props.popupAlign,
builtinPlacements = props.builtinPlacements;
if (popupPlacement && builtinPlacements) {
return getAlignFromPlacement(builtinPlacements, popupPlacement, popupAlign);
}
return popupAlign;
}
}, {
key: "setPopupVisible",
value:
/**
* @param popupVisible Show or not the popup element
* @param event SyntheticEvent, used for `pointAlign`
*/
function setPopupVisible(popupVisible, event) {
var alignPoint = this.props.alignPoint;
var prevPopupVisible = this.state.popupVisible;
this.clearDelayTimer();
if (prevPopupVisible !== popupVisible) {
if (!('popupVisible' in this.props)) {
this.setState({
popupVisible: popupVisible,
prevPopupVisible: prevPopupVisible
});
}
this.props.onPopupVisibleChange(popupVisible);
} // Always record the point position since mouseEnterDelay will delay the show
if (alignPoint && event && popupVisible) {
this.setPoint(event);
}
}
}, {
key: "delaySetPopupVisible",
value: function delaySetPopupVisible(visible, delayS, event) {
var _this2 = this;
var delay = delayS * 1000;
this.clearDelayTimer();
if (delay) {
var point = event ? {
pageX: event.pageX,
pageY: event.pageY
} : null;
this.delayTimer = window.setTimeout(function () {
_this2.setPopupVisible(visible, point);
_this2.clearDelayTimer();
}, delay);
} else {
this.setPopupVisible(visible, event);
}
}
}, {
key: "clearDelayTimer",
value: function clearDelayTimer() {
if (this.delayTimer) {
clearTimeout(this.delayTimer);
this.delayTimer = null;
}
}
}, {
key: "clearOutsideHandler",
value: function clearOutsideHandler() {
if (this.clickOutsideHandler) {
this.clickOutsideHandler.remove();
this.clickOutsideHandler = null;
}
if (this.contextMenuOutsideHandler1) {
this.contextMenuOutsideHandler1.remove();
this.contextMenuOutsideHandler1 = null;
}
if (this.contextMenuOutsideHandler2) {
this.contextMenuOutsideHandler2.remove();
this.contextMenuOutsideHandler2 = null;
}
if (this.touchOutsideHandler) {
this.touchOutsideHandler.remove();
this.touchOutsideHandler = null;
}
}
}, {
key: "createTwoChains",
value: function createTwoChains(event) {
var childPros = this.props.children.props;
var props = this.props;
if (childPros[event] && props[event]) {
return this["fire".concat(event)];
}
return childPros[event] || props[event];
}
}, {
key: "isClickToShow",
value: function isClickToShow() {
var _this$props4 = this.props,
action = _this$props4.action,
showAction = _this$props4.showAction;
return action.indexOf('click') !== -1 || showAction.indexOf('click') !== -1;
}
}, {
key: "isContextMenuOnly",
value: function isContextMenuOnly() {
var action = this.props.action;
return action === 'contextMenu' || action.length === 1 && action[0] === 'contextMenu';
}
}, {
key: "isContextMenuToShow",
value: function isContextMenuToShow() {
var _this$props5 = this.props,
action = _this$props5.action,
showAction = _this$props5.showAction;
return action.indexOf('contextMenu') !== -1 || showAction.indexOf('contextMenu') !== -1;
}
}, {
key: "isClickToHide",
value: function isClickToHide() {
var _this$props6 = this.props,
action = _this$props6.action,
hideAction = _this$props6.hideAction;
return action.indexOf('click') !== -1 || hideAction.indexOf('click') !== -1;
}
}, {
key: "isMouseEnterToShow",
value: function isMouseEnterToShow() {
var _this$props7 = this.props,
action = _this$props7.action,
showAction = _this$props7.showAction;
return action.indexOf('hover') !== -1 || showAction.indexOf('mouseEnter') !== -1;
}
}, {
key: "isMouseLeaveToHide",
value: function isMouseLeaveToHide() {
var _this$props8 = this.props,
action = _this$props8.action,
hideAction = _this$props8.hideAction;
return action.indexOf('hover') !== -1 || hideAction.indexOf('mouseLeave') !== -1;
}
}, {
key: "isFocusToShow",
value: function isFocusToShow() {
var _this$props9 = this.props,
action = _this$props9.action,
showAction = _this$props9.showAction;
return action.indexOf('focus') !== -1 || showAction.indexOf('focus') !== -1;
}
}, {
key: "isBlurToHide",
value: function isBlurToHide() {
var _this$props10 = this.props,
action = _this$props10.action,
hideAction = _this$props10.hideAction;
return action.indexOf('focus') !== -1 || hideAction.indexOf('blur') !== -1;
}
}, {
key: "forcePopupAlign",
value: function forcePopupAlign() {
if (this.state.popupVisible) {
var _this$popupRef$curren3;
(_this$popupRef$curren3 = this.popupRef.current) === null || _this$popupRef$curren3 === void 0 ? void 0 : _this$popupRef$curren3.forceAlign();
}
}
}, {
key: "fireEvents",
value: function fireEvents(type, e) {
var childCallback = this.props.children.props[type];
if (childCallback) {
childCallback(e);
}
var callback = this.props[type];
if (callback) {
callback(e);
}
}
}, {
key: "close",
value: function close() {
this.setPopupVisible(false);
}
}, {
key: "render",
value: function render() {
var popupVisible = this.state.popupVisible;
var _this$props11 = this.props,
children = _this$props11.children,
forceRender = _this$props11.forceRender,
alignPoint = _this$props11.alignPoint,
className = _this$props11.className,
autoDestroy = _this$props11.autoDestroy;
var child = React.Children.only(children);
var newChildProps = {
key: 'trigger'
}; // ============================== Visible Handlers ==============================
// >>> ContextMenu
if (this.isContextMenuToShow()) {
newChildProps.onContextMenu = this.onContextMenu;
} else {
newChildProps.onContextMenu = this.createTwoChains('onContextMenu');
} // >>> Click
if (this.isClickToHide() || this.isClickToShow()) {
newChildProps.onClick = this.onClick;
newChildProps.onMouseDown = this.onMouseDown;
newChildProps.onTouchStart = this.onTouchStart;
} else {
newChildProps.onClick = this.createTwoChains('onClick');
newChildProps.onMouseDown = this.createTwoChains('onMouseDown');
newChildProps.onTouchStart = this.createTwoChains('onTouchStart');
} // >>> Hover(enter)
if (this.isMouseEnterToShow()) {
newChildProps.onMouseEnter = this.onMouseEnter; // Point align
if (alignPoint) {
newChildProps.onMouseMove = this.onMouseMove;
}
} else {
newChildProps.onMouseEnter = this.createTwoChains('onMouseEnter');
} // >>> Hover(leave)
if (this.isMouseLeaveToHide()) {
newChildProps.onMouseLeave = this.onMouseLeave;
} else {
newChildProps.onMouseLeave = this.createTwoChains('onMouseLeave');
} // >>> Focus
if (this.isFocusToShow() || this.isBlurToHide()) {
newChildProps.onFocus = this.onFocus;
newChildProps.onBlur = this.onBlur;
} else {
newChildProps.onFocus = this.createTwoChains('onFocus');
newChildProps.onBlur = this.createTwoChains('onBlur');
} // =================================== Render ===================================
var childrenClassName = classNames(child && child.props && child.props.className, className);
if (childrenClassName) {
newChildProps.className = childrenClassName;
}
var cloneProps = _objectSpread2$1({}, newChildProps);
if (supportRef(child)) {
cloneProps.ref = composeRef(this.triggerRef, child.ref);
}
var trigger = /*#__PURE__*/React.cloneElement(child, cloneProps);
var portal; // prevent unmounting after it's rendered
if (popupVisible || this.popupRef.current || forceRender) {
portal = /*#__PURE__*/React.createElement(PortalComponent, {
key: "portal",
getContainer: this.getContainer,
didUpdate: this.handlePortalUpdate
}, this.getComponent());
}
if (!popupVisible && autoDestroy) {
portal = null;
}
return /*#__PURE__*/React.createElement(TriggerContext.Provider, {
value: this.triggerContextValue
}, trigger, portal);
}
}], [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(_ref, prevState) {
var popupVisible = _ref.popupVisible;
var newState = {};
if (popupVisible !== undefined && prevState.popupVisible !== popupVisible) {
newState.popupVisible = popupVisible;
newState.prevPopupVisible = prevState.popupVisible;
}
return newState;
}
}]);
return Trigger;
}(React.Component);
_defineProperty$1(Trigger, "contextType", TriggerContext);
_defineProperty$1(Trigger, "defaultProps", {
prefixCls: 'rc-trigger-popup',
getPopupClassNameFromAlign: returnEmptyString,
getDocument: returnDocument,
onPopupVisibleChange: noop,
afterPopupVisibleChange: noop,
onPopupAlign: noop,
popupClassName: '',
mouseEnterDelay: 0,
mouseLeaveDelay: 0.1,
focusDelay: 0,
blurDelay: 0.15,
popupStyle: {},
destroyPopupOnHide: false,
popupAlign: {},
defaultPopupVisible: false,
mask: false,
maskClosable: true,
action: [],
showAction: [],
hideAction: [],
autoDestroy: false
});
return Trigger;
}
var Trigger = generateTrigger(Portal);
// https://stackoverflow.com/questions/46176165/ways-to-get-string-literal-type-of-array-values-without-enum-overhead
var tuple = function tuple() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return args;
};
// ================== Collapse Motion ==================
var getCollapsedHeight = function getCollapsedHeight() {
return {
height: 0,
opacity: 0
};
};
var getRealHeight = function getRealHeight(node) {
var scrollHeight = node.scrollHeight;
return {
height: scrollHeight,
opacity: 1
};
};
var getCurrentHeight = function getCurrentHeight(node) {
return {
height: node ? node.offsetHeight : 0
};
};
var skipOpacityTransition = function skipOpacityTransition(_, event) {
return (event === null || event === void 0 ? void 0 : event.deadline) === true || event.propertyName === 'height';
};
var initCollapseMotion = function initCollapseMotion() {
var rootCls = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'ant';
return {
motionName: rootCls + "-motion-collapse",
onAppearStart: getCollapsedHeight,
onEnterStart: getCollapsedHeight,
onAppearActive: getRealHeight,
onEnterActive: getRealHeight,
onLeaveStart: getCurrentHeight,
onLeaveActive: getCollapsedHeight,
onAppearEnd: skipOpacityTransition,
onEnterEnd: skipOpacityTransition,
onLeaveEnd: skipOpacityTransition,
motionDeadline: 500
};
};
tuple('bottomLeft', 'bottomRight', 'topLeft', 'topRight');
var getTransitionName = function getTransitionName(rootPrefixCls, motion, transitionName) {
if (transitionName !== undefined) {
return transitionName;
}
return rootPrefixCls + "-" + motion;
};
var LoadingOutlined = function LoadingOutlined(props, ref) {
return /*#__PURE__*/React.createElement(AntdIcon, _objectSpread2$1(_objectSpread2$1({}, props), {}, {
ref: ref,
icon: LoadingOutlinedSvg
}));
};
LoadingOutlined.displayName = 'LoadingOutlined';
var LoadingOutlined$1 = /*#__PURE__*/React.forwardRef(LoadingOutlined);
var initMotionCommon = function initMotionCommon(duration) {
return {
animationDuration: duration,
animationFillMode: 'both'
};
};
// FIXME: origin less code seems same as initMotionCommon. Maybe we can safe remove
var initMotionCommonLeave = function initMotionCommonLeave(duration) {
return {
animationDuration: duration,
animationFillMode: 'both'
};
};
var initMotion = function initMotion(motionCls, inKeyframes, outKeyframes, duration) {
var _ref;
var sameLevel = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
var sameLevelPrefix = sameLevel ? '&' : '';
return _ref = {}, _defineProperty$1(_ref, "\n " + sameLevelPrefix + motionCls + "-enter,\n " + sameLevelPrefix + motionCls + "-appear\n ", _extends$1(_extends$1({}, initMotionCommon(duration)), {
animationPlayState: 'paused'
})), _defineProperty$1(_ref, "" + sameLevelPrefix + motionCls + "-leave", _extends$1(_extends$1({}, initMotionCommonLeave(duration)), {
animationPlayState: 'paused'
})), _defineProperty$1(_ref, "\n " + sameLevelPrefix + motionCls + "-enter" + motionCls + "-enter-active,\n " + sameLevelPrefix + motionCls + "-appear" + motionCls + "-appear-active\n ", {
animationName: inKeyframes,
animationPlayState: 'running'
}), _defineProperty$1(_ref, "" + sameLevelPrefix + motionCls + "-leave" + motionCls + "-leave-active", {
animationName: outKeyframes,
animationPlayState: 'running',
pointerEvents: 'none'
}), _ref;
};
var moveDownIn = new Keyframe('antMoveDownIn', {
'0%': {
transform: 'translate3d(0, 100%, 0)',
transformOrigin: '0 0',
opacity: 0
},
'100%': {
transform: 'translate3d(0, 0, 0)',
transformOrigin: '0 0',
opacity: 1
}
});
var moveDownOut = new Keyframe('antMoveDownOut', {
'0%': {
transform: 'translate3d(0, 0, 0)',
transformOrigin: '0 0',
opacity: 1
},
'100%': {
transform: 'translate3d(0, 100%, 0)',
transformOrigin: '0 0',
opacity: 0
}
});
var moveLeftIn = new Keyframe('antMoveLeftIn', {
'0%': {
transform: 'translate3d(-100%, 0, 0)',
transformOrigin: '0 0',
opacity: 0
},
'100%': {
transform: 'translate3d(0, 0, 0)',
transformOrigin: '0 0',
opacity: 1
}
});
var moveLeftOut = new Keyframe('antMoveLeftOut', {
'0%': {
transform: 'translate3d(0, 0, 0)',
transformOrigin: '0 0',
opacity: 1
},
'100%': {
transform: 'translate3d(-100%, 0, 0)',
transformOrigin: '0 0',
opacity: 0
}
});
var moveRightIn = new Keyframe('antMoveRightIn', {
'0%': {
transform: 'translate3d(100%, 0, 0)',
transformOrigin: '0 0',
opacity: 0
},
'100%': {
transform: 'translate3d(0, 0, 0)',
transformOrigin: '0 0',
opacity: 1
}
});
var moveRightOut = new Keyframe('antMoveRightOut', {
'0%': {
transform: 'translate3d(0, 0, 0)',
transformOrigin: '0 0',
opacity: 1
},
'100%': {
transform: 'translate3d(100%, 0, 0)',
transformOrigin: '0 0',
opacity: 0
}
});
var moveUpIn = new Keyframe('antMoveUpIn', {
'0%': {
transform: 'translate3d(0, -100%, 0)',
transformOrigin: '0 0',
opacity: 0
},
'100%': {
transform: 'translate3d(0, 0, 0)',
transformOrigin: '0 0',
opacity: 1
}
});
var moveUpOut = new Keyframe('antMoveUpOut', {
'0%': {
transform: 'translate3d(0, 0, 0)',
transformOrigin: '0 0',
opacity: 1
},
'100%': {
transform: 'translate3d(0, -100%, 0)',
transformOrigin: '0 0',
opacity: 0
}
});
var moveMotion = {
'move-up': {
inKeyframes: moveUpIn,
outKeyframes: moveUpOut
},
'move-down': {
inKeyframes: moveDownIn,
outKeyframes: moveDownOut
},
'move-left': {
inKeyframes: moveLeftIn,
outKeyframes: moveLeftOut
},
'move-right': {
inKeyframes: moveRightIn,
outKeyframes: moveRightOut
}
};
var initMoveMotion = function initMoveMotion(token, motionName) {
var _ref;
var antCls = token.antCls;
var motionCls = antCls + "-" + motionName;
var _moveMotion$motionNam = moveMotion[motionName],
inKeyframes = _moveMotion$motionNam.inKeyframes,
outKeyframes = _moveMotion$motionNam.outKeyframes;
return [initMotion(motionCls, inKeyframes, outKeyframes, token.motionDurationMid), (_ref = {}, _defineProperty$1(_ref, "\n " + motionCls + "-enter,\n " + motionCls + "-appear\n ", {
opacity: 0,
animationTimingFunction: token.motionEaseOutCirc
}), _defineProperty$1(_ref, motionCls + "-leave", {
animationTimingFunction: token.motionEaseInOutCirc
}), _ref)];
};
var slideUpIn = new Keyframe('antSlideUpIn', {
'0%': {
transform: 'scaleY(0.8)',
transformOrigin: '0% 0%',
opacity: 0
},
'100%': {
transform: 'scaleY(1)',
transformOrigin: '0% 0%',
opacity: 1
}
});
var slideUpOut = new Keyframe('antSlideUpOut', {
'0%': {
transform: 'scaleY(1)',
transformOrigin: '0% 0%',
opacity: 1
},
'100%': {
transform: 'scaleY(0.8)',
transformOrigin: '0% 0%',
opacity: 0
}
});
var slideDownIn = new Keyframe('antSlideDownIn', {
'0%': {
transform: 'scaleY(0.8)',
transformOrigin: '100% 100%',
opacity: 0
},
'100%': {
transform: 'scaleY(1)',
transformOrigin: '100% 100%',
opacity: 1
}
});
var slideDownOut = new Keyframe('antSlideDownOut', {
'0%': {
transform: 'scaleY(1)',
transformOrigin: '100% 100%',
opacity: 1
},
'100%': {
transform: 'scaleY(0.8)',
transformOrigin: '100% 100%',
opacity: 0
}
});
var slideLeftIn = new Keyframe('antSlideLeftIn', {
'0%': {
transform: 'scaleX(0.8)',
transformOrigin: '0% 0%',
opacity: 0
},
'100%': {
transform: 'scaleX(1)',
transformOrigin: '0% 0%',
opacity: 1
}
});
var slideLeftOut = new Keyframe('antSlideLeftOut', {
'0%': {
transform: 'scaleX(1)',
transformOrigin: '0% 0%',
opacity: 1
},
'100%': {
transform: 'scaleX(0.8)',
transformOrigin: '0% 0%',
opacity: 0
}
});
var slideRightIn = new Keyframe('antSlideRightIn', {
'0%': {
transform: 'scaleX(0.8)',
transformOrigin: '100% 0%',
opacity: 0
},
'100%': {
transform: 'scaleX(1)',
transformOrigin: '100% 0%',
opacity: 1
}
});
var slideRightOut = new Keyframe('antSlideRightOut', {
'0%': {
transform: 'scaleX(1)',
transformOrigin: '100% 0%',
opacity: 1
},
'100%': {
transform: 'scaleX(0.8)',
transformOrigin: '100% 0%',
opacity: 0
}
});
var slideMotion = {
'slide-up': {
inKeyframes: slideUpIn,
outKeyframes: slideUpOut
},
'slide-down': {
inKeyframes: slideDownIn,
outKeyframes: slideDownOut
},
'slide-left': {
inKeyframes: slideLeftIn,
outKeyframes: slideLeftOut
},
'slide-right': {
inKeyframes: slideRightIn,
outKeyframes: slideRightOut
}
};
var initSlideMotion = function initSlideMotion(token, motionName) {
var _ref;
var antCls = token.antCls;
var motionCls = antCls + "-" + motionName;
var _slideMotion$motionNa = slideMotion[motionName],
inKeyframes = _slideMotion$motionNa.inKeyframes,
outKeyframes = _slideMotion$motionNa.outKeyframes;
return [initMotion(motionCls, inKeyframes, outKeyframes, token.motionDurationMid), (_ref = {}, _defineProperty$1(_ref, "\n " + motionCls + "-enter,\n " + motionCls + "-appear\n ", {
opacity: 0,
animationTimingFunction: token.motionEaseOutQuint
}), _defineProperty$1(_ref, motionCls + "-leave", {
animationTimingFunction: token.motionEaseInQuint
}), _ref)];
};
var zoomIn = new Keyframe('antZoomIn', {
'0%': {
transform: 'scale(0.2)',
opacity: 0
},
'100%': {
transform: 'scale(1)',
opacity: 1
}
});
var zoomOut = new Keyframe('antZoomOut', {
'0%': {
transform: 'scale(1)'
},
'100%': {
transform: 'scale(0.2)',
opacity: 0
}
});
var zoomBigIn = new Keyframe('antZoomBigIn', {
'0%': {
transform: 'scale(0.8)',
opacity: 0
},
'100%': {
transform: 'scale(1)',
opacity: 1
}
});
var zoomBigOut = new Keyframe('antZoomBigOut', {
'0%': {
transform: 'scale(1)'
},
'100%': {
transform: 'scale(0.8)',
opacity: 0
}
});
var zoomUpIn = new Keyframe('antZoomUpIn', {
'0%': {
transform: 'scale(0.8)',
transformOrigin: '50% 0%',
opacity: 0
},
'100%': {
transform: 'scale(1)',
transformOrigin: '50% 0%'
}
});
var zoomUpOut = new Keyframe('antZoomUpOut', {
'0%': {
transform: 'scale(1)',
transformOrigin: '50% 0%'
},
'100%': {
transform: 'scale(0.8)',
transformOrigin: '50% 0%',
opacity: 0
}
});
var zoomLeftIn = new Keyframe('antZoomLeftIn', {
'0%': {
transform: 'scale(0.8)',
transformOrigin: '0% 50%',
opacity: 0
},
'100%': {
transform: 'scale(1)',
transformOrigin: '0% 50%'
}
});
var zoomLeftOut = new Keyframe('antZoomLeftOut', {
'0%': {
transform: 'scale(1)',
transformOrigin: '0% 50%'
},
'100%': {
transform: 'scale(0.8)',
transformOrigin: '0% 50%',
opacity: 0
}
});
var zoomRightIn = new Keyframe('antZoomRightIn', {
'0%': {
transform: 'scale(0.8)',
transformOrigin: '100% 50%',
opacity: 0
},
'100%': {
transform: 'scale(1)',
transformOrigin: '100% 50%'
}
});
var zoomRightOut = new Keyframe('antZoomRightOut', {
'0%': {
transform: 'scale(1)',
transformOrigin: '100% 50%'
},
'100%': {
transform: 'scale(0.8)',
transformOrigin: '100% 50%',
opacity: 0
}
});
var zoomDownIn = new Keyframe('antZoomDownIn', {
'0%': {
transform: 'scale(0.8)',
transformOrigin: '50% 100%',
opacity: 0
},
'100%': {
transform: 'scale(1)',
transformOrigin: '50% 100%'
}
});
var zoomDownOut = new Keyframe('antZoomDownOut', {
'0%': {
transform: 'scale(1)',
transformOrigin: '50% 100%'
},
'100%': {
transform: 'scale(0.8)',
transformOrigin: '50% 100%',
opacity: 0
}
});
var zoomMotion = {
zoom: {
inKeyframes: zoomIn,
outKeyframes: zoomOut
},
'zoom-big': {
inKeyframes: zoomBigIn,
outKeyframes: zoomBigOut
},
'zoom-big-fast': {
inKeyframes: zoomBigIn,
outKeyframes: zoomBigOut
},
'zoom-left': {
inKeyframes: zoomLeftIn,
outKeyframes: zoomLeftOut
},
'zoom-right': {
inKeyframes: zoomRightIn,
outKeyframes: zoomRightOut
},
'zoom-up': {
inKeyframes: zoomUpIn,
outKeyframes: zoomUpOut
},
'zoom-down': {
inKeyframes: zoomDownIn,
outKeyframes: zoomDownOut
}
};
var initZoomMotion = function initZoomMotion(token, motionName) {
var _ref;
var antCls = token.antCls;
var motionCls = antCls + "-" + motionName;
var _zoomMotion$motionNam = zoomMotion[motionName],
inKeyframes = _zoomMotion$motionNam.inKeyframes,
outKeyframes = _zoomMotion$motionNam.outKeyframes;
return [initMotion(motionCls, inKeyframes, outKeyframes, motionName === 'zoom-big-fast' ? token.motionDurationMid : token.motionDurationMid), (_ref = {}, _defineProperty$1(_ref, "\n " + motionCls + "-enter,\n " + motionCls + "-appear\n ", {
transform: 'scale(0)',
opacity: 0,
animationTimingFunction: token.motionEaseOutCirc,
'&-prepare': {
transform: 'none'
}
}), _defineProperty$1(_ref, motionCls + "-leave", {
animationTimingFunction: token.motionEaseInOutCirc
}), _ref)];
};
var genCollapseMotion = function genCollapseMotion(token) {
var _token$componentCls;
return _defineProperty$1({}, token.componentCls, (_token$componentCls = {}, _defineProperty$1(_token$componentCls, token.antCls + "-motion-collapse-legacy", {
overflow: 'hidden',
'&-active': {
transition: "height " + token.motionDurationMid + " " + token.motionEaseInOut + ",\n opacity " + token.motionDurationMid + " " + token.motionEaseInOut + " !important"
}
}), _defineProperty$1(_token$componentCls, token.antCls + "-motion-collapse", {
overflow: 'hidden',
transition: "height " + token.motionDurationMid + " " + token.motionEaseInOut + ",\n opacity " + token.motionDurationMid + " " + token.motionEaseInOut + " !important"
}), _token$componentCls));
};
var genCollapseMotion$1 = genCollapseMotion;
// handle border collapse
function compactItemBorder(token, options) {
var childCombinator = options.borderElCls ? '> *' : '';
var hoverEffects = ['hover', options.focus ? 'focus' : null, 'active'].filter(Boolean).map(function (n) {
return "&:" + n + " " + childCombinator;
}).join(',');
return {
'&-item:not(&-last-item)': {
marginInlineEnd: -token.lineWidth
},
'&-item': _extends$1(_extends$1(_defineProperty$1({}, hoverEffects, {
zIndex: 2
}), options.focusElCls ? _defineProperty$1({}, "&" + options.focusElCls, {
zIndex: 2
}) : {}), _defineProperty$1({}, "&[disabled] " + childCombinator, {
zIndex: 0
}))
};
}
// handle border-radius
function compactItemBorderRadius(prefixCls, options) {
var _ref2;
var childCombinator = options.borderElCls ? "> " + options.borderElCls : '';
return _ref2 = {}, _defineProperty$1(_ref2, "&-item:not(&-first-item):not(&-last-item) " + childCombinator, {
borderRadius: 0
}), _defineProperty$1(_ref2, '&-item:not(&-last-item)&-first-item', _defineProperty$1({}, "& " + childCombinator + ", &" + prefixCls + "-sm " + childCombinator + ", &" + prefixCls + "-lg " + childCombinator, {
borderStartEndRadius: 0,
borderEndEndRadius: 0
})), _defineProperty$1(_ref2, '&-item:not(&-first-item)&-last-item', _defineProperty$1({}, "& " + childCombinator + ", &" + prefixCls + "-sm " + childCombinator + ", &" + prefixCls + "-lg " + childCombinator, {
borderStartStartRadius: 0,
borderEndStartRadius: 0
})), _ref2;
}
function genCompactItemStyle(token, prefixCls) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
focus: true
};
return {
'&-compact': _extends$1(_extends$1({}, compactItemBorder(token, options)), compactItemBorderRadius(prefixCls, options))
};
}
/* istanbul ignore next */
function genPurePanel(Component, defaultPrefixCls, getDropdownCls) {
return function PurePanel(props) {
var customizePrefixCls = props.prefixCls,
style = props.style;
var holderRef = React.useRef(null);
var _React$useState = React.useState(0),
_React$useState2 = _slicedToArray(_React$useState, 2),
popupHeight = _React$useState2[0],
setPopupHeight = _React$useState2[1];
var _React$useState3 = React.useState(0),
_React$useState4 = _slicedToArray(_React$useState3, 2),
popupWidth = _React$useState4[0],
setPopupWidth = _React$useState4[1];
var _useMergedState = useMergedState(false, {
value: props.open
}),
_useMergedState2 = _slicedToArray(_useMergedState, 2),
open = _useMergedState2[0],
setOpen = _useMergedState2[1];
var _React$useContext = React.useContext(ConfigContext),
getPrefixCls = _React$useContext.getPrefixCls;
var prefixCls = getPrefixCls(defaultPrefixCls || 'select', customizePrefixCls);
React.useEffect(function () {
// We do not care about ssr
setOpen(true);
if (typeof ResizeObserver !== 'undefined') {
var resizeObserver = new ResizeObserver(function (entries) {
var element = entries[0].target;
setPopupHeight(element.offsetHeight + 8);
setPopupWidth(element.offsetWidth);
});
var interval = setInterval(function () {
var _a;
var dropdownCls = getDropdownCls ? "." + getDropdownCls(prefixCls) : "." + prefixCls + "-dropdown";
var popup = (_a = holderRef.current) === null || _a === void 0 ? void 0 : _a.querySelector(dropdownCls);
if (popup) {
clearInterval(interval);
resizeObserver.observe(popup);
}
}, 10);
return function () {
clearInterval(interval);
resizeObserver.disconnect();
};
}
}, []);
return /*#__PURE__*/React.createElement(ConfigProvider, {
theme: {
token: {
motionDurationFast: '0.01s',
motionDurationMid: '0.01s',
motionDurationSlow: '0.01s'
}
}
}, /*#__PURE__*/React.createElement("div", {
ref: holderRef,
style: {
paddingBottom: popupHeight,
position: 'relative',
width: 'fit-content',
minWidth: popupWidth
}
}, /*#__PURE__*/React.createElement(Component, _extends$1({}, props, {
style: _extends$1(_extends$1({}, style), {
margin: 0
}),
open: open,
visible: open,
getPopupContainer: function getPopupContainer() {
return holderRef.current;
}
}))));
};
}
var genSpaceCompactStyle = function genSpaceCompactStyle(token) {
var componentCls = token.componentCls;
return _defineProperty$1({}, componentCls, {
display: 'inline-flex',
'&-block': {
display: 'flex',
width: '100%'
},
'&-vertical': {
flexDirection: 'column'
}
});
};
// ============================== Export ==============================
var genSpaceCompactStyle$1 = genSpaceCompactStyle;
var genSpaceStyle = function genSpaceStyle(token) {
var componentCls = token.componentCls;
return _defineProperty$1({}, componentCls, _defineProperty$1({
display: 'inline-flex',
'&-rtl': {
direction: 'rtl'
},
'&-vertical': {
flexDirection: 'column'
},
'&-align': {
flexDirection: 'column',
'&-center': {
alignItems: 'center'
},
'&-start': {
alignItems: 'flex-start'
},
'&-end': {
alignItems: 'flex-end'
},
'&-baseline': {
alignItems: 'flex-baseline'
}
}
}, componentCls + "-space-item", {
'&:empty': {
display: 'none'
}
}));
};
// ============================== Export ==============================
var useStyle$7 = genComponentStyleHook('Space', function (token) {
return [genSpaceStyle(token), genSpaceCompactStyle$1(token)];
});
var __rest$e = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var SpaceCompactItemContext = /*#__PURE__*/React.createContext(null);
var useCompactItemContext = function useCompactItemContext(prefixCls, direction) {
var compactItemContext = React.useContext(SpaceCompactItemContext);
var compactItemClassnames = React.useMemo(function () {
var _classNames;
if (!compactItemContext) return '';
var compactDirection = compactItemContext.compactDirection,
isFirstItem = compactItemContext.isFirstItem,
isLastItem = compactItemContext.isLastItem;
var separator = compactDirection === 'vertical' ? '-vertical-' : '-';
return classNames((_classNames = {}, _defineProperty$1(_classNames, prefixCls + "-compact" + separator + "item", true), _defineProperty$1(_classNames, prefixCls + "-compact" + separator + "first-item", isFirstItem), _defineProperty$1(_classNames, prefixCls + "-compact" + separator + "last-item", isLastItem), _defineProperty$1(_classNames, prefixCls + "-compact" + separator + "item-rtl", direction === 'rtl'), _classNames));
}, [prefixCls, direction, compactItemContext]);
return {
compactSize: compactItemContext === null || compactItemContext === void 0 ? void 0 : compactItemContext.compactSize,
compactDirection: compactItemContext === null || compactItemContext === void 0 ? void 0 : compactItemContext.compactDirection,
compactItemClassnames: compactItemClassnames
};
};
var NoCompactStyle = function NoCompactStyle(_ref) {
var children = _ref.children;
return /*#__PURE__*/React.createElement(SpaceCompactItemContext.Provider, {
value: null
}, children);
};
var CompactItem = function CompactItem(_a) {
var children = _a.children,
otherProps = __rest$e(_a, ["children"]);
return /*#__PURE__*/React.createElement(SpaceCompactItemContext.Provider, {
value: otherProps
}, children);
};
var Compact = function Compact(props) {
var _classNames2;
var _React$useContext = React.useContext(ConfigContext),
getPrefixCls = _React$useContext.getPrefixCls,
directionConfig = _React$useContext.direction;
var _props$size = props.size,
size = _props$size === void 0 ? 'middle' : _props$size,
direction = props.direction,
block = props.block,
customizePrefixCls = props.prefixCls,
className = props.className,
children = props.children,
restProps = __rest$e(props, ["size", "direction", "block", "prefixCls", "className", "children"]);
var prefixCls = getPrefixCls('space-compact', customizePrefixCls);
var _useStyle = useStyle$7(prefixCls),
_useStyle2 = _slicedToArray(_useStyle, 2),
wrapSSR = _useStyle2[0],
hashId = _useStyle2[1];
var clx = classNames(prefixCls, hashId, (_classNames2 = {}, _defineProperty$1(_classNames2, prefixCls + "-rtl", directionConfig === 'rtl'), _defineProperty$1(_classNames2, prefixCls + "-block", block), _defineProperty$1(_classNames2, prefixCls + "-vertical", direction === 'vertical'), _classNames2), className);
var compactItemContext = React.useContext(SpaceCompactItemContext);
var childNodes = toArray$1(children);
var nodes = React.useMemo(function () {
return childNodes.map(function (child, i) {
var key = child && child.key || prefixCls + "-item-" + i;
return /*#__PURE__*/React.createElement(CompactItem, {
key: key,
compactSize: size,
compactDirection: direction,
isFirstItem: i === 0 && (!compactItemContext || (compactItemContext === null || compactItemContext === void 0 ? void 0 : compactItemContext.isFirstItem)),
isLastItem: i === childNodes.length - 1 && (!compactItemContext || (compactItemContext === null || compactItemContext === void 0 ? void 0 : compactItemContext.isLastItem))
}, child);
});
}, [size, childNodes, compactItemContext]);
// =========================== Render ===========================
if (childNodes.length === 0) {
return null;
}
return wrapSSR( /*#__PURE__*/React.createElement("div", _extends$1({
className: clx
}, restProps), nodes));
};
var Compact$1 = Compact;
var autoAdjustOverflow$2 = {
adjustX: 1,
adjustY: 1
};
var targetOffset$2 = [0, 0];
var placements$2 = {
left: {
points: ['cr', 'cl'],
overflow: autoAdjustOverflow$2,
offset: [-4, 0],
targetOffset: targetOffset$2
},
right: {
points: ['cl', 'cr'],
overflow: autoAdjustOverflow$2,
offset: [4, 0],
targetOffset: targetOffset$2
},
top: {
points: ['bc', 'tc'],
overflow: autoAdjustOverflow$2,
offset: [0, -4],
targetOffset: targetOffset$2
},
bottom: {
points: ['tc', 'bc'],
overflow: autoAdjustOverflow$2,
offset: [0, 4],
targetOffset: targetOffset$2
},
topLeft: {
points: ['bl', 'tl'],
overflow: autoAdjustOverflow$2,
offset: [0, -4],
targetOffset: targetOffset$2
},
leftTop: {
points: ['tr', 'tl'],
overflow: autoAdjustOverflow$2,
offset: [-4, 0],
targetOffset: targetOffset$2
},
topRight: {
points: ['br', 'tr'],
overflow: autoAdjustOverflow$2,
offset: [0, -4],
targetOffset: targetOffset$2
},
rightTop: {
points: ['tl', 'tr'],
overflow: autoAdjustOverflow$2,
offset: [4, 0],
targetOffset: targetOffset$2
},
bottomRight: {
points: ['tr', 'br'],
overflow: autoAdjustOverflow$2,
offset: [0, 4],
targetOffset: targetOffset$2
},
rightBottom: {
points: ['bl', 'br'],
overflow: autoAdjustOverflow$2,
offset: [4, 0],
targetOffset: targetOffset$2
},
bottomLeft: {
points: ['tl', 'bl'],
overflow: autoAdjustOverflow$2,
offset: [0, 4],
targetOffset: targetOffset$2
},
leftBottom: {
points: ['br', 'bl'],
overflow: autoAdjustOverflow$2,
offset: [-4, 0],
targetOffset: targetOffset$2
}
};
function Popup(props) {
var showArrow = props.showArrow,
arrowContent = props.arrowContent,
children = props.children,
prefixCls = props.prefixCls,
id = props.id,
overlayInnerStyle = props.overlayInnerStyle,
className = props.className,
style = props.style;
return /*#__PURE__*/React.createElement("div", {
className: classNames("".concat(prefixCls, "-content"), className),
style: style
}, showArrow !== false && /*#__PURE__*/React.createElement("div", {
className: "".concat(prefixCls, "-arrow"),
key: "arrow"
}, arrowContent), /*#__PURE__*/React.createElement("div", {
className: "".concat(prefixCls, "-inner"),
id: id,
role: "tooltip",
style: overlayInnerStyle
}, typeof children === 'function' ? children() : children));
}
var Tooltip$2 = function Tooltip(props, ref) {
var overlayClassName = props.overlayClassName,
_props$trigger = props.trigger,
trigger = _props$trigger === void 0 ? ['hover'] : _props$trigger,
_props$mouseEnterDela = props.mouseEnterDelay,
mouseEnterDelay = _props$mouseEnterDela === void 0 ? 0 : _props$mouseEnterDela,
_props$mouseLeaveDela = props.mouseLeaveDelay,
mouseLeaveDelay = _props$mouseLeaveDela === void 0 ? 0.1 : _props$mouseLeaveDela,
overlayStyle = props.overlayStyle,
_props$prefixCls = props.prefixCls,
prefixCls = _props$prefixCls === void 0 ? 'rc-tooltip' : _props$prefixCls,
children = props.children,
onVisibleChange = props.onVisibleChange,
afterVisibleChange = props.afterVisibleChange,
transitionName = props.transitionName,
animation = props.animation,
motion = props.motion,
_props$placement = props.placement,
placement = _props$placement === void 0 ? 'right' : _props$placement,
_props$align = props.align,
align = _props$align === void 0 ? {} : _props$align,
_props$destroyTooltip = props.destroyTooltipOnHide,
destroyTooltipOnHide = _props$destroyTooltip === void 0 ? false : _props$destroyTooltip,
defaultVisible = props.defaultVisible,
getTooltipContainer = props.getTooltipContainer,
overlayInnerStyle = props.overlayInnerStyle,
arrowContent = props.arrowContent,
overlay = props.overlay,
id = props.id,
showArrow = props.showArrow,
restProps = _objectWithoutProperties(props, ["overlayClassName", "trigger", "mouseEnterDelay", "mouseLeaveDelay", "overlayStyle", "prefixCls", "children", "onVisibleChange", "afterVisibleChange", "transitionName", "animation", "motion", "placement", "align", "destroyTooltipOnHide", "defaultVisible", "getTooltipContainer", "overlayInnerStyle", "arrowContent", "overlay", "id", "showArrow"]);
var domRef = useRef(null);
useImperativeHandle(ref, function () {
return domRef.current;
});
var extraProps = _objectSpread2$1({}, restProps);
if ('visible' in props) {
extraProps.popupVisible = props.visible;
}
var getPopupElement = function getPopupElement() {
return /*#__PURE__*/React.createElement(Popup, {
showArrow: showArrow,
arrowContent: arrowContent,
key: "content",
prefixCls: prefixCls,
id: id,
overlayInnerStyle: overlayInnerStyle
}, overlay);
};
var destroyTooltip = false;
var autoDestroy = false;
if (typeof destroyTooltipOnHide === 'boolean') {
destroyTooltip = destroyTooltipOnHide;
} else if (destroyTooltipOnHide && _typeof$1(destroyTooltipOnHide) === 'object') {
var keepParent = destroyTooltipOnHide.keepParent;
destroyTooltip = keepParent === true;
autoDestroy = keepParent === false;
}
return /*#__PURE__*/React.createElement(Trigger, _extends$1({
popupClassName: overlayClassName,
prefixCls: prefixCls,
popup: getPopupElement,
action: trigger,
builtinPlacements: placements$2,
popupPlacement: placement,
ref: domRef,
popupAlign: align,
getPopupContainer: getTooltipContainer,
onPopupVisibleChange: onVisibleChange,
afterPopupVisibleChange: afterVisibleChange,
popupTransitionName: transitionName,
popupAnimation: animation,
popupMotion: motion,
defaultPopupVisible: defaultVisible,
destroyPopupOnHide: destroyTooltip,
autoDestroy: autoDestroy,
mouseLeaveDelay: mouseLeaveDelay,
popupStyle: overlayStyle,
mouseEnterDelay: mouseEnterDelay
}, extraProps), children);
};
var Tooltip$3 = /*#__PURE__*/forwardRef(Tooltip$2);
var autoAdjustOverflowEnabled = {
adjustX: 1,
adjustY: 1
};
var autoAdjustOverflowDisabled = {
adjustX: 0,
adjustY: 0
};
var targetOffset$1 = [0, 0];
function getOverflowOptions(autoAdjustOverflow) {
if (typeof autoAdjustOverflow === 'boolean') {
return autoAdjustOverflow ? autoAdjustOverflowEnabled : autoAdjustOverflowDisabled;
}
return _extends$1(_extends$1({}, autoAdjustOverflowDisabled), autoAdjustOverflow);
}
function getPlacements(config) {
var _config$arrowWidth = config.arrowWidth,
arrowWidth = _config$arrowWidth === void 0 ? 4 : _config$arrowWidth,
_config$horizontalArr = config.horizontalArrowShift,
horizontalArrowShift = _config$horizontalArr === void 0 ? 16 : _config$horizontalArr,
_config$verticalArrow = config.verticalArrowShift,
verticalArrowShift = _config$verticalArrow === void 0 ? 8 : _config$verticalArrow,
autoAdjustOverflow = config.autoAdjustOverflow,
arrowPointAtCenter = config.arrowPointAtCenter;
var placementMap = {
left: {
points: ['cr', 'cl'],
offset: [-4, 0]
},
right: {
points: ['cl', 'cr'],
offset: [4, 0]
},
top: {
points: ['bc', 'tc'],
offset: [0, -4]
},
bottom: {
points: ['tc', 'bc'],
offset: [0, 4]
},
topLeft: {
points: ['bl', 'tc'],
offset: [-(horizontalArrowShift + arrowWidth), -4]
},
leftTop: {
points: ['tr', 'cl'],
offset: [-4, -(verticalArrowShift + arrowWidth)]
},
topRight: {
points: ['br', 'tc'],
offset: [horizontalArrowShift + arrowWidth, -4]
},
rightTop: {
points: ['tl', 'cr'],
offset: [4, -(verticalArrowShift + arrowWidth)]
},
bottomRight: {
points: ['tr', 'bc'],
offset: [horizontalArrowShift + arrowWidth, 4]
},
rightBottom: {
points: ['bl', 'cr'],
offset: [4, verticalArrowShift + arrowWidth]
},
bottomLeft: {
points: ['tl', 'bc'],
offset: [-(horizontalArrowShift + arrowWidth), 4]
},
leftBottom: {
points: ['br', 'cl'],
offset: [-4, verticalArrowShift + arrowWidth]
}
};
Object.keys(placementMap).forEach(function (key) {
placementMap[key] = arrowPointAtCenter ? _extends$1(_extends$1({}, placementMap[key]), {
overflow: getOverflowOptions(autoAdjustOverflow),
targetOffset: targetOffset$1
}) : _extends$1(_extends$1({}, placements$2[key]), {
overflow: getOverflowOptions(autoAdjustOverflow)
});
placementMap[key].ignoreShake = true;
});
return placementMap;
}
function connectArrowCls(classList) {
var showArrowCls = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
return classList.map(function (cls) {
return "" + showArrowCls + cls;
}).join(',');
}
var MAX_VERTICAL_CONTENT_RADIUS = 8;
function getArrowOffset(options) {
var maxVerticalContentRadius = MAX_VERTICAL_CONTENT_RADIUS;
var sizePopupArrow = options.sizePopupArrow,
contentRadius = options.contentRadius,
borderRadiusOuter = options.borderRadiusOuter,
limitVerticalRadius = options.limitVerticalRadius;
var arrowInnerOffset = sizePopupArrow / 2 - Math.ceil(borderRadiusOuter * (Math.sqrt(2) - 1));
var dropdownArrowOffset = (contentRadius > 12 ? contentRadius + 2 : 12) - arrowInnerOffset;
var dropdownArrowOffsetVertical = limitVerticalRadius ? maxVerticalContentRadius - arrowInnerOffset : dropdownArrowOffset;
return {
dropdownArrowOffset: dropdownArrowOffset,
dropdownArrowOffsetVertical: dropdownArrowOffsetVertical
};
}
function getArrowStyle(token, options) {
var _componentCls;
var componentCls = token.componentCls,
sizePopupArrow = token.sizePopupArrow,
marginXXS = token.marginXXS,
borderRadiusXS = token.borderRadiusXS,
borderRadiusOuter = token.borderRadiusOuter,
boxShadowPopoverArrow = token.boxShadowPopoverArrow;
var colorBg = options.colorBg,
showArrowCls = options.showArrowCls,
_options$contentRadiu = options.contentRadius,
contentRadius = _options$contentRadiu === void 0 ? token.borderRadiusLG : _options$contentRadiu,
limitVerticalRadius = options.limitVerticalRadius;
var _getArrowOffset = getArrowOffset({
sizePopupArrow: sizePopupArrow,
contentRadius: contentRadius,
borderRadiusOuter: borderRadiusOuter,
limitVerticalRadius: limitVerticalRadius
}),
dropdownArrowOffsetVertical = _getArrowOffset.dropdownArrowOffsetVertical,
dropdownArrowOffset = _getArrowOffset.dropdownArrowOffset;
var dropdownArrowDistance = sizePopupArrow / 2 + marginXXS;
return _defineProperty$1({}, componentCls, (_componentCls = {}, _defineProperty$1(_componentCls, componentCls + "-arrow", [_extends$1(_extends$1({
position: 'absolute',
zIndex: 1,
display: 'block'
}, roundedArrow(sizePopupArrow, borderRadiusXS, borderRadiusOuter, colorBg, boxShadowPopoverArrow)), {
'&:before': {
background: colorBg
}
})]), _defineProperty$1(_componentCls, ["&-placement-top " + componentCls + "-arrow", "&-placement-topLeft " + componentCls + "-arrow", "&-placement-topRight " + componentCls + "-arrow"].join(','), {
bottom: 0,
transform: 'translateY(100%) rotate(180deg)'
}), _defineProperty$1(_componentCls, "&-placement-top " + componentCls + "-arrow", {
left: {
_skip_check_: true,
value: '50%'
},
transform: 'translateX(-50%) translateY(100%) rotate(180deg)'
}), _defineProperty$1(_componentCls, "&-placement-topLeft " + componentCls + "-arrow", {
left: {
_skip_check_: true,
value: dropdownArrowOffset
}
}), _defineProperty$1(_componentCls, "&-placement-topRight " + componentCls + "-arrow", {
right: {
_skip_check_: true,
value: dropdownArrowOffset
}
}), _defineProperty$1(_componentCls, ["&-placement-bottom " + componentCls + "-arrow", "&-placement-bottomLeft " + componentCls + "-arrow", "&-placement-bottomRight " + componentCls + "-arrow"].join(','), {
top: 0,
transform: "translateY(-100%)"
}), _defineProperty$1(_componentCls, "&-placement-bottom " + componentCls + "-arrow", {
left: {
_skip_check_: true,
value: '50%'
},
transform: "translateX(-50%) translateY(-100%)"
}), _defineProperty$1(_componentCls, "&-placement-bottomLeft " + componentCls + "-arrow", {
left: {
_skip_check_: true,
value: dropdownArrowOffset
}
}), _defineProperty$1(_componentCls, "&-placement-bottomRight " + componentCls + "-arrow", {
right: {
_skip_check_: true,
value: dropdownArrowOffset
}
}), _defineProperty$1(_componentCls, ["&-placement-left " + componentCls + "-arrow", "&-placement-leftTop " + componentCls + "-arrow", "&-placement-leftBottom " + componentCls + "-arrow"].join(','), {
right: {
_skip_check_: true,
value: 0
},
transform: 'translateX(100%) rotate(90deg)'
}), _defineProperty$1(_componentCls, "&-placement-left " + componentCls + "-arrow", {
top: {
_skip_check_: true,
value: '50%'
},
transform: 'translateY(-50%) translateX(100%) rotate(90deg)'
}), _defineProperty$1(_componentCls, "&-placement-leftTop " + componentCls + "-arrow", {
top: dropdownArrowOffsetVertical
}), _defineProperty$1(_componentCls, "&-placement-leftBottom " + componentCls + "-arrow", {
bottom: dropdownArrowOffsetVertical
}), _defineProperty$1(_componentCls, ["&-placement-right " + componentCls + "-arrow", "&-placement-rightTop " + componentCls + "-arrow", "&-placement-rightBottom " + componentCls + "-arrow"].join(','), {
left: {
_skip_check_: true,
value: 0
},
transform: 'translateX(-100%) rotate(-90deg)'
}), _defineProperty$1(_componentCls, "&-placement-right " + componentCls + "-arrow", {
top: {
_skip_check_: true,
value: '50%'
},
transform: 'translateY(-50%) translateX(-100%) rotate(-90deg)'
}), _defineProperty$1(_componentCls, "&-placement-rightTop " + componentCls + "-arrow", {
top: dropdownArrowOffsetVertical
}), _defineProperty$1(_componentCls, "&-placement-rightBottom " + componentCls + "-arrow", {
bottom: dropdownArrowOffsetVertical
}), _defineProperty$1(_componentCls, connectArrowCls(["&-placement-topLeft", "&-placement-top", "&-placement-topRight"], showArrowCls), {
paddingBottom: dropdownArrowDistance
}), _defineProperty$1(_componentCls, connectArrowCls(["&-placement-bottomLeft", "&-placement-bottom", "&-placement-bottomRight"], showArrowCls), {
paddingTop: dropdownArrowDistance
}), _defineProperty$1(_componentCls, connectArrowCls(["&-placement-leftTop", "&-placement-left", "&-placement-leftBottom"], showArrowCls), {
paddingRight: {
_skip_check_: true,
value: dropdownArrowDistance
}
}), _defineProperty$1(_componentCls, connectArrowCls(["&-placement-rightTop", "&-placement-right", "&-placement-rightBottom"], showArrowCls), {
paddingLeft: {
_skip_check_: true,
value: dropdownArrowDistance
}
}), _componentCls));
}
var generatorTooltipPresetColor = function generatorTooltipPresetColor(token) {
var componentCls = token.componentCls;
return PresetColors.reduce(function (previousValue, currentValue) {
var _previousValue;
var lightColor = token[currentValue + "-6"];
previousValue["&" + componentCls + "-" + currentValue] = (_previousValue = {}, _defineProperty$1(_previousValue, componentCls + "-inner", {
backgroundColor: lightColor
}), _defineProperty$1(_previousValue, componentCls + "-arrow", {
'--antd-arrow-background-color': lightColor
}), _previousValue);
return previousValue;
}, {});
};
var genTooltipStyle = function genTooltipStyle(token) {
var _extends2;
var componentCls = token.componentCls,
tooltipMaxWidth = token.tooltipMaxWidth,
tooltipColor = token.tooltipColor,
tooltipBg = token.tooltipBg,
tooltipBorderRadius = token.tooltipBorderRadius,
zIndexPopup = token.zIndexPopup,
controlHeight = token.controlHeight,
boxShadowSecondary = token.boxShadowSecondary,
paddingSM = token.paddingSM,
paddingXS = token.paddingXS,
tooltipRadiusOuter = token.tooltipRadiusOuter;
return [_defineProperty$1({}, componentCls, _extends$1(_extends$1(_extends$1(_extends$1({}, resetComponent(token)), (_extends2 = {
position: 'absolute',
zIndex: zIndexPopup,
display: 'block',
'&': [{
width: 'max-content'
}, {
width: 'intrinsic'
}],
maxWidth: tooltipMaxWidth,
visibility: 'visible',
'&-hidden': {
display: 'none'
},
'--antd-arrow-background-color': tooltipBg
}, _defineProperty$1(_extends2, componentCls + "-inner", {
minWidth: controlHeight,
minHeight: controlHeight,
padding: paddingSM / 2 + "px " + paddingXS + "px",
color: tooltipColor,
textAlign: 'start',
textDecoration: 'none',
wordWrap: 'break-word',
backgroundColor: tooltipBg,
borderRadius: tooltipBorderRadius,
boxShadow: boxShadowSecondary
}), _defineProperty$1(_extends2, ["&-placement-left", "&-placement-leftTop", "&-placement-leftBottom", "&-placement-right", "&-placement-rightTop", "&-placement-rightBottom"].join(','), _defineProperty$1({}, componentCls + "-inner", {
borderRadius: tooltipBorderRadius > MAX_VERTICAL_CONTENT_RADIUS ? MAX_VERTICAL_CONTENT_RADIUS : tooltipBorderRadius
})), _defineProperty$1(_extends2, componentCls + "-content", {
position: 'relative'
}), _extends2)), generatorTooltipPresetColor(token)), {
// RTL
'&-rtl': {
direction: 'rtl'
}
})),
// Arrow Style
getArrowStyle(merge(token, {
borderRadiusOuter: tooltipRadiusOuter
}), {
colorBg: 'var(--antd-arrow-background-color)',
showArrowCls: '',
contentRadius: tooltipBorderRadius,
limitVerticalRadius: true
}),
// Pure Render
_defineProperty$1({}, componentCls + "-pure", {
position: 'relative',
maxWidth: 'none'
})];
};
// ============================== Export ==============================
var useStyle$6 = (function (prefixCls, injectStyle) {
var useOriginHook = genComponentStyleHook('Tooltip', function (token) {
// Popover use Tooltip as internal component. We do not need to handle this.
if (injectStyle === false) {
return [];
}
var borderRadius = token.borderRadius,
colorTextLightSolid = token.colorTextLightSolid,
colorBgDefault = token.colorBgDefault,
borderRadiusOuter = token.borderRadiusOuter;
var TooltipToken = merge(token, {
// default variables
tooltipMaxWidth: 250,
tooltipColor: colorTextLightSolid,
tooltipBorderRadius: borderRadius,
tooltipBg: colorBgDefault,
tooltipRadiusOuter: borderRadiusOuter > 4 ? 4 : borderRadiusOuter
});
return [genTooltipStyle(TooltipToken), initZoomMotion(token, 'zoom-big-fast')];
}, function (_ref3) {
var zIndexPopupBase = _ref3.zIndexPopupBase,
colorBgSpotlight = _ref3.colorBgSpotlight;
return {
zIndexPopup: zIndexPopupBase + 70,
colorBgDefault: colorBgSpotlight
};
});
return useOriginHook(prefixCls);
});
tuple('success', 'processing', 'error', 'default', 'warning');
// eslint-disable-next-line import/prefer-default-export
var PresetColorTypes = tuple('pink', 'red', 'yellow', 'orange', 'cyan', 'green', 'blue', 'purple', 'geekblue', 'magenta', 'volcano', 'gold', 'lime');
var PresetColorRegex = new RegExp("^(" + PresetColorTypes.join('|') + ")(-inverse)?$");
function parseColor(prefixCls, color) {
var className = classNames(_defineProperty$1({}, prefixCls + "-" + color, color && PresetColorRegex.test(color)));
var overlayStyle = {};
var arrowStyle = {};
if (color && !PresetColorRegex.test(color)) {
overlayStyle.background = color;
// @ts-ignore
arrowStyle['--antd-arrow-background-color'] = color;
}
return {
className: className,
overlayStyle: overlayStyle,
arrowStyle: arrowStyle
};
}
// ant-tooltip css-dev-only-do-not-override-w2s56n ant-tooltip-placement-top ant-tooltip-hidden
function PurePanel$1(props) {
var customizePrefixCls = props.prefixCls,
className = props.className,
_props$placement = props.placement,
placement = _props$placement === void 0 ? 'top' : _props$placement,
title = props.title,
color = props.color,
overlayInnerStyle = props.overlayInnerStyle;
var _React$useContext = React.useContext(ConfigContext),
getPrefixCls = _React$useContext.getPrefixCls;
var prefixCls = getPrefixCls('tooltip', customizePrefixCls);
var _useStyle = useStyle$6(prefixCls, true),
_useStyle2 = _slicedToArray(_useStyle, 2),
wrapSSR = _useStyle2[0],
hashId = _useStyle2[1];
// Color
var colorInfo = parseColor(prefixCls, color);
var formattedOverlayInnerStyle = _extends$1(_extends$1({}, overlayInnerStyle), colorInfo.overlayStyle);
var arrowContentStyle = colorInfo.arrowStyle;
return wrapSSR( /*#__PURE__*/React.createElement("div", {
className: classNames(hashId, prefixCls, prefixCls + "-pure", prefixCls + "-placement-" + placement, className, colorInfo.className),
style: arrowContentStyle
}, /*#__PURE__*/React.createElement(Popup, _extends$1({}, props, {
className: hashId,
prefixCls: prefixCls,
overlayInnerStyle: formattedOverlayInnerStyle
}), title)));
}
var __rest$d = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var splitObject = function splitObject(obj, keys) {
var picked = {};
var omitted = _extends$1({}, obj);
keys.forEach(function (key) {
if (obj && key in obj) {
picked[key] = obj[key];
delete omitted[key];
}
});
return {
picked: picked,
omitted: omitted
};
};
// Fix Tooltip won't hide at disabled button
// mouse events don't trigger at disabled button in Chrome
// https://github.com/react-component/tooltip/issues/18
function getDisabledCompatibleChildren(element, prefixCls) {
var elementType = element.type;
if ((elementType.__ANT_BUTTON === true || element.type === 'button') && element.props.disabled || elementType.__ANT_SWITCH === true && (element.props.disabled || element.props.loading) || elementType.__ANT_RADIO === true && element.props.disabled) {
// Pick some layout related style properties up to span
// Prevent layout bugs like https://github.com/ant-design/ant-design/issues/5254
var _splitObject = splitObject(element.props.style, ['position', 'left', 'right', 'top', 'bottom', 'float', 'display', 'zIndex']),
picked = _splitObject.picked,
omitted = _splitObject.omitted;
var spanStyle = _extends$1(_extends$1({
display: 'inline-block'
}, picked), {
cursor: 'not-allowed',
width: element.props.block ? '100%' : undefined
});
var buttonStyle = _extends$1(_extends$1({}, omitted), {
pointerEvents: 'none'
});
var child = cloneElement(element, {
style: buttonStyle,
className: null
});
return /*#__PURE__*/React.createElement("span", {
style: spanStyle,
className: classNames(element.props.className, prefixCls + "-disabled-compatible-wrapper")
}, child);
}
return element;
}
var Tooltip = /*#__PURE__*/React.forwardRef(function (props, ref) {
var _a, _b;
var customizePrefixCls = props.prefixCls,
openClassName = props.openClassName,
getTooltipContainer = props.getTooltipContainer,
overlayClassName = props.overlayClassName,
color = props.color,
overlayInnerStyle = props.overlayInnerStyle,
children = props.children,
afterOpenChange = props.afterOpenChange,
afterVisibleChange = props.afterVisibleChange;
var _React$useContext = React.useContext(ConfigContext),
getContextPopupContainer = _React$useContext.getPopupContainer,
getPrefixCls = _React$useContext.getPrefixCls,
direction = _React$useContext.direction;
if (process.env.NODE_ENV !== 'production') {
[['visible', 'open'], ['defaultVisible', 'defaultOpen'], ['onVisibleChange', 'onOpenChange'], ['afterVisibleChange', 'afterOpenChange']].forEach(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
deprecatedName = _ref2[0],
newName = _ref2[1];
process.env.NODE_ENV !== "production" ? warning$2(!(deprecatedName in props), 'Tooltip', "`" + deprecatedName + "` is deprecated, please use `" + newName + "` instead.") : void 0;
});
}
var _useMergedState = useMergedState(false, {
value: (_a = props.open) !== null && _a !== void 0 ? _a : props.visible,
defaultValue: (_b = props.defaultOpen) !== null && _b !== void 0 ? _b : props.defaultVisible
}),
_useMergedState2 = _slicedToArray(_useMergedState, 2),
open = _useMergedState2[0],
setOpen = _useMergedState2[1];
var isNoTitle = function isNoTitle() {
var title = props.title,
overlay = props.overlay;
return !title && !overlay && title !== 0; // overlay for old version compatibility
};
var onOpenChange = function onOpenChange(vis) {
var _a, _b;
setOpen(isNoTitle() ? false : vis);
if (!isNoTitle()) {
(_a = props.onOpenChange) === null || _a === void 0 ? void 0 : _a.call(props, vis);
(_b = props.onVisibleChange) === null || _b === void 0 ? void 0 : _b.call(props, vis);
}
};
var getTooltipPlacements = function getTooltipPlacements() {
var builtinPlacements = props.builtinPlacements,
_props$arrowPointAtCe = props.arrowPointAtCenter,
arrowPointAtCenter = _props$arrowPointAtCe === void 0 ? false : _props$arrowPointAtCe,
_props$autoAdjustOver = props.autoAdjustOverflow,
autoAdjustOverflow = _props$autoAdjustOver === void 0 ? true : _props$autoAdjustOver;
return builtinPlacements || getPlacements({
arrowPointAtCenter: arrowPointAtCenter,
autoAdjustOverflow: autoAdjustOverflow
});
};
// 动态设置动画点
var onPopupAlign = function onPopupAlign(domNode, align) {
var placements = getTooltipPlacements();
// 当前返回的位置
var placement = Object.keys(placements).find(function (key) {
var _a, _b;
return placements[key].points[0] === ((_a = align.points) === null || _a === void 0 ? void 0 : _a[0]) && placements[key].points[1] === ((_b = align.points) === null || _b === void 0 ? void 0 : _b[1]);
});
if (!placement) {
return;
}
// 根据当前坐标设置动画点
var rect = domNode.getBoundingClientRect();
var transformOrigin = {
top: '50%',
left: '50%'
};
if (/top|Bottom/.test(placement)) {
transformOrigin.top = rect.height - align.offset[1] + "px";
} else if (/Top|bottom/.test(placement)) {
transformOrigin.top = -align.offset[1] + "px";
}
if (/left|Right/.test(placement)) {
transformOrigin.left = rect.width - align.offset[0] + "px";
} else if (/right|Left/.test(placement)) {
transformOrigin.left = -align.offset[0] + "px";
}
domNode.style.transformOrigin = transformOrigin.left + " " + transformOrigin.top;
};
var getOverlay = function getOverlay() {
var title = props.title,
overlay = props.overlay;
if (title === 0) {
return title;
}
return overlay || title || '';
};
var getPopupContainer = props.getPopupContainer,
_props$placement = props.placement,
placement = _props$placement === void 0 ? 'top' : _props$placement,
_props$mouseEnterDela = props.mouseEnterDelay,
mouseEnterDelay = _props$mouseEnterDela === void 0 ? 0.1 : _props$mouseEnterDela,
_props$mouseLeaveDela = props.mouseLeaveDelay,
mouseLeaveDelay = _props$mouseLeaveDela === void 0 ? 0.1 : _props$mouseLeaveDela,
overlayStyle = props.overlayStyle,
otherProps = __rest$d(props, ["getPopupContainer", "placement", "mouseEnterDelay", "mouseLeaveDelay", "overlayStyle"]);
var prefixCls = getPrefixCls('tooltip', customizePrefixCls);
var rootPrefixCls = getPrefixCls();
var injectFromPopover = props['data-popover-inject'];
var tempOpen = open;
// Hide tooltip when there is no title
if (!('open' in props) && !('visible' in props) && isNoTitle()) {
tempOpen = false;
}
var child = getDisabledCompatibleChildren(isValidElement(children) && !isFragment(children) ? children : /*#__PURE__*/React.createElement("span", null, children), prefixCls);
var childProps = child.props;
var childCls = !childProps.className || typeof childProps.className === 'string' ? classNames(childProps.className, _defineProperty$1({}, openClassName || prefixCls + "-open", true)) : childProps.className;
// Style
var _useStyle = useStyle$6(prefixCls, !injectFromPopover),
_useStyle2 = _slicedToArray(_useStyle, 2),
wrapSSR = _useStyle2[0],
hashId = _useStyle2[1];
// Color
var colorInfo = parseColor(prefixCls, color);
var formattedOverlayInnerStyle = _extends$1(_extends$1({}, overlayInnerStyle), colorInfo.overlayStyle);
var arrowContentStyle = colorInfo.arrowStyle;
var customOverlayClassName = classNames(overlayClassName, _defineProperty$1({}, prefixCls + "-rtl", direction === 'rtl'), colorInfo.className, hashId);
return wrapSSR( /*#__PURE__*/React.createElement(Tooltip$3, _extends$1({}, otherProps, {
placement: placement,
mouseEnterDelay: mouseEnterDelay,
mouseLeaveDelay: mouseLeaveDelay,
prefixCls: prefixCls,
overlayClassName: customOverlayClassName,
overlayStyle: _extends$1(_extends$1({}, arrowContentStyle), overlayStyle),
getTooltipContainer: getPopupContainer || getTooltipContainer || getContextPopupContainer,
ref: ref,
builtinPlacements: getTooltipPlacements(),
overlay: getOverlay(),
visible: tempOpen,
onVisibleChange: onOpenChange,
afterVisibleChange: afterOpenChange !== null && afterOpenChange !== void 0 ? afterOpenChange : afterVisibleChange,
onPopupAlign: onPopupAlign,
overlayInnerStyle: formattedOverlayInnerStyle,
arrowContent: /*#__PURE__*/React.createElement("span", {
className: prefixCls + "-arrow-content"
}),
motion: {
motionName: getTransitionName(rootPrefixCls, 'zoom-big-fast', props.transitionName),
motionDeadline: 1000
}
}), tempOpen ? cloneElement(child, {
className: childCls
}) : child));
});
if (process.env.NODE_ENV !== 'production') {
Tooltip.displayName = 'Tooltip';
}
Tooltip._InternalPanelDoNotUseOrYouWillBeFired = PurePanel$1;
var Tooltip$1 = Tooltip;
var antStatusProcessing = new Keyframe('antStatusProcessing', {
'0%': {
transform: 'scale(0.8)',
opacity: 0.5
},
'100%': {
transform: 'scale(2.4)',
opacity: 0
}
});
var antZoomBadgeIn = new Keyframe('antZoomBadgeIn', {
'0%': {
transform: 'scale(0) translate(50%, -50%)',
opacity: 0
},
'100%': {
transform: 'scale(1) translate(50%, -50%)'
}
});
var antZoomBadgeOut = new Keyframe('antZoomBadgeOut', {
'0%': {
transform: 'scale(1) translate(50%, -50%)'
},
'100%': {
transform: 'scale(0) translate(50%, -50%)',
opacity: 0
}
});
var antNoWrapperZoomBadgeIn = new Keyframe('antNoWrapperZoomBadgeIn', {
'0%': {
transform: 'scale(0)',
opacity: 0
},
'100%': {
transform: 'scale(1)'
}
});
var antNoWrapperZoomBadgeOut = new Keyframe('antNoWrapperZoomBadgeOut', {
'0%': {
transform: 'scale(1)'
},
'100%': {
transform: 'scale(0)',
opacity: 0
}
});
var antBadgeLoadingCircle = new Keyframe('antBadgeLoadingCircle', {
'0%': {
transformOrigin: '50%'
},
'100%': {
transform: 'translate(50%, -50%) rotate(360deg)',
transformOrigin: '50%'
}
});
var genSharedBadgeStyle = function genSharedBadgeStyle(token) {
var _extends4, _ref2, _ref4, _extends6, _extends7, _extends8, _ref7;
var componentCls = token.componentCls,
iconCls = token.iconCls,
antCls = token.antCls,
badgeFontHeight = token.badgeFontHeight,
badgeShadowSize = token.badgeShadowSize,
badgeHeightSm = token.badgeHeightSm,
motionDurationSlow = token.motionDurationSlow,
badgeStatusSize = token.badgeStatusSize,
marginXS = token.marginXS,
badgeRibbonOffset = token.badgeRibbonOffset;
var numberPrefixCls = antCls + "-scroll-number";
var ribbonPrefixCls = antCls + "-ribbon";
var ribbonWrapperPrefixCls = antCls + "-ribbon-wrapper";
var statusPreset = PresetColors.reduce(function (prev, colorKey) {
var darkColor = token[colorKey + "-6"];
return _extends$1(_extends$1({}, prev), _defineProperty$1({}, componentCls + "-status-" + colorKey, {
background: darkColor
}));
}, {});
var statusRibbonPreset = PresetColors.reduce(function (prev, colorKey) {
var darkColor = token[colorKey + "-6"];
return _extends$1(_extends$1({}, prev), _defineProperty$1({}, "&" + ribbonPrefixCls + "-color-" + colorKey, {
background: darkColor,
color: darkColor
}));
}, {});
return _ref7 = {}, _defineProperty$1(_ref7, componentCls, _extends$1(_extends$1({}, resetComponent(token)), (_extends6 = {
position: 'relative',
display: 'inline-block',
lineHeight: 1
}, _defineProperty$1(_extends6, componentCls + "-count", {
zIndex: token.badgeZIndex,
minWidth: token.badgeHeight,
height: token.badgeHeight,
color: token.badgeTextColor,
fontWeight: token.badgeFontWeight,
fontSize: token.badgeFontSize,
lineHeight: token.badgeHeight + "px",
whiteSpace: 'nowrap',
textAlign: 'center',
background: token.badgeColor,
borderRadius: token.badgeHeight / 2,
boxShadow: "0 0 0 " + badgeShadowSize + "px " + token.badgeShadowColor,
transition: "background " + token.motionDurationMid,
a: {
color: token.badgeTextColor
},
'a:hover': {
color: token.badgeTextColor
},
'a:hover &': {
background: token.badgeColorHover
}
}), _defineProperty$1(_extends6, componentCls + "-count-sm", {
minWidth: badgeHeightSm,
height: badgeHeightSm,
fontSize: token.badgeFontSizeSm,
lineHeight: badgeHeightSm + "px",
borderRadius: badgeHeightSm / 2
}), _defineProperty$1(_extends6, componentCls + "-multiple-words", {
padding: "0 " + token.paddingXS + "px"
}), _defineProperty$1(_extends6, componentCls + "-dot", {
zIndex: token.badgeZIndex,
width: token.badgeDotSize,
minWidth: token.badgeDotSize,
height: token.badgeDotSize,
background: token.badgeColor,
borderRadius: '100%',
boxShadow: "0 0 0 " + badgeShadowSize + "px " + token.badgeShadowColor
}), _defineProperty$1(_extends6, componentCls + "-dot" + numberPrefixCls, {
transition: "background " + motionDurationSlow
}), _defineProperty$1(_extends6, componentCls + "-count, " + componentCls + "-dot, " + numberPrefixCls + "-custom-component", _defineProperty$1({
position: 'absolute',
top: 0,
insetInlineEnd: 0,
transform: 'translate(50%, -50%)',
transformOrigin: '100% 0%'
}, iconCls + "-spin", {
animationName: antBadgeLoadingCircle,
animationDuration: token.motionDurationMid,
animationIterationCount: 'infinite',
animationTimingFunction: 'linear'
})), _defineProperty$1(_extends6, "&" + componentCls + "-status", _extends$1(_extends$1((_extends4 = {
lineHeight: 'inherit',
verticalAlign: 'baseline'
}, _defineProperty$1(_extends4, componentCls + "-status-dot", {
position: 'relative',
top: -1,
display: 'inline-block',
width: badgeStatusSize,
height: badgeStatusSize,
verticalAlign: 'middle',
borderRadius: '50%'
}), _defineProperty$1(_extends4, componentCls + "-status-success", {
backgroundColor: token.colorSuccess
}), _defineProperty$1(_extends4, componentCls + "-status-processing", {
position: 'relative',
color: token.colorPrimary,
backgroundColor: token.colorPrimary,
'&::after': {
position: 'absolute',
top: 0,
insetInlineStart: 0,
width: '100%',
height: '100%',
borderWidth: badgeShadowSize,
borderStyle: 'solid',
borderColor: 'inherit',
borderRadius: '50%',
animationName: antStatusProcessing,
animationDuration: token.badgeProcessingDuration,
animationIterationCount: 'infinite',
animationTimingFunction: 'ease-in-out',
content: '""'
}
}), _defineProperty$1(_extends4, componentCls + "-status-default", {
backgroundColor: token.colorTextPlaceholder
}), _defineProperty$1(_extends4, componentCls + "-status-error", {
backgroundColor: token.colorError
}), _defineProperty$1(_extends4, componentCls + "-status-warning", {
backgroundColor: token.colorWarning
}), _extends4), statusPreset), _defineProperty$1({}, componentCls + "-status-text", {
marginInlineStart: marginXS,
color: token.colorText,
fontSize: token.fontSize
}))), _defineProperty$1(_extends6, componentCls + "-zoom-appear, " + componentCls + "-zoom-enter", {
animationName: antZoomBadgeIn,
animationDuration: token.motionDurationSlow,
animationTimingFunction: token.motionEaseOutBack,
animationFillMode: 'both'
}), _defineProperty$1(_extends6, componentCls + "-zoom-leave", {
animationName: antZoomBadgeOut,
animationDuration: token.motionDurationSlow,
animationTimingFunction: token.motionEaseOutBack,
animationFillMode: 'both'
}), _defineProperty$1(_extends6, "&" + componentCls + "-not-a-wrapper", (_ref2 = {}, _defineProperty$1(_ref2, componentCls + "-zoom-appear, " + componentCls + "-zoom-enter", {
animationName: antNoWrapperZoomBadgeIn,
animationDuration: token.motionDurationSlow,
animationTimingFunction: token.motionEaseOutBack
}), _defineProperty$1(_ref2, componentCls + "-zoom-leave", {
animationName: antNoWrapperZoomBadgeOut,
animationDuration: token.motionDurationSlow,
animationTimingFunction: token.motionEaseOutBack
}), _defineProperty$1(_ref2, "&:not(" + componentCls + "-status)", {
verticalAlign: 'middle'
}), _defineProperty$1(_ref2, numberPrefixCls + "-custom-component, " + componentCls + "-count", {
transform: 'none'
}), _defineProperty$1(_ref2, numberPrefixCls + "-custom-component, " + numberPrefixCls, {
position: 'relative',
top: 'auto',
display: 'block',
transformOrigin: '50% 50%'
}), _ref2)), _defineProperty$1(_extends6, "" + numberPrefixCls, (_ref4 = {
overflow: 'hidden',
direction: 'ltr'
}, _defineProperty$1(_ref4, numberPrefixCls + "-only", _defineProperty$1({
position: 'relative',
display: 'inline-block',
height: token.badgeHeight,
transition: "all " + token.motionDurationSlow + " " + token.motionEaseOutBack,
WebkitTransformStyle: 'preserve-3d',
WebkitBackfaceVisibility: 'hidden'
}, "> p" + numberPrefixCls + "-only-unit", {
height: token.badgeHeight,
margin: 0,
WebkitTransformStyle: 'preserve-3d',
WebkitBackfaceVisibility: 'hidden'
})), _defineProperty$1(_ref4, numberPrefixCls + "-symbol", {
verticalAlign: 'top'
}), _ref4)), _defineProperty$1(_extends6, '&-rtl', _defineProperty$1({
direction: 'rtl'
}, componentCls + "-count, " + componentCls + "-dot, " + numberPrefixCls + "-custom-component", {
insetInlineEnd: 'auto'
})), _extends6))), _defineProperty$1(_ref7, "" + ribbonWrapperPrefixCls, {
position: 'relative'
}), _defineProperty$1(_ref7, "" + ribbonPrefixCls, _extends$1(_extends$1(_extends$1(_extends$1({}, resetComponent(token)), (_extends7 = {
position: 'absolute',
top: marginXS,
height: badgeFontHeight,
padding: "0 " + token.paddingXS + "px",
color: token.colorPrimary,
lineHeight: badgeFontHeight + "px",
whiteSpace: 'nowrap',
backgroundColor: token.colorPrimary,
borderRadius: token.borderRadiusSM
}, _defineProperty$1(_extends7, ribbonPrefixCls + "-text", {
color: token.colorTextLightSolid
}), _defineProperty$1(_extends7, ribbonPrefixCls + "-corner", {
position: 'absolute',
top: '100%',
width: badgeRibbonOffset,
height: badgeRibbonOffset,
color: 'currentcolor',
border: badgeRibbonOffset / 2 + "px solid",
transform: token.badgeRibbonCornerTransform,
transformOrigin: 'top',
filter: token.badgeRibbonCornerFilter
}), _extends7)), statusRibbonPreset), (_extends8 = {}, _defineProperty$1(_extends8, "&" + ribbonPrefixCls + "-placement-end", _defineProperty$1({
insetInlineEnd: -badgeRibbonOffset,
borderEndEndRadius: 0
}, ribbonPrefixCls + "-corner", {
insetInlineEnd: 0,
borderInlineEndColor: 'transparent',
borderBlockEndColor: 'transparent'
})), _defineProperty$1(_extends8, "&" + ribbonPrefixCls + "-placement-start", _defineProperty$1({
insetInlineStart: -badgeRibbonOffset,
borderEndStartRadius: 0
}, ribbonPrefixCls + "-corner", {
insetInlineStart: 0,
borderBlockEndColor: 'transparent',
borderInlineStartColor: 'transparent'
})), _defineProperty$1(_extends8, '&-rtl', {
direction: 'rtl'
}), _extends8))), _ref7;
};
// ============================== Export ==============================
var useStyle$5 = genComponentStyleHook('Badge', function (token) {
var fontSize = token.fontSize,
lineHeight = token.lineHeight,
fontSizeSM = token.fontSizeSM,
lineWidth = token.lineWidth,
marginXS = token.marginXS,
colorBorderBg = token.colorBorderBg;
var badgeFontHeight = Math.round(fontSize * lineHeight);
var badgeShadowSize = lineWidth;
var badgeZIndex = 'auto';
var badgeHeight = badgeFontHeight - 2 * badgeShadowSize;
var badgeTextColor = token.colorBgContainer;
var badgeFontWeight = 'normal';
var badgeFontSize = fontSizeSM;
var badgeColor = token.colorError;
var badgeColorHover = token.colorErrorHover;
var badgeHeightSm = fontSize;
var badgeDotSize = fontSizeSM / 2;
var badgeFontSizeSm = fontSizeSM;
var badgeStatusSize = fontSizeSM / 2;
var badgeToken = merge(token, {
badgeFontHeight: badgeFontHeight,
badgeShadowSize: badgeShadowSize,
badgeZIndex: badgeZIndex,
badgeHeight: badgeHeight,
badgeTextColor: badgeTextColor,
badgeFontWeight: badgeFontWeight,
badgeFontSize: badgeFontSize,
badgeColor: badgeColor,
badgeColorHover: badgeColorHover,
badgeShadowColor: colorBorderBg,
badgeHeightSm: badgeHeightSm,
badgeDotSize: badgeDotSize,
badgeFontSizeSm: badgeFontSizeSm,
badgeStatusSize: badgeStatusSize,
badgeProcessingDuration: '1.2s',
badgeRibbonOffset: marginXS,
// Follow token just by Design. Not related with token
badgeRibbonCornerTransform: 'scaleY(0.75)',
badgeRibbonCornerFilter: "brightness(75%)"
});
return [genSharedBadgeStyle(badgeToken)];
});
// eslint-disable-next-line import/prefer-default-export
function isPresetColor(color) {
return PresetColorTypes.includes(color);
}
var Ribbon = function Ribbon(_ref) {
var _classNames;
var className = _ref.className,
customizePrefixCls = _ref.prefixCls,
style = _ref.style,
color = _ref.color,
children = _ref.children,
text = _ref.text,
_ref$placement = _ref.placement,
placement = _ref$placement === void 0 ? 'end' : _ref$placement;
var _React$useContext = React.useContext(ConfigContext),
getPrefixCls = _React$useContext.getPrefixCls,
direction = _React$useContext.direction;
var prefixCls = getPrefixCls('ribbon', customizePrefixCls);
var colorInPreset = isPresetColor(color);
var ribbonCls = classNames(prefixCls, prefixCls + "-placement-" + placement, (_classNames = {}, _defineProperty$1(_classNames, prefixCls + "-rtl", direction === 'rtl'), _defineProperty$1(_classNames, prefixCls + "-color-" + color, colorInPreset), _classNames), className);
var _useStyle = useStyle$5(prefixCls),
_useStyle2 = _slicedToArray(_useStyle, 2),
wrapSSR = _useStyle2[0],
hashId = _useStyle2[1];
var colorStyle = {};
var cornerColorStyle = {};
if (color && !colorInPreset) {
colorStyle.background = color;
cornerColorStyle.color = color;
}
return wrapSSR( /*#__PURE__*/React.createElement("div", {
className: classNames(prefixCls + "-wrapper", hashId)
}, children, /*#__PURE__*/React.createElement("div", {
className: classNames(ribbonCls, hashId),
style: _extends$1(_extends$1({}, colorStyle), style)
}, /*#__PURE__*/React.createElement("span", {
className: prefixCls + "-text"
}, text), /*#__PURE__*/React.createElement("div", {
className: prefixCls + "-corner",
style: cornerColorStyle
}))));
};
var Ribbon$1 = Ribbon;
function UnitNumber(_ref) {
var prefixCls = _ref.prefixCls,
value = _ref.value,
current = _ref.current,
_ref$offset = _ref.offset,
offset = _ref$offset === void 0 ? 0 : _ref$offset;
var style;
if (offset) {
style = {
position: 'absolute',
top: offset + "00%",
left: 0
};
}
return /*#__PURE__*/React.createElement("span", {
style: style,
className: classNames(prefixCls + "-only-unit", {
current: current
})
}, value);
}
function getOffset$1(start, end, unit) {
var index = start;
var offset = 0;
while ((index + 10) % 10 !== end) {
index += unit;
offset += unit;
}
return offset;
}
function SingleNumber(props) {
var prefixCls = props.prefixCls,
originCount = props.count,
originValue = props.value;
var value = Number(originValue);
var count = Math.abs(originCount);
var _React$useState = React.useState(value),
_React$useState2 = _slicedToArray(_React$useState, 2),
prevValue = _React$useState2[0],
setPrevValue = _React$useState2[1];
var _React$useState3 = React.useState(count),
_React$useState4 = _slicedToArray(_React$useState3, 2),
prevCount = _React$useState4[0],
setPrevCount = _React$useState4[1];
// ============================= Events =============================
var onTransitionEnd = function onTransitionEnd() {
setPrevValue(value);
setPrevCount(count);
};
// Fallback if transition event not support
React.useEffect(function () {
var timeout = setTimeout(function () {
onTransitionEnd();
}, 1000);
return function () {
clearTimeout(timeout);
};
}, [value]);
// ============================= Render =============================
// Render unit list
var unitNodes;
var offsetStyle;
if (prevValue === value || Number.isNaN(value) || Number.isNaN(prevValue)) {
// Nothing to change
unitNodes = [/*#__PURE__*/React.createElement(UnitNumber, _extends$1({}, props, {
key: value,
current: true
}))];
offsetStyle = {
transition: 'none'
};
} else {
unitNodes = [];
// Fill basic number units
var end = value + 10;
var unitNumberList = [];
for (var index = value; index <= end; index += 1) {
unitNumberList.push(index);
}
// Fill with number unit nodes
var prevIndex = unitNumberList.findIndex(function (n) {
return n % 10 === prevValue;
});
unitNodes = unitNumberList.map(function (n, index) {
var singleUnit = n % 10;
return /*#__PURE__*/React.createElement(UnitNumber, _extends$1({}, props, {
key: n,
value: singleUnit,
offset: index - prevIndex,
current: index === prevIndex
}));
});
// Calculate container offset value
var unit = prevCount < count ? 1 : -1;
offsetStyle = {
transform: "translateY(" + -getOffset$1(prevValue, value, unit) + "00%)"
};
}
return /*#__PURE__*/React.createElement("span", {
className: prefixCls + "-only",
style: offsetStyle,
onTransitionEnd: onTransitionEnd
}, unitNodes);
}
var __rest$c = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var ScrollNumber = function ScrollNumber(_a) {
var customizePrefixCls = _a.prefixCls,
count = _a.count,
className = _a.className,
motionClassName = _a.motionClassName,
style = _a.style,
title = _a.title,
show = _a.show,
_a$component = _a.component,
component = _a$component === void 0 ? 'sup' : _a$component,
children = _a.children,
restProps = __rest$c(_a, ["prefixCls", "count", "className", "motionClassName", "style", "title", "show", "component", "children"]);
var _React$useContext = React.useContext(ConfigContext),
getPrefixCls = _React$useContext.getPrefixCls;
var prefixCls = getPrefixCls('scroll-number', customizePrefixCls);
// ============================ Render ============================
var newProps = _extends$1(_extends$1({}, restProps), {
'data-show': show,
style: style,
className: classNames(prefixCls, className, motionClassName),
title: title
});
// Only integer need motion
var numberNodes = count;
if (count && Number(count) % 1 === 0) {
var numberList = String(count).split('');
numberNodes = numberList.map(function (num, i) {
return /*#__PURE__*/React.createElement(SingleNumber, {
prefixCls: prefixCls,
count: Number(count),
value: num,
// eslint-disable-next-line react/no-array-index-key
key: numberList.length - i
});
});
}
// allow specify the border
// mock border-color by box-shadow for compatible with old usage:
// <Badge count={4} style={{ backgroundColor: '#fff', color: '#999', borderColor: '#d9d9d9' }} />
if (style && style.borderColor) {
newProps.style = _extends$1(_extends$1({}, style), {
boxShadow: "0 0 0 1px " + style.borderColor + " inset"
});
}
if (children) {
return cloneElement(children, function (oriProps) {
return {
className: classNames(prefixCls + "-custom-component", oriProps === null || oriProps === void 0 ? void 0 : oriProps.className, motionClassName)
};
});
}
return /*#__PURE__*/React.createElement(component, newProps, numberNodes);
};
var ScrollNumber$1 = ScrollNumber;
var __rest$b = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var Badge = function Badge(_a) {
var _classNames, _classNames2;
var customizePrefixCls = _a.prefixCls,
customizeScrollNumberPrefixCls = _a.scrollNumberPrefixCls,
children = _a.children,
status = _a.status,
text = _a.text,
color = _a.color,
_a$count = _a.count,
count = _a$count === void 0 ? null : _a$count,
_a$overflowCount = _a.overflowCount,
overflowCount = _a$overflowCount === void 0 ? 99 : _a$overflowCount,
_a$dot = _a.dot,
dot = _a$dot === void 0 ? false : _a$dot,
_a$size = _a.size,
size = _a$size === void 0 ? 'default' : _a$size,
title = _a.title,
offset = _a.offset,
style = _a.style,
className = _a.className,
_a$showZero = _a.showZero,
showZero = _a$showZero === void 0 ? false : _a$showZero,
restProps = __rest$b(_a, ["prefixCls", "scrollNumberPrefixCls", "children", "status", "text", "color", "count", "overflowCount", "dot", "size", "title", "offset", "style", "className", "showZero"]);
var _React$useContext = React.useContext(ConfigContext),
getPrefixCls = _React$useContext.getPrefixCls,
direction = _React$useContext.direction;
var prefixCls = getPrefixCls('badge', customizePrefixCls);
// Style
var _useStyle = useStyle$5(prefixCls),
_useStyle2 = _slicedToArray(_useStyle, 2),
wrapSSR = _useStyle2[0],
hashId = _useStyle2[1];
// ================================ Misc ================================
var numberedDisplayCount = count > overflowCount ? overflowCount + "+" : count;
var isZero = numberedDisplayCount === '0' || numberedDisplayCount === 0;
var ignoreCount = count === null || isZero && !showZero;
var hasStatus = (status !== null && status !== undefined || color !== null && color !== undefined) && ignoreCount;
var showAsDot = dot && !isZero;
var mergedCount = showAsDot ? '' : numberedDisplayCount;
var isHidden = useMemo$1(function () {
var isEmpty = mergedCount === null || mergedCount === undefined || mergedCount === '';
return (isEmpty || isZero && !showZero) && !showAsDot;
}, [mergedCount, isZero, showZero, showAsDot]);
// Count should be cache in case hidden change it
var countRef = useRef(count);
if (!isHidden) {
countRef.current = count;
}
var livingCount = countRef.current;
// We need cache count since remove motion should not change count display
var displayCountRef = useRef(mergedCount);
if (!isHidden) {
displayCountRef.current = mergedCount;
}
var displayCount = displayCountRef.current;
// We will cache the dot status to avoid shaking on leaved motion
var isDotRef = useRef(showAsDot);
if (!isHidden) {
isDotRef.current = showAsDot;
}
// =============================== Styles ===============================
var mergedStyle = useMemo$1(function () {
if (!offset) {
return _extends$1({}, style);
}
var offsetStyle = {
marginTop: offset[1]
};
if (direction === 'rtl') {
offsetStyle.left = parseInt(offset[0], 10);
} else {
offsetStyle.right = -parseInt(offset[0], 10);
}
return _extends$1(_extends$1({}, offsetStyle), style);
}, [direction, offset, style]);
// =============================== Render ===============================
// >>> Title
var titleNode = title !== null && title !== void 0 ? title : typeof livingCount === 'string' || typeof livingCount === 'number' ? livingCount : undefined;
// >>> Status Text
var statusTextNode = isHidden || !text ? null : /*#__PURE__*/React.createElement("span", {
className: prefixCls + "-status-text"
}, text);
// >>> Display Component
var displayNode = !livingCount || _typeof$1(livingCount) !== 'object' ? undefined : cloneElement(livingCount, function (oriProps) {
return {
style: _extends$1(_extends$1({}, mergedStyle), oriProps.style)
};
});
// Shared styles
var statusCls = classNames((_classNames = {}, _defineProperty$1(_classNames, prefixCls + "-status-dot", hasStatus), _defineProperty$1(_classNames, prefixCls + "-status-" + status, !!status), _defineProperty$1(_classNames, prefixCls + "-status-" + color, isPresetColor(color)), _classNames));
var statusStyle = {};
if (color && !isPresetColor(color)) {
statusStyle.color = color;
statusStyle.background = color;
}
var badgeClassName = classNames(prefixCls, (_classNames2 = {}, _defineProperty$1(_classNames2, prefixCls + "-status", hasStatus), _defineProperty$1(_classNames2, prefixCls + "-not-a-wrapper", !children), _defineProperty$1(_classNames2, prefixCls + "-rtl", direction === 'rtl'), _classNames2), className);
// <Badge status="success" />
if (!children && hasStatus) {
var statusTextColor = mergedStyle.color;
return wrapSSR( /*#__PURE__*/React.createElement("span", _extends$1({}, restProps, {
className: classNames(badgeClassName, hashId),
style: mergedStyle
}), /*#__PURE__*/React.createElement("span", {
className: statusCls,
style: statusStyle
}), text && /*#__PURE__*/React.createElement("span", {
style: {
color: statusTextColor
},
className: prefixCls + "-status-text"
}, text)));
}
// <Badge status="success" count={<Icon type="xxx" />}></Badge>
return wrapSSR( /*#__PURE__*/React.createElement("span", _extends$1({}, restProps, {
className: classNames(badgeClassName, hashId)
}), children, /*#__PURE__*/React.createElement(CSSMotion, {
visible: !isHidden,
motionName: prefixCls + "-zoom",
motionAppear: false,
motionDeadline: 1000
}, function (_ref) {
var _classNames3;
var motionClassName = _ref.className;
var scrollNumberPrefixCls = getPrefixCls('scroll-number', customizeScrollNumberPrefixCls);
var isDot = isDotRef.current;
var scrollNumberCls = classNames((_classNames3 = {}, _defineProperty$1(_classNames3, prefixCls + "-dot", isDot), _defineProperty$1(_classNames3, prefixCls + "-count", !isDot), _defineProperty$1(_classNames3, prefixCls + "-count-sm", size === 'small'), _defineProperty$1(_classNames3, prefixCls + "-multiple-words", !isDot && displayCount && displayCount.toString().length > 1), _defineProperty$1(_classNames3, prefixCls + "-status-" + status, !!status), _defineProperty$1(_classNames3, prefixCls + "-status-" + color, isPresetColor(color)), _classNames3));
var scrollNumberStyle = _extends$1({}, mergedStyle);
if (color && !isPresetColor(color)) {
scrollNumberStyle = scrollNumberStyle || {};
scrollNumberStyle.background = color;
}
return /*#__PURE__*/React.createElement(ScrollNumber$1, {
prefixCls: scrollNumberPrefixCls,
show: !isHidden,
motionClassName: motionClassName,
className: scrollNumberCls,
count: displayCount,
title: titleNode,
style: scrollNumberStyle,
key: "scrollNumber"
}, displayNode);
}), statusTextNode));
};
Badge.Ribbon = Ribbon$1;
var Badge$1 = Badge;
var IdContext = /*#__PURE__*/React.createContext(null);
function getMenuId(uuid, eventKey) {
if (uuid === undefined) {
return null;
}
return "".concat(uuid, "-").concat(eventKey);
}
/**
* Get `data-menu-id`
*/
function useMenuId(eventKey) {
var id = React.useContext(IdContext);
return getMenuId(id, eventKey);
}
var _excluded$8 = ["children", "locked"];
var MenuContext$2 = /*#__PURE__*/React.createContext(null);
function mergeProps(origin, target) {
var clone = _objectSpread2$1({}, origin);
Object.keys(target).forEach(function (key) {
var value = target[key];
if (value !== undefined) {
clone[key] = value;
}
});
return clone;
}
function InheritableContextProvider(_ref) {
var children = _ref.children,
locked = _ref.locked,
restProps = _objectWithoutProperties(_ref, _excluded$8);
var context = React.useContext(MenuContext$2);
var inheritableContext = useMemo(function () {
return mergeProps(context, restProps);
}, [context, restProps], function (prev, next) {
return !locked && (prev[0] !== next[0] || !isEqual(prev[1], next[1], true));
});
return /*#__PURE__*/React.createElement(MenuContext$2.Provider, {
value: inheritableContext
}, children);
}
var EmptyList = [];
// ========================= Path Register =========================
var PathRegisterContext = /*#__PURE__*/React.createContext(null);
function useMeasure() {
return React.useContext(PathRegisterContext);
}
// ========================= Path Tracker ==========================
var PathTrackerContext = /*#__PURE__*/React.createContext(EmptyList);
function useFullPath(eventKey) {
var parentKeyPath = React.useContext(PathTrackerContext);
return React.useMemo(function () {
return eventKey !== undefined ? [].concat(_toConsumableArray(parentKeyPath), [eventKey]) : parentKeyPath;
}, [parentKeyPath, eventKey]);
}
// =========================== Path User ===========================
var PathUserContext = /*#__PURE__*/React.createContext(null);
var PrivateContext = /*#__PURE__*/React.createContext({});
function focusable(node) {
var includePositive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (isVisible(node)) {
var nodeName = node.nodeName.toLowerCase();
var isFocusableElement =
// Focusable element
['input', 'select', 'textarea', 'button'].includes(nodeName) ||
// Editable element
node.isContentEditable ||
// Anchor with href element
nodeName === 'a' && !!node.getAttribute('href');
// Get tabIndex
var tabIndexAttr = node.getAttribute('tabindex');
var tabIndexNum = Number(tabIndexAttr);
// Parse as number if validate
var tabIndex = null;
if (tabIndexAttr && !Number.isNaN(tabIndexNum)) {
tabIndex = tabIndexNum;
} else if (isFocusableElement && tabIndex === null) {
tabIndex = 0;
}
// Block focusable if disabled
if (isFocusableElement && node.disabled) {
tabIndex = null;
}
return tabIndex !== null && (tabIndex >= 0 || includePositive && tabIndex < 0);
}
return false;
}
function getFocusNodeList(node) {
var includePositive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var res = _toConsumableArray(node.querySelectorAll('*')).filter(function (child) {
return focusable(child, includePositive);
});
if (focusable(node, includePositive)) {
res.unshift(node);
}
return res;
}
// destruct to reduce minify size
var LEFT = KeyCode.LEFT,
RIGHT = KeyCode.RIGHT,
UP = KeyCode.UP,
DOWN = KeyCode.DOWN,
ENTER = KeyCode.ENTER,
ESC$1 = KeyCode.ESC,
HOME = KeyCode.HOME,
END = KeyCode.END;
var ArrowKeys = [UP, DOWN, LEFT, RIGHT];
function getOffset(mode, isRootLevel, isRtl, which) {
var _inline, _horizontal, _vertical, _offsets;
var prev = 'prev';
var next = 'next';
var children = 'children';
var parent = 'parent';
// Inline enter is special that we use unique operation
if (mode === 'inline' && which === ENTER) {
return {
inlineTrigger: true
};
}
var inline = (_inline = {}, _defineProperty$1(_inline, UP, prev), _defineProperty$1(_inline, DOWN, next), _inline);
var horizontal = (_horizontal = {}, _defineProperty$1(_horizontal, LEFT, isRtl ? next : prev), _defineProperty$1(_horizontal, RIGHT, isRtl ? prev : next), _defineProperty$1(_horizontal, DOWN, children), _defineProperty$1(_horizontal, ENTER, children), _horizontal);
var vertical = (_vertical = {}, _defineProperty$1(_vertical, UP, prev), _defineProperty$1(_vertical, DOWN, next), _defineProperty$1(_vertical, ENTER, children), _defineProperty$1(_vertical, ESC$1, parent), _defineProperty$1(_vertical, LEFT, isRtl ? children : parent), _defineProperty$1(_vertical, RIGHT, isRtl ? parent : children), _vertical);
var offsets = {
inline: inline,
horizontal: horizontal,
vertical: vertical,
inlineSub: inline,
horizontalSub: vertical,
verticalSub: vertical
};
var type = (_offsets = offsets["".concat(mode).concat(isRootLevel ? '' : 'Sub')]) === null || _offsets === void 0 ? void 0 : _offsets[which];
switch (type) {
case prev:
return {
offset: -1,
sibling: true
};
case next:
return {
offset: 1,
sibling: true
};
case parent:
return {
offset: -1,
sibling: false
};
case children:
return {
offset: 1,
sibling: false
};
default:
return null;
}
}
function findContainerUL(element) {
var current = element;
while (current) {
if (current.getAttribute('data-menu-list')) {
return current;
}
current = current.parentElement;
}
// Normally should not reach this line
/* istanbul ignore next */
return null;
}
/**
* Find focused element within element set provided
*/
function getFocusElement(activeElement, elements) {
var current = activeElement || document.activeElement;
while (current) {
if (elements.has(current)) {
return current;
}
current = current.parentElement;
}
return null;
}
/**
* Get focusable elements from the element set under provided container
*/
function getFocusableElements(container, elements) {
var list = getFocusNodeList(container, true);
return list.filter(function (ele) {
return elements.has(ele);
});
}
function getNextFocusElement(parentQueryContainer, elements, focusMenuElement) {
var offset = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;
// Key on the menu item will not get validate parent container
if (!parentQueryContainer) {
return null;
}
// List current level menu item elements
var sameLevelFocusableMenuElementList = getFocusableElements(parentQueryContainer, elements);
// Find next focus index
var count = sameLevelFocusableMenuElementList.length;
var focusIndex = sameLevelFocusableMenuElementList.findIndex(function (ele) {
return focusMenuElement === ele;
});
if (offset < 0) {
if (focusIndex === -1) {
focusIndex = count - 1;
} else {
focusIndex -= 1;
}
} else if (offset > 0) {
focusIndex += 1;
}
focusIndex = (focusIndex + count) % count;
// Focus menu item
return sameLevelFocusableMenuElementList[focusIndex];
}
function useAccessibility$1(mode, activeKey, isRtl, id, containerRef, getKeys, getKeyPath, triggerActiveKey, triggerAccessibilityOpen, originOnKeyDown) {
var rafRef = React.useRef();
var activeRef = React.useRef();
activeRef.current = activeKey;
var cleanRaf = function cleanRaf() {
wrapperRaf$1.cancel(rafRef.current);
};
React.useEffect(function () {
return function () {
cleanRaf();
};
}, []);
return function (e) {
var which = e.which;
if ([].concat(ArrowKeys, [ENTER, ESC$1, HOME, END]).includes(which)) {
// Convert key to elements
var elements;
var key2element;
var element2key;
// >>> Wrap as function since we use raf for some case
var refreshElements = function refreshElements() {
elements = new Set();
key2element = new Map();
element2key = new Map();
var keys = getKeys();
keys.forEach(function (key) {
var element = document.querySelector("[data-menu-id='".concat(getMenuId(id, key), "']"));
if (element) {
elements.add(element);
element2key.set(element, key);
key2element.set(key, element);
}
});
return elements;
};
refreshElements();
// First we should find current focused MenuItem/SubMenu element
var activeElement = key2element.get(activeKey);
var focusMenuElement = getFocusElement(activeElement, elements);
var focusMenuKey = element2key.get(focusMenuElement);
var offsetObj = getOffset(mode, getKeyPath(focusMenuKey, true).length === 1, isRtl, which);
// Some mode do not have fully arrow operation like inline
if (!offsetObj && which !== HOME && which !== END) {
return;
}
// Arrow prevent default to avoid page scroll
if (ArrowKeys.includes(which) || [HOME, END].includes(which)) {
e.preventDefault();
}
var tryFocus = function tryFocus(menuElement) {
if (menuElement) {
var focusTargetElement = menuElement;
// Focus to link instead of menu item if possible
var link = menuElement.querySelector('a');
if (link !== null && link !== void 0 && link.getAttribute('href')) {
focusTargetElement = link;
}
var targetKey = element2key.get(menuElement);
triggerActiveKey(targetKey);
/**
* Do not `useEffect` here since `tryFocus` may trigger async
* which makes React sync update the `activeKey`
* that force render before `useRef` set the next activeKey
*/
cleanRaf();
rafRef.current = wrapperRaf$1(function () {
if (activeRef.current === targetKey) {
focusTargetElement.focus();
}
});
}
};
if ([HOME, END].includes(which) || offsetObj.sibling || !focusMenuElement) {
// ========================== Sibling ==========================
// Find walkable focus menu element container
var parentQueryContainer;
if (!focusMenuElement || mode === 'inline') {
parentQueryContainer = containerRef.current;
} else {
parentQueryContainer = findContainerUL(focusMenuElement);
}
// Get next focus element
var targetElement;
var focusableElements = getFocusableElements(parentQueryContainer, elements);
if (which === HOME) {
targetElement = focusableElements[0];
} else if (which === END) {
targetElement = focusableElements[focusableElements.length - 1];
} else {
targetElement = getNextFocusElement(parentQueryContainer, elements, focusMenuElement, offsetObj.offset);
}
// Focus menu item
tryFocus(targetElement);
// ======================= InlineTrigger =======================
} else if (offsetObj.inlineTrigger) {
// Inline trigger no need switch to sub menu item
triggerAccessibilityOpen(focusMenuKey);
// =========================== Level ===========================
} else if (offsetObj.offset > 0) {
triggerAccessibilityOpen(focusMenuKey, true);
cleanRaf();
rafRef.current = wrapperRaf$1(function () {
// Async should resync elements
refreshElements();
var controlId = focusMenuElement.getAttribute('aria-controls');
var subQueryContainer = document.getElementById(controlId);
// Get sub focusable menu item
var targetElement = getNextFocusElement(subQueryContainer, elements);
// Focus menu item
tryFocus(targetElement);
}, 5);
} else if (offsetObj.offset < 0) {
var keyPath = getKeyPath(focusMenuKey, true);
var parentKey = keyPath[keyPath.length - 2];
var parentMenuElement = key2element.get(parentKey);
// Focus menu item
triggerAccessibilityOpen(parentKey, false);
tryFocus(parentMenuElement);
}
}
// Pass origin key down event
originOnKeyDown === null || originOnKeyDown === void 0 ? void 0 : originOnKeyDown(e);
};
}
function nextSlice(callback) {
/* istanbul ignore next */
Promise.resolve().then(callback);
}
var PATH_SPLIT = '__RC_UTIL_PATH_SPLIT__';
var getPathStr = function getPathStr(keyPath) {
return keyPath.join(PATH_SPLIT);
};
var getPathKeys = function getPathKeys(keyPathStr) {
return keyPathStr.split(PATH_SPLIT);
};
var OVERFLOW_KEY = 'rc-menu-more';
function useKeyRecords() {
var _React$useState = React.useState({}),
_React$useState2 = _slicedToArray(_React$useState, 2),
internalForceUpdate = _React$useState2[1];
var key2pathRef = useRef(new Map());
var path2keyRef = useRef(new Map());
var _React$useState3 = React.useState([]),
_React$useState4 = _slicedToArray(_React$useState3, 2),
overflowKeys = _React$useState4[0],
setOverflowKeys = _React$useState4[1];
var updateRef = useRef(0);
var destroyRef = useRef(false);
var forceUpdate = function forceUpdate() {
if (!destroyRef.current) {
internalForceUpdate({});
}
};
var registerPath = useCallback(function (key, keyPath) {
// Warning for invalidate or duplicated `key`
if (process.env.NODE_ENV !== 'production') {
warningOnce(!key2pathRef.current.has(key), "Duplicated key '".concat(key, "' used in Menu by path [").concat(keyPath.join(' > '), "]"));
}
// Fill map
var connectedPath = getPathStr(keyPath);
path2keyRef.current.set(connectedPath, key);
key2pathRef.current.set(key, connectedPath);
updateRef.current += 1;
var id = updateRef.current;
nextSlice(function () {
if (id === updateRef.current) {
forceUpdate();
}
});
}, []);
var unregisterPath = useCallback(function (key, keyPath) {
var connectedPath = getPathStr(keyPath);
path2keyRef.current.delete(connectedPath);
key2pathRef.current.delete(key);
}, []);
var refreshOverflowKeys = useCallback(function (keys) {
setOverflowKeys(keys);
}, []);
var getKeyPath = useCallback(function (eventKey, includeOverflow) {
var fullPath = key2pathRef.current.get(eventKey) || '';
var keys = getPathKeys(fullPath);
if (includeOverflow && overflowKeys.includes(keys[0])) {
keys.unshift(OVERFLOW_KEY);
}
return keys;
}, [overflowKeys]);
var isSubPathKey = useCallback(function (pathKeys, eventKey) {
return pathKeys.some(function (pathKey) {
var pathKeyList = getKeyPath(pathKey, true);
return pathKeyList.includes(eventKey);
});
}, [getKeyPath]);
var getKeys = function getKeys() {
var keys = _toConsumableArray(key2pathRef.current.keys());
if (overflowKeys.length) {
keys.push(OVERFLOW_KEY);
}
return keys;
};
/**
* Find current key related child path keys
*/
var getSubPathKeys = useCallback(function (key) {
var connectedPath = "".concat(key2pathRef.current.get(key)).concat(PATH_SPLIT);
var pathKeys = new Set();
_toConsumableArray(path2keyRef.current.keys()).forEach(function (pathKey) {
if (pathKey.startsWith(connectedPath)) {
pathKeys.add(path2keyRef.current.get(pathKey));
}
});
return pathKeys;
}, []);
React.useEffect(function () {
return function () {
destroyRef.current = true;
};
}, []);
return {
// Register
registerPath: registerPath,
unregisterPath: unregisterPath,
refreshOverflowKeys: refreshOverflowKeys,
// Util
isSubPathKey: isSubPathKey,
getKeyPath: getKeyPath,
getKeys: getKeys,
getSubPathKeys: getSubPathKeys
};
}
/**
* Cache callback function that always return same ref instead.
* This is used for context optimization.
*/
function useMemoCallback(func) {
var funRef = React.useRef(func);
funRef.current = func;
var callback = React.useCallback(function () {
var _funRef$current;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return (_funRef$current = funRef.current) === null || _funRef$current === void 0 ? void 0 : _funRef$current.call.apply(_funRef$current, [funRef].concat(args));
}, []);
return func ? callback : undefined;
}
var uniquePrefix = Math.random().toFixed(5).toString().slice(2);
var internalId = 0;
function useUUID(id) {
var _useMergedState = useMergedState(id, {
value: id
}),
_useMergedState2 = _slicedToArray(_useMergedState, 2),
uuid = _useMergedState2[0],
setUUID = _useMergedState2[1];
React.useEffect(function () {
internalId += 1;
var newId = process.env.NODE_ENV === 'test' ? 'test' : "".concat(uniquePrefix, "-").concat(internalId);
setUUID("rc-menu-uuid-".concat(newId));
}, []);
return uuid;
}
function useActive(eventKey, disabled, onMouseEnter, onMouseLeave) {
var _React$useContext = React.useContext(MenuContext$2),
activeKey = _React$useContext.activeKey,
onActive = _React$useContext.onActive,
onInactive = _React$useContext.onInactive;
var ret = {
active: activeKey === eventKey
};
// Skip when disabled
if (!disabled) {
ret.onMouseEnter = function (domEvent) {
onMouseEnter === null || onMouseEnter === void 0 ? void 0 : onMouseEnter({
key: eventKey,
domEvent: domEvent
});
onActive(eventKey);
};
ret.onMouseLeave = function (domEvent) {
onMouseLeave === null || onMouseLeave === void 0 ? void 0 : onMouseLeave({
key: eventKey,
domEvent: domEvent
});
onInactive(eventKey);
};
}
return ret;
}
function useDirectionStyle(level) {
var _React$useContext = React.useContext(MenuContext$2),
mode = _React$useContext.mode,
rtl = _React$useContext.rtl,
inlineIndent = _React$useContext.inlineIndent;
if (mode !== 'inline') {
return null;
}
var len = level;
return rtl ? {
paddingRight: len * inlineIndent
} : {
paddingLeft: len * inlineIndent
};
}
function Icon(_ref) {
var icon = _ref.icon,
props = _ref.props,
children = _ref.children;
var iconNode;
if (typeof icon === 'function') {
iconNode = /*#__PURE__*/React.createElement(icon, _objectSpread2$1({}, props));
} else {
// Compatible for origin definition
iconNode = icon;
}
return iconNode || children || null;
}
var _excluded$7 = ["item"];
/**
* `onClick` event return `info.item` which point to react node directly.
* We should warning this since it will not work on FC.
*/
function warnItemProp(_ref) {
var item = _ref.item,
restInfo = _objectWithoutProperties(_ref, _excluded$7);
Object.defineProperty(restInfo, 'item', {
get: function get() {
warningOnce(false, '`info.item` is deprecated since we will move to function component that not provides React Node instance in future.');
return item;
}
});
return restInfo;
}
var _excluded$6 = ["title", "attribute", "elementRef"],
_excluded2$2 = ["style", "className", "eventKey", "warnKey", "disabled", "itemIcon", "children", "role", "onMouseEnter", "onMouseLeave", "onClick", "onKeyDown", "onFocus"],
_excluded3 = ["active"];
// Since Menu event provide the `info.item` which point to the MenuItem node instance.
// We have to use class component here.
// This should be removed from doc & api in future.
var LegacyMenuItem = /*#__PURE__*/function (_React$Component) {
_inherits(LegacyMenuItem, _React$Component);
var _super = _createSuper(LegacyMenuItem);
function LegacyMenuItem() {
_classCallCheck(this, LegacyMenuItem);
return _super.apply(this, arguments);
}
_createClass(LegacyMenuItem, [{
key: "render",
value: function render() {
var _this$props = this.props,
title = _this$props.title,
attribute = _this$props.attribute,
elementRef = _this$props.elementRef,
restProps = _objectWithoutProperties(_this$props, _excluded$6);
// Here the props are eventually passed to the DOM element.
// React does not recognize non-standard attributes.
// Therefore, remove the props that is not used here.
// ref: https://github.com/ant-design/ant-design/issues/41395
var passedProps = omit(restProps, ['eventKey', 'popupClassName', 'popupOffset', 'onTitleClick']);
warningOnce(!attribute, '`attribute` of Menu.Item is deprecated. Please pass attribute directly.');
return /*#__PURE__*/React.createElement(ForwardOverflow.Item, _extends$1({}, attribute, {
title: typeof title === 'string' ? title : undefined
}, passedProps, {
ref: elementRef
}));
}
}]);
return LegacyMenuItem;
}(React.Component);
/**
* Real Menu Item component
*/
var InternalMenuItem = /*#__PURE__*/React.forwardRef(function (props, ref) {
var _classNames;
var style = props.style,
className = props.className,
eventKey = props.eventKey,
warnKey = props.warnKey,
disabled = props.disabled,
itemIcon = props.itemIcon,
children = props.children,
role = props.role,
onMouseEnter = props.onMouseEnter,
onMouseLeave = props.onMouseLeave,
onClick = props.onClick,
onKeyDown = props.onKeyDown,
onFocus = props.onFocus,
restProps = _objectWithoutProperties(props, _excluded2$2);
var domDataId = useMenuId(eventKey);
var _React$useContext = React.useContext(MenuContext$2),
prefixCls = _React$useContext.prefixCls,
onItemClick = _React$useContext.onItemClick,
contextDisabled = _React$useContext.disabled,
overflowDisabled = _React$useContext.overflowDisabled,
contextItemIcon = _React$useContext.itemIcon,
selectedKeys = _React$useContext.selectedKeys,
onActive = _React$useContext.onActive;
var _React$useContext2 = React.useContext(PrivateContext),
_internalRenderMenuItem = _React$useContext2._internalRenderMenuItem;
var itemCls = "".concat(prefixCls, "-item");
var legacyMenuItemRef = React.useRef();
var elementRef = React.useRef();
var mergedDisabled = contextDisabled || disabled;
var mergedEleRef = useComposeRef(ref, elementRef);
var connectedKeys = useFullPath(eventKey);
// ================================ Warn ================================
if (process.env.NODE_ENV !== 'production' && warnKey) {
warningOnce(false, 'MenuItem should not leave undefined `key`.');
}
// ============================= Info =============================
var getEventInfo = function getEventInfo(e) {
return {
key: eventKey,
// Note: For legacy code is reversed which not like other antd component
keyPath: _toConsumableArray(connectedKeys).reverse(),
item: legacyMenuItemRef.current,
domEvent: e
};
};
// ============================= Icon =============================
var mergedItemIcon = itemIcon || contextItemIcon;
// ============================ Active ============================
var _useActive = useActive(eventKey, mergedDisabled, onMouseEnter, onMouseLeave),
active = _useActive.active,
activeProps = _objectWithoutProperties(_useActive, _excluded3);
// ============================ Select ============================
var selected = selectedKeys.includes(eventKey);
// ======================== DirectionStyle ========================
var directionStyle = useDirectionStyle(connectedKeys.length);
// ============================ Events ============================
var onInternalClick = function onInternalClick(e) {
if (mergedDisabled) {
return;
}
var info = getEventInfo(e);
onClick === null || onClick === void 0 ? void 0 : onClick(warnItemProp(info));
onItemClick(info);
};
var onInternalKeyDown = function onInternalKeyDown(e) {
onKeyDown === null || onKeyDown === void 0 ? void 0 : onKeyDown(e);
if (e.which === KeyCode.ENTER) {
var info = getEventInfo(e);
// Legacy. Key will also trigger click event
onClick === null || onClick === void 0 ? void 0 : onClick(warnItemProp(info));
onItemClick(info);
}
};
/**
* Used for accessibility. Helper will focus element without key board.
* We should manually trigger an active
*/
var onInternalFocus = function onInternalFocus(e) {
onActive(eventKey);
onFocus === null || onFocus === void 0 ? void 0 : onFocus(e);
};
// ============================ Render ============================
var optionRoleProps = {};
if (props.role === 'option') {
optionRoleProps['aria-selected'] = selected;
}
var renderNode = /*#__PURE__*/React.createElement(LegacyMenuItem, _extends$1({
ref: legacyMenuItemRef,
elementRef: mergedEleRef,
role: role === null ? 'none' : role || 'menuitem',
tabIndex: disabled ? null : -1,
"data-menu-id": overflowDisabled && domDataId ? null : domDataId
}, restProps, activeProps, optionRoleProps, {
component: "li",
"aria-disabled": disabled,
style: _objectSpread2$1(_objectSpread2$1({}, directionStyle), style),
className: classNames(itemCls, (_classNames = {}, _defineProperty$1(_classNames, "".concat(itemCls, "-active"), active), _defineProperty$1(_classNames, "".concat(itemCls, "-selected"), selected), _defineProperty$1(_classNames, "".concat(itemCls, "-disabled"), mergedDisabled), _classNames), className),
onClick: onInternalClick,
onKeyDown: onInternalKeyDown,
onFocus: onInternalFocus
}), children, /*#__PURE__*/React.createElement(Icon, {
props: _objectSpread2$1(_objectSpread2$1({}, props), {}, {
isSelected: selected
}),
icon: mergedItemIcon
}));
if (_internalRenderMenuItem) {
renderNode = _internalRenderMenuItem(renderNode, props, {
selected: selected
});
}
return renderNode;
});
function MenuItem$1(props, ref) {
var eventKey = props.eventKey;
// ==================== Record KeyPath ====================
var measure = useMeasure();
var connectedKeyPath = useFullPath(eventKey);
// eslint-disable-next-line consistent-return
React.useEffect(function () {
if (measure) {
measure.registerPath(eventKey, connectedKeyPath);
return function () {
measure.unregisterPath(eventKey, connectedKeyPath);
};
}
}, [connectedKeyPath]);
if (measure) {
return null;
}
// ======================== Render ========================
return /*#__PURE__*/React.createElement(InternalMenuItem, _extends$1({}, props, {
ref: ref
}));
}
var MenuItem$2 = /*#__PURE__*/React.forwardRef(MenuItem$1);
var _excluded$5 = ["className", "children"];
var InternalSubMenuList = function InternalSubMenuList(_ref, ref) {
var className = _ref.className,
children = _ref.children,
restProps = _objectWithoutProperties(_ref, _excluded$5);
var _React$useContext = React.useContext(MenuContext$2),
prefixCls = _React$useContext.prefixCls,
mode = _React$useContext.mode,
rtl = _React$useContext.rtl;
return /*#__PURE__*/React.createElement("ul", _extends$1({
className: classNames(prefixCls, rtl && "".concat(prefixCls, "-rtl"), "".concat(prefixCls, "-sub"), "".concat(prefixCls, "-").concat(mode === 'inline' ? 'inline' : 'vertical'), className),
role: "menu"
}, restProps, {
"data-menu-list": true,
ref: ref
}), children);
};
var SubMenuList = /*#__PURE__*/React.forwardRef(InternalSubMenuList);
SubMenuList.displayName = 'SubMenuList';
var _excluded$4 = ["label", "children", "key", "type"];
function parseChildren(children, keyPath) {
return toArray$1(children).map(function (child, index) {
if ( /*#__PURE__*/React.isValidElement(child)) {
var _eventKey, _child$props;
var key = child.key;
var eventKey = (_eventKey = (_child$props = child.props) === null || _child$props === void 0 ? void 0 : _child$props.eventKey) !== null && _eventKey !== void 0 ? _eventKey : key;
var emptyKey = eventKey === null || eventKey === undefined;
if (emptyKey) {
eventKey = "tmp_key-".concat([].concat(_toConsumableArray(keyPath), [index]).join('-'));
}
var cloneProps = {
key: eventKey,
eventKey: eventKey
};
if (process.env.NODE_ENV !== 'production' && emptyKey) {
cloneProps.warnKey = true;
}
return /*#__PURE__*/React.cloneElement(child, cloneProps);
}
return child;
});
}
function convertItemsToNodes$1(list) {
return (list || []).map(function (opt, index) {
if (opt && _typeof$1(opt) === 'object') {
var _ref = opt,
label = _ref.label,
children = _ref.children,
key = _ref.key,
type = _ref.type,
restProps = _objectWithoutProperties(_ref, _excluded$4);
var mergedKey = key !== null && key !== void 0 ? key : "tmp-".concat(index);
// MenuItemGroup & SubMenuItem
if (children || type === 'group') {
if (type === 'group') {
// Group
return /*#__PURE__*/React.createElement(MenuItemGroup, _extends$1({
key: mergedKey
}, restProps, {
title: label
}), convertItemsToNodes$1(children));
}
// Sub Menu
return /*#__PURE__*/React.createElement(SubMenu$1, _extends$1({
key: mergedKey
}, restProps, {
title: label
}), convertItemsToNodes$1(children));
}
// MenuItem & Divider
if (type === 'divider') {
return /*#__PURE__*/React.createElement(Divider, _extends$1({
key: mergedKey
}, restProps));
}
return /*#__PURE__*/React.createElement(MenuItem$2, _extends$1({
key: mergedKey
}, restProps), label);
}
return null;
}).filter(function (opt) {
return opt;
});
}
function parseItems(children, items, keyPath) {
var childNodes = children;
if (items) {
childNodes = convertItemsToNodes$1(items);
}
return parseChildren(childNodes, keyPath);
}
var autoAdjustOverflow$1 = {
adjustX: 1,
adjustY: 1
};
var placements$1 = {
topLeft: {
points: ['bl', 'tl'],
overflow: autoAdjustOverflow$1,
offset: [0, -7]
},
bottomLeft: {
points: ['tl', 'bl'],
overflow: autoAdjustOverflow$1,
offset: [0, 7]
},
leftTop: {
points: ['tr', 'tl'],
overflow: autoAdjustOverflow$1,
offset: [-4, 0]
},
rightTop: {
points: ['tl', 'tr'],
overflow: autoAdjustOverflow$1,
offset: [4, 0]
}
};
var placementsRtl = {
topLeft: {
points: ['bl', 'tl'],
overflow: autoAdjustOverflow$1,
offset: [0, -7]
},
bottomLeft: {
points: ['tl', 'bl'],
overflow: autoAdjustOverflow$1,
offset: [0, 7]
},
rightTop: {
points: ['tr', 'tl'],
overflow: autoAdjustOverflow$1,
offset: [-4, 0]
},
leftTop: {
points: ['tl', 'tr'],
overflow: autoAdjustOverflow$1,
offset: [4, 0]
}
};
function getMotion(mode, motion, defaultMotions) {
if (motion) {
return motion;
}
if (defaultMotions) {
return defaultMotions[mode] || defaultMotions.other;
}
return undefined;
}
var popupPlacementMap = {
horizontal: 'bottomLeft',
vertical: 'rightTop',
'vertical-left': 'rightTop',
'vertical-right': 'leftTop'
};
function PopupTrigger(_ref) {
var prefixCls = _ref.prefixCls,
visible = _ref.visible,
children = _ref.children,
popup = _ref.popup,
popupClassName = _ref.popupClassName,
popupOffset = _ref.popupOffset,
disabled = _ref.disabled,
mode = _ref.mode,
onVisibleChange = _ref.onVisibleChange;
var _React$useContext = React.useContext(MenuContext$2),
getPopupContainer = _React$useContext.getPopupContainer,
rtl = _React$useContext.rtl,
subMenuOpenDelay = _React$useContext.subMenuOpenDelay,
subMenuCloseDelay = _React$useContext.subMenuCloseDelay,
builtinPlacements = _React$useContext.builtinPlacements,
triggerSubMenuAction = _React$useContext.triggerSubMenuAction,
forceSubMenuRender = _React$useContext.forceSubMenuRender,
rootClassName = _React$useContext.rootClassName,
motion = _React$useContext.motion,
defaultMotions = _React$useContext.defaultMotions;
var _React$useState = React.useState(false),
_React$useState2 = _slicedToArray(_React$useState, 2),
innerVisible = _React$useState2[0],
setInnerVisible = _React$useState2[1];
var placement = rtl ? _objectSpread2$1(_objectSpread2$1({}, placementsRtl), builtinPlacements) : _objectSpread2$1(_objectSpread2$1({}, placements$1), builtinPlacements);
var popupPlacement = popupPlacementMap[mode];
var targetMotion = getMotion(mode, motion, defaultMotions);
var targetMotionRef = React.useRef(targetMotion);
if (mode !== 'inline') {
/**
* PopupTrigger is only used for vertical and horizontal types.
* When collapsed is unfolded, the inline animation will destroy the vertical animation.
*/
targetMotionRef.current = targetMotion;
}
var mergedMotion = _objectSpread2$1(_objectSpread2$1({}, targetMotionRef.current), {}, {
leavedClassName: "".concat(prefixCls, "-hidden"),
removeOnLeave: false,
motionAppear: true
});
// Delay to change visible
var visibleRef = React.useRef();
React.useEffect(function () {
visibleRef.current = wrapperRaf$1(function () {
setInnerVisible(visible);
});
return function () {
wrapperRaf$1.cancel(visibleRef.current);
};
}, [visible]);
return /*#__PURE__*/React.createElement(Trigger, {
prefixCls: prefixCls,
popupClassName: classNames("".concat(prefixCls, "-popup"), _defineProperty$1({}, "".concat(prefixCls, "-rtl"), rtl), popupClassName, rootClassName),
stretch: mode === 'horizontal' ? 'minWidth' : null,
getPopupContainer: getPopupContainer,
builtinPlacements: placement,
popupPlacement: popupPlacement,
popupVisible: innerVisible,
popup: popup,
popupAlign: popupOffset && {
offset: popupOffset
},
action: disabled ? [] : [triggerSubMenuAction],
mouseEnterDelay: subMenuOpenDelay,
mouseLeaveDelay: subMenuCloseDelay,
onPopupVisibleChange: onVisibleChange,
forceRender: forceSubMenuRender,
popupMotion: mergedMotion
}, children);
}
function InlineSubMenuList(_ref) {
var id = _ref.id,
open = _ref.open,
keyPath = _ref.keyPath,
children = _ref.children;
var fixedMode = 'inline';
var _React$useContext = React.useContext(MenuContext$2),
prefixCls = _React$useContext.prefixCls,
forceSubMenuRender = _React$useContext.forceSubMenuRender,
motion = _React$useContext.motion,
defaultMotions = _React$useContext.defaultMotions,
mode = _React$useContext.mode;
// Always use latest mode check
var sameModeRef = React.useRef(false);
sameModeRef.current = mode === fixedMode;
// We record `destroy` mark here since when mode change from `inline` to others.
// The inline list should remove when motion end.
var _React$useState = React.useState(!sameModeRef.current),
_React$useState2 = _slicedToArray(_React$useState, 2),
destroy = _React$useState2[0],
setDestroy = _React$useState2[1];
var mergedOpen = sameModeRef.current ? open : false;
// ================================= Effect =================================
// Reset destroy state when mode change back
React.useEffect(function () {
if (sameModeRef.current) {
setDestroy(false);
}
}, [mode]);
// ================================= Render =================================
var mergedMotion = _objectSpread2$1({}, getMotion(fixedMode, motion, defaultMotions));
// No need appear since nest inlineCollapse changed
if (keyPath.length > 1) {
mergedMotion.motionAppear = false;
}
// Hide inline list when mode changed and motion end
var originOnVisibleChanged = mergedMotion.onVisibleChanged;
mergedMotion.onVisibleChanged = function (newVisible) {
if (!sameModeRef.current && !newVisible) {
setDestroy(true);
}
return originOnVisibleChanged === null || originOnVisibleChanged === void 0 ? void 0 : originOnVisibleChanged(newVisible);
};
if (destroy) {
return null;
}
return /*#__PURE__*/React.createElement(InheritableContextProvider, {
mode: fixedMode,
locked: !sameModeRef.current
}, /*#__PURE__*/React.createElement(CSSMotion, _extends$1({
visible: mergedOpen
}, mergedMotion, {
forceRender: forceSubMenuRender,
removeOnLeave: false,
leavedClassName: "".concat(prefixCls, "-hidden")
}), function (_ref2) {
var motionClassName = _ref2.className,
motionStyle = _ref2.style;
return /*#__PURE__*/React.createElement(SubMenuList, {
id: id,
className: motionClassName,
style: motionStyle
}, children);
}));
}
var _excluded$3 = ["style", "className", "title", "eventKey", "warnKey", "disabled", "internalPopupClose", "children", "itemIcon", "expandIcon", "popupClassName", "popupOffset", "onClick", "onMouseEnter", "onMouseLeave", "onTitleClick", "onTitleMouseEnter", "onTitleMouseLeave"],
_excluded2$1 = ["active"];
var InternalSubMenu = function InternalSubMenu(props) {
var _classNames;
var style = props.style,
className = props.className,
title = props.title,
eventKey = props.eventKey,
warnKey = props.warnKey,
disabled = props.disabled,
internalPopupClose = props.internalPopupClose,
children = props.children,
itemIcon = props.itemIcon,
expandIcon = props.expandIcon,
popupClassName = props.popupClassName,
popupOffset = props.popupOffset,
onClick = props.onClick,
onMouseEnter = props.onMouseEnter,
onMouseLeave = props.onMouseLeave,
onTitleClick = props.onTitleClick,
onTitleMouseEnter = props.onTitleMouseEnter,
onTitleMouseLeave = props.onTitleMouseLeave,
restProps = _objectWithoutProperties(props, _excluded$3);
var domDataId = useMenuId(eventKey);
var _React$useContext = React.useContext(MenuContext$2),
prefixCls = _React$useContext.prefixCls,
mode = _React$useContext.mode,
openKeys = _React$useContext.openKeys,
contextDisabled = _React$useContext.disabled,
overflowDisabled = _React$useContext.overflowDisabled,
activeKey = _React$useContext.activeKey,
selectedKeys = _React$useContext.selectedKeys,
contextItemIcon = _React$useContext.itemIcon,
contextExpandIcon = _React$useContext.expandIcon,
onItemClick = _React$useContext.onItemClick,
onOpenChange = _React$useContext.onOpenChange,
onActive = _React$useContext.onActive;
var _React$useContext2 = React.useContext(PrivateContext),
_internalRenderSubMenuItem = _React$useContext2._internalRenderSubMenuItem;
var _React$useContext3 = React.useContext(PathUserContext),
isSubPathKey = _React$useContext3.isSubPathKey;
var connectedPath = useFullPath();
var subMenuPrefixCls = "".concat(prefixCls, "-submenu");
var mergedDisabled = contextDisabled || disabled;
var elementRef = React.useRef();
var popupRef = React.useRef();
// ================================ Warn ================================
if (process.env.NODE_ENV !== 'production' && warnKey) {
warningOnce(false, 'SubMenu should not leave undefined `key`.');
}
// ================================ Icon ================================
var mergedItemIcon = itemIcon || contextItemIcon;
var mergedExpandIcon = expandIcon || contextExpandIcon;
// ================================ Open ================================
var originOpen = openKeys.includes(eventKey);
var open = !overflowDisabled && originOpen;
// =============================== Select ===============================
var childrenSelected = isSubPathKey(selectedKeys, eventKey);
// =============================== Active ===============================
var _useActive = useActive(eventKey, mergedDisabled, onTitleMouseEnter, onTitleMouseLeave),
active = _useActive.active,
activeProps = _objectWithoutProperties(_useActive, _excluded2$1);
// Fallback of active check to avoid hover on menu title or disabled item
var _React$useState = React.useState(false),
_React$useState2 = _slicedToArray(_React$useState, 2),
childrenActive = _React$useState2[0],
setChildrenActive = _React$useState2[1];
var triggerChildrenActive = function triggerChildrenActive(newActive) {
if (!mergedDisabled) {
setChildrenActive(newActive);
}
};
var onInternalMouseEnter = function onInternalMouseEnter(domEvent) {
triggerChildrenActive(true);
onMouseEnter === null || onMouseEnter === void 0 ? void 0 : onMouseEnter({
key: eventKey,
domEvent: domEvent
});
};
var onInternalMouseLeave = function onInternalMouseLeave(domEvent) {
triggerChildrenActive(false);
onMouseLeave === null || onMouseLeave === void 0 ? void 0 : onMouseLeave({
key: eventKey,
domEvent: domEvent
});
};
var mergedActive = React.useMemo(function () {
if (active) {
return active;
}
if (mode !== 'inline') {
return childrenActive || isSubPathKey([activeKey], eventKey);
}
return false;
}, [mode, active, activeKey, childrenActive, eventKey, isSubPathKey]);
// ========================== DirectionStyle ==========================
var directionStyle = useDirectionStyle(connectedPath.length);
// =============================== Events ===============================
// >>>> Title click
var onInternalTitleClick = function onInternalTitleClick(e) {
// Skip if disabled
if (mergedDisabled) {
return;
}
onTitleClick === null || onTitleClick === void 0 ? void 0 : onTitleClick({
key: eventKey,
domEvent: e
});
// Trigger open by click when mode is `inline`
if (mode === 'inline') {
onOpenChange(eventKey, !originOpen);
}
};
// >>>> Context for children click
var onMergedItemClick = useMemoCallback(function (info) {
onClick === null || onClick === void 0 ? void 0 : onClick(warnItemProp(info));
onItemClick(info);
});
// >>>>> Visible change
var onPopupVisibleChange = function onPopupVisibleChange(newVisible) {
if (mode !== 'inline') {
onOpenChange(eventKey, newVisible);
}
};
/**
* Used for accessibility. Helper will focus element without key board.
* We should manually trigger an active
*/
var onInternalFocus = function onInternalFocus() {
onActive(eventKey);
};
// =============================== Render ===============================
var popupId = domDataId && "".concat(domDataId, "-popup");
// >>>>> Title
var titleNode = /*#__PURE__*/React.createElement("div", _extends$1({
role: "menuitem",
style: directionStyle,
className: "".concat(subMenuPrefixCls, "-title"),
tabIndex: mergedDisabled ? null : -1,
ref: elementRef,
title: typeof title === 'string' ? title : null,
"data-menu-id": overflowDisabled && domDataId ? null : domDataId,
"aria-expanded": open,
"aria-haspopup": true,
"aria-controls": popupId,
"aria-disabled": mergedDisabled,
onClick: onInternalTitleClick,
onFocus: onInternalFocus
}, activeProps), title, /*#__PURE__*/React.createElement(Icon, {
icon: mode !== 'horizontal' ? mergedExpandIcon : null,
props: _objectSpread2$1(_objectSpread2$1({}, props), {}, {
isOpen: open,
// [Legacy] Not sure why need this mark
isSubMenu: true
})
}, /*#__PURE__*/React.createElement("i", {
className: "".concat(subMenuPrefixCls, "-arrow")
})));
// Cache mode if it change to `inline` which do not have popup motion
var triggerModeRef = React.useRef(mode);
if (mode !== 'inline' && connectedPath.length > 1) {
triggerModeRef.current = 'vertical';
} else {
triggerModeRef.current = mode;
}
if (!overflowDisabled) {
var triggerMode = triggerModeRef.current;
// Still wrap with Trigger here since we need avoid react re-mount dom node
// Which makes motion failed
titleNode = /*#__PURE__*/React.createElement(PopupTrigger, {
mode: triggerMode,
prefixCls: subMenuPrefixCls,
visible: !internalPopupClose && open && mode !== 'inline',
popupClassName: popupClassName,
popupOffset: popupOffset,
popup: /*#__PURE__*/React.createElement(InheritableContextProvider
// Special handle of horizontal mode
, {
mode: triggerMode === 'horizontal' ? 'vertical' : triggerMode
}, /*#__PURE__*/React.createElement(SubMenuList, {
id: popupId,
ref: popupRef
}, children)),
disabled: mergedDisabled,
onVisibleChange: onPopupVisibleChange
}, titleNode);
}
// >>>>> List node
var listNode = /*#__PURE__*/React.createElement(ForwardOverflow.Item, _extends$1({
role: "none"
}, restProps, {
component: "li",
style: style,
className: classNames(subMenuPrefixCls, "".concat(subMenuPrefixCls, "-").concat(mode), className, (_classNames = {}, _defineProperty$1(_classNames, "".concat(subMenuPrefixCls, "-open"), open), _defineProperty$1(_classNames, "".concat(subMenuPrefixCls, "-active"), mergedActive), _defineProperty$1(_classNames, "".concat(subMenuPrefixCls, "-selected"), childrenSelected), _defineProperty$1(_classNames, "".concat(subMenuPrefixCls, "-disabled"), mergedDisabled), _classNames)),
onMouseEnter: onInternalMouseEnter,
onMouseLeave: onInternalMouseLeave
}), titleNode, !overflowDisabled && /*#__PURE__*/React.createElement(InlineSubMenuList, {
id: popupId,
open: open,
keyPath: connectedPath
}, children));
if (_internalRenderSubMenuItem) {
listNode = _internalRenderSubMenuItem(listNode, props, {
selected: childrenSelected,
active: mergedActive,
open: open,
disabled: mergedDisabled
});
}
// >>>>> Render
return /*#__PURE__*/React.createElement(InheritableContextProvider, {
onItemClick: onMergedItemClick,
mode: mode === 'horizontal' ? 'vertical' : mode,
itemIcon: mergedItemIcon,
expandIcon: mergedExpandIcon
}, listNode);
};
function SubMenu$1(props) {
var eventKey = props.eventKey,
children = props.children;
var connectedKeyPath = useFullPath(eventKey);
var childList = parseChildren(children, connectedKeyPath);
// ==================== Record KeyPath ====================
var measure = useMeasure();
// eslint-disable-next-line consistent-return
React.useEffect(function () {
if (measure) {
measure.registerPath(eventKey, connectedKeyPath);
return function () {
measure.unregisterPath(eventKey, connectedKeyPath);
};
}
}, [connectedKeyPath]);
var renderNode;
// ======================== Render ========================
if (measure) {
renderNode = childList;
} else {
renderNode = /*#__PURE__*/React.createElement(InternalSubMenu, props, childList);
}
return /*#__PURE__*/React.createElement(PathTrackerContext.Provider, {
value: connectedKeyPath
}, renderNode);
}
var _excluded$2 = ["prefixCls", "rootClassName", "style", "className", "tabIndex", "items", "children", "direction", "id", "mode", "inlineCollapsed", "disabled", "disabledOverflow", "subMenuOpenDelay", "subMenuCloseDelay", "forceSubMenuRender", "defaultOpenKeys", "openKeys", "activeKey", "defaultActiveFirst", "selectable", "multiple", "defaultSelectedKeys", "selectedKeys", "onSelect", "onDeselect", "inlineIndent", "motion", "defaultMotions", "triggerSubMenuAction", "builtinPlacements", "itemIcon", "expandIcon", "overflowedIndicator", "overflowedIndicatorPopupClassName", "getPopupContainer", "onClick", "onOpenChange", "onKeyDown", "openAnimation", "openTransitionName", "_internalRenderMenuItem", "_internalRenderSubMenuItem"];
/**
* Menu modify after refactor:
* ## Add
* - disabled
*
* ## Remove
* - openTransitionName
* - openAnimation
* - onDestroy
* - siderCollapsed: Seems antd do not use this prop (Need test in antd)
* - collapsedWidth: Seems this logic should be handle by antd Layout.Sider
*/
// optimize for render
var EMPTY_LIST = [];
var Menu$2 = /*#__PURE__*/React.forwardRef(function (props, ref) {
var _childList$, _classNames;
var _ref = props,
_ref$prefixCls = _ref.prefixCls,
prefixCls = _ref$prefixCls === void 0 ? 'rc-menu' : _ref$prefixCls,
rootClassName = _ref.rootClassName,
style = _ref.style,
className = _ref.className,
_ref$tabIndex = _ref.tabIndex,
tabIndex = _ref$tabIndex === void 0 ? 0 : _ref$tabIndex,
items = _ref.items,
children = _ref.children,
direction = _ref.direction,
id = _ref.id,
_ref$mode = _ref.mode,
mode = _ref$mode === void 0 ? 'vertical' : _ref$mode,
inlineCollapsed = _ref.inlineCollapsed,
disabled = _ref.disabled,
disabledOverflow = _ref.disabledOverflow,
_ref$subMenuOpenDelay = _ref.subMenuOpenDelay,
subMenuOpenDelay = _ref$subMenuOpenDelay === void 0 ? 0.1 : _ref$subMenuOpenDelay,
_ref$subMenuCloseDela = _ref.subMenuCloseDelay,
subMenuCloseDelay = _ref$subMenuCloseDela === void 0 ? 0.1 : _ref$subMenuCloseDela,
forceSubMenuRender = _ref.forceSubMenuRender,
defaultOpenKeys = _ref.defaultOpenKeys,
openKeys = _ref.openKeys,
activeKey = _ref.activeKey,
defaultActiveFirst = _ref.defaultActiveFirst,
_ref$selectable = _ref.selectable,
selectable = _ref$selectable === void 0 ? true : _ref$selectable,
_ref$multiple = _ref.multiple,
multiple = _ref$multiple === void 0 ? false : _ref$multiple,
defaultSelectedKeys = _ref.defaultSelectedKeys,
selectedKeys = _ref.selectedKeys,
onSelect = _ref.onSelect,
onDeselect = _ref.onDeselect,
_ref$inlineIndent = _ref.inlineIndent,
inlineIndent = _ref$inlineIndent === void 0 ? 24 : _ref$inlineIndent,
motion = _ref.motion,
defaultMotions = _ref.defaultMotions,
_ref$triggerSubMenuAc = _ref.triggerSubMenuAction,
triggerSubMenuAction = _ref$triggerSubMenuAc === void 0 ? 'hover' : _ref$triggerSubMenuAc,
builtinPlacements = _ref.builtinPlacements,
itemIcon = _ref.itemIcon,
expandIcon = _ref.expandIcon,
_ref$overflowedIndica = _ref.overflowedIndicator,
overflowedIndicator = _ref$overflowedIndica === void 0 ? '...' : _ref$overflowedIndica,
overflowedIndicatorPopupClassName = _ref.overflowedIndicatorPopupClassName,
getPopupContainer = _ref.getPopupContainer,
onClick = _ref.onClick,
onOpenChange = _ref.onOpenChange,
onKeyDown = _ref.onKeyDown,
openAnimation = _ref.openAnimation,
openTransitionName = _ref.openTransitionName,
_internalRenderMenuItem = _ref._internalRenderMenuItem,
_internalRenderSubMenuItem = _ref._internalRenderSubMenuItem,
restProps = _objectWithoutProperties(_ref, _excluded$2);
var childList = React.useMemo(function () {
return parseItems(children, items, EMPTY_LIST);
}, [children, items]);
var _React$useState = React.useState(false),
_React$useState2 = _slicedToArray(_React$useState, 2),
mounted = _React$useState2[0],
setMounted = _React$useState2[1];
var containerRef = React.useRef();
var uuid = useUUID(id);
var isRtl = direction === 'rtl';
// ========================= Warn =========================
if (process.env.NODE_ENV !== 'production') {
warningOnce(!openAnimation && !openTransitionName, '`openAnimation` and `openTransitionName` is removed. Please use `motion` or `defaultMotion` instead.');
}
// ========================= Open =========================
var _useMergedState = useMergedState(defaultOpenKeys, {
value: openKeys,
postState: function postState(keys) {
return keys || EMPTY_LIST;
}
}),
_useMergedState2 = _slicedToArray(_useMergedState, 2),
mergedOpenKeys = _useMergedState2[0],
setMergedOpenKeys = _useMergedState2[1];
// React 18 will merge mouse event which means we open key will not sync
// ref: https://github.com/ant-design/ant-design/issues/38818
var triggerOpenKeys = function triggerOpenKeys(keys) {
var forceFlush = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
function doUpdate() {
setMergedOpenKeys(keys);
onOpenChange === null || onOpenChange === void 0 ? void 0 : onOpenChange(keys);
}
if (forceFlush) {
flushSync(doUpdate);
} else {
doUpdate();
}
};
// >>>>> Cache & Reset open keys when inlineCollapsed changed
var _React$useState3 = React.useState(mergedOpenKeys),
_React$useState4 = _slicedToArray(_React$useState3, 2),
inlineCacheOpenKeys = _React$useState4[0],
setInlineCacheOpenKeys = _React$useState4[1];
var mountRef = React.useRef(false);
// ========================= Mode =========================
var _React$useMemo = React.useMemo(function () {
if ((mode === 'inline' || mode === 'vertical') && inlineCollapsed) {
return ['vertical', inlineCollapsed];
}
return [mode, false];
}, [mode, inlineCollapsed]),
_React$useMemo2 = _slicedToArray(_React$useMemo, 2),
mergedMode = _React$useMemo2[0],
mergedInlineCollapsed = _React$useMemo2[1];
var isInlineMode = mergedMode === 'inline';
var _React$useState5 = React.useState(mergedMode),
_React$useState6 = _slicedToArray(_React$useState5, 2),
internalMode = _React$useState6[0],
setInternalMode = _React$useState6[1];
var _React$useState7 = React.useState(mergedInlineCollapsed),
_React$useState8 = _slicedToArray(_React$useState7, 2),
internalInlineCollapsed = _React$useState8[0],
setInternalInlineCollapsed = _React$useState8[1];
React.useEffect(function () {
setInternalMode(mergedMode);
setInternalInlineCollapsed(mergedInlineCollapsed);
if (!mountRef.current) {
return;
}
// Synchronously update MergedOpenKeys
if (isInlineMode) {
setMergedOpenKeys(inlineCacheOpenKeys);
} else {
// Trigger open event in case its in control
triggerOpenKeys(EMPTY_LIST);
}
}, [mergedMode, mergedInlineCollapsed]);
// ====================== Responsive ======================
var _React$useState9 = React.useState(0),
_React$useState10 = _slicedToArray(_React$useState9, 2),
lastVisibleIndex = _React$useState10[0],
setLastVisibleIndex = _React$useState10[1];
var allVisible = lastVisibleIndex >= childList.length - 1 || internalMode !== 'horizontal' || disabledOverflow;
// Cache
React.useEffect(function () {
if (isInlineMode) {
setInlineCacheOpenKeys(mergedOpenKeys);
}
}, [mergedOpenKeys]);
React.useEffect(function () {
mountRef.current = true;
return function () {
mountRef.current = false;
};
}, []);
// ========================= Path =========================
var _useKeyRecords = useKeyRecords(),
registerPath = _useKeyRecords.registerPath,
unregisterPath = _useKeyRecords.unregisterPath,
refreshOverflowKeys = _useKeyRecords.refreshOverflowKeys,
isSubPathKey = _useKeyRecords.isSubPathKey,
getKeyPath = _useKeyRecords.getKeyPath,
getKeys = _useKeyRecords.getKeys,
getSubPathKeys = _useKeyRecords.getSubPathKeys;
var registerPathContext = React.useMemo(function () {
return {
registerPath: registerPath,
unregisterPath: unregisterPath
};
}, [registerPath, unregisterPath]);
var pathUserContext = React.useMemo(function () {
return {
isSubPathKey: isSubPathKey
};
}, [isSubPathKey]);
React.useEffect(function () {
refreshOverflowKeys(allVisible ? EMPTY_LIST : childList.slice(lastVisibleIndex + 1).map(function (child) {
return child.key;
}));
}, [lastVisibleIndex, allVisible]);
// ======================== Active ========================
var _useMergedState3 = useMergedState(activeKey || defaultActiveFirst && ((_childList$ = childList[0]) === null || _childList$ === void 0 ? void 0 : _childList$.key), {
value: activeKey
}),
_useMergedState4 = _slicedToArray(_useMergedState3, 2),
mergedActiveKey = _useMergedState4[0],
setMergedActiveKey = _useMergedState4[1];
var onActive = useMemoCallback(function (key) {
setMergedActiveKey(key);
});
var onInactive = useMemoCallback(function () {
setMergedActiveKey(undefined);
});
useImperativeHandle(ref, function () {
return {
list: containerRef.current,
focus: function focus(options) {
var _childList$find;
var shouldFocusKey = mergedActiveKey !== null && mergedActiveKey !== void 0 ? mergedActiveKey : (_childList$find = childList.find(function (node) {
return !node.props.disabled;
})) === null || _childList$find === void 0 ? void 0 : _childList$find.key;
if (shouldFocusKey) {
var _containerRef$current, _containerRef$current2, _containerRef$current3;
(_containerRef$current = containerRef.current) === null || _containerRef$current === void 0 ? void 0 : (_containerRef$current2 = _containerRef$current.querySelector("li[data-menu-id='".concat(getMenuId(uuid, shouldFocusKey), "']"))) === null || _containerRef$current2 === void 0 ? void 0 : (_containerRef$current3 = _containerRef$current2.focus) === null || _containerRef$current3 === void 0 ? void 0 : _containerRef$current3.call(_containerRef$current2, options);
}
}
};
});
// ======================== Select ========================
// >>>>> Select keys
var _useMergedState5 = useMergedState(defaultSelectedKeys || [], {
value: selectedKeys,
// Legacy convert key to array
postState: function postState(keys) {
if (Array.isArray(keys)) {
return keys;
}
if (keys === null || keys === undefined) {
return EMPTY_LIST;
}
return [keys];
}
}),
_useMergedState6 = _slicedToArray(_useMergedState5, 2),
mergedSelectKeys = _useMergedState6[0],
setMergedSelectKeys = _useMergedState6[1];
// >>>>> Trigger select
var triggerSelection = function triggerSelection(info) {
if (selectable) {
// Insert or Remove
var targetKey = info.key;
var exist = mergedSelectKeys.includes(targetKey);
var newSelectKeys;
if (multiple) {
if (exist) {
newSelectKeys = mergedSelectKeys.filter(function (key) {
return key !== targetKey;
});
} else {
newSelectKeys = [].concat(_toConsumableArray(mergedSelectKeys), [targetKey]);
}
} else {
newSelectKeys = [targetKey];
}
setMergedSelectKeys(newSelectKeys);
// Trigger event
var selectInfo = _objectSpread2$1(_objectSpread2$1({}, info), {}, {
selectedKeys: newSelectKeys
});
if (exist) {
onDeselect === null || onDeselect === void 0 ? void 0 : onDeselect(selectInfo);
} else {
onSelect === null || onSelect === void 0 ? void 0 : onSelect(selectInfo);
}
}
// Whatever selectable, always close it
if (!multiple && mergedOpenKeys.length && internalMode !== 'inline') {
triggerOpenKeys(EMPTY_LIST);
}
};
// ========================= Open =========================
/**
* Click for item. SubMenu do not have selection status
*/
var onInternalClick = useMemoCallback(function (info) {
onClick === null || onClick === void 0 ? void 0 : onClick(warnItemProp(info));
triggerSelection(info);
});
var onInternalOpenChange = useMemoCallback(function (key, open) {
var newOpenKeys = mergedOpenKeys.filter(function (k) {
return k !== key;
});
if (open) {
newOpenKeys.push(key);
} else if (internalMode !== 'inline') {
// We need find all related popup to close
var subPathKeys = getSubPathKeys(key);
newOpenKeys = newOpenKeys.filter(function (k) {
return !subPathKeys.has(k);
});
}
if (!isEqual(mergedOpenKeys, newOpenKeys, true)) {
triggerOpenKeys(newOpenKeys, true);
}
});
var getInternalPopupContainer = useMemoCallback(getPopupContainer);
// ==================== Accessibility =====================
var triggerAccessibilityOpen = function triggerAccessibilityOpen(key, open) {
var nextOpen = open !== null && open !== void 0 ? open : !mergedOpenKeys.includes(key);
onInternalOpenChange(key, nextOpen);
};
var onInternalKeyDown = useAccessibility$1(internalMode, mergedActiveKey, isRtl, uuid, containerRef, getKeys, getKeyPath, setMergedActiveKey, triggerAccessibilityOpen, onKeyDown);
// ======================== Effect ========================
React.useEffect(function () {
setMounted(true);
}, []);
// ======================= Context ========================
var privateContext = React.useMemo(function () {
return {
_internalRenderMenuItem: _internalRenderMenuItem,
_internalRenderSubMenuItem: _internalRenderSubMenuItem
};
}, [_internalRenderMenuItem, _internalRenderSubMenuItem]);
// ======================== Render ========================
// >>>>> Children
var wrappedChildList = internalMode !== 'horizontal' || disabledOverflow ? childList :
// Need wrap for overflow dropdown that do not response for open
childList.map(function (child, index) {
return /*#__PURE__*/(
// Always wrap provider to avoid sub node re-mount
React.createElement(InheritableContextProvider, {
key: child.key,
overflowDisabled: index > lastVisibleIndex
}, child)
);
});
// >>>>> Container
var container = /*#__PURE__*/React.createElement(ForwardOverflow, _extends$1({
id: id,
ref: containerRef,
prefixCls: "".concat(prefixCls, "-overflow"),
component: "ul",
itemComponent: MenuItem$2,
className: classNames(prefixCls, "".concat(prefixCls, "-root"), "".concat(prefixCls, "-").concat(internalMode), className, (_classNames = {}, _defineProperty$1(_classNames, "".concat(prefixCls, "-inline-collapsed"), internalInlineCollapsed), _defineProperty$1(_classNames, "".concat(prefixCls, "-rtl"), isRtl), _classNames), rootClassName),
dir: direction,
style: style,
role: "menu",
tabIndex: tabIndex,
data: wrappedChildList,
renderRawItem: function renderRawItem(node) {
return node;
},
renderRawRest: function renderRawRest(omitItems) {
// We use origin list since wrapped list use context to prevent open
var len = omitItems.length;
var originOmitItems = len ? childList.slice(-len) : null;
return /*#__PURE__*/React.createElement(SubMenu$1, {
eventKey: OVERFLOW_KEY,
title: overflowedIndicator,
disabled: allVisible,
internalPopupClose: len === 0,
popupClassName: overflowedIndicatorPopupClassName
}, originOmitItems);
},
maxCount: internalMode !== 'horizontal' || disabledOverflow ? ForwardOverflow.INVALIDATE : ForwardOverflow.RESPONSIVE,
ssr: "full",
"data-menu-list": true,
onVisibleChange: function onVisibleChange(newLastIndex) {
setLastVisibleIndex(newLastIndex);
},
onKeyDown: onInternalKeyDown
}, restProps));
// >>>>> Render
return /*#__PURE__*/React.createElement(PrivateContext.Provider, {
value: privateContext
}, /*#__PURE__*/React.createElement(IdContext.Provider, {
value: uuid
}, /*#__PURE__*/React.createElement(InheritableContextProvider, {
prefixCls: prefixCls,
rootClassName: rootClassName,
mode: internalMode,
openKeys: mergedOpenKeys,
rtl: isRtl
// Disabled
,
disabled: disabled
// Motion
,
motion: mounted ? motion : null,
defaultMotions: mounted ? defaultMotions : null
// Active
,
activeKey: mergedActiveKey,
onActive: onActive,
onInactive: onInactive
// Selection
,
selectedKeys: mergedSelectKeys
// Level
,
inlineIndent: inlineIndent
// Popup
,
subMenuOpenDelay: subMenuOpenDelay,
subMenuCloseDelay: subMenuCloseDelay,
forceSubMenuRender: forceSubMenuRender,
builtinPlacements: builtinPlacements,
triggerSubMenuAction: triggerSubMenuAction,
getPopupContainer: getInternalPopupContainer
// Icon
,
itemIcon: itemIcon,
expandIcon: expandIcon
// Events
,
onItemClick: onInternalClick,
onOpenChange: onInternalOpenChange
}, /*#__PURE__*/React.createElement(PathUserContext.Provider, {
value: pathUserContext
}, container), /*#__PURE__*/React.createElement("div", {
style: {
display: 'none'
},
"aria-hidden": true
}, /*#__PURE__*/React.createElement(PathRegisterContext.Provider, {
value: registerPathContext
}, childList)))));
});
var _excluded$1 = ["className", "title", "eventKey", "children"],
_excluded2 = ["children"];
var InternalMenuItemGroup = function InternalMenuItemGroup(_ref) {
var className = _ref.className,
title = _ref.title;
_ref.eventKey;
var children = _ref.children,
restProps = _objectWithoutProperties(_ref, _excluded$1);
var _React$useContext = React.useContext(MenuContext$2),
prefixCls = _React$useContext.prefixCls;
var groupPrefixCls = "".concat(prefixCls, "-item-group");
return /*#__PURE__*/React.createElement("li", _extends$1({
role: "presentation"
}, restProps, {
onClick: function onClick(e) {
return e.stopPropagation();
},
className: classNames(groupPrefixCls, className)
}), /*#__PURE__*/React.createElement("div", {
role: "presentation",
className: "".concat(groupPrefixCls, "-title"),
title: typeof title === 'string' ? title : undefined
}, title), /*#__PURE__*/React.createElement("ul", {
role: "group",
className: "".concat(groupPrefixCls, "-list")
}, children));
};
function MenuItemGroup(_ref2) {
var children = _ref2.children,
props = _objectWithoutProperties(_ref2, _excluded2);
var connectedKeyPath = useFullPath(props.eventKey);
var childList = parseChildren(children, connectedKeyPath);
var measure = useMeasure();
if (measure) {
return childList;
}
return /*#__PURE__*/React.createElement(InternalMenuItemGroup, omit(props, ['warnKey']), childList);
}
function Divider(_ref) {
var className = _ref.className,
style = _ref.style;
var _React$useContext = React.useContext(MenuContext$2),
prefixCls = _React$useContext.prefixCls;
var measure = useMeasure();
if (measure) {
return null;
}
return /*#__PURE__*/React.createElement("li", {
className: classNames("".concat(prefixCls, "-item-divider"), className),
style: style
});
}
var ExportMenu = Menu$2;
ExportMenu.Item = MenuItem$2;
ExportMenu.SubMenu = SubMenu$1;
ExportMenu.ItemGroup = MenuItemGroup;
ExportMenu.Divider = Divider;
var EllipsisOutlined = function EllipsisOutlined(props, ref) {
return /*#__PURE__*/React.createElement(AntdIcon, _objectSpread2$1(_objectSpread2$1({}, props), {}, {
ref: ref,
icon: EllipsisOutlinedSvg
}));
};
EllipsisOutlined.displayName = 'EllipsisOutlined';
var EllipsisOutlined$1 = /*#__PURE__*/React.forwardRef(EllipsisOutlined);
var getHorizontalStyle = function getHorizontalStyle(token) {
var _ref;
var componentCls = token.componentCls,
motionDurationSlow = token.motionDurationSlow,
menuHorizontalHeight = token.menuHorizontalHeight,
colorSplit = token.colorSplit,
lineWidth = token.lineWidth,
lineType = token.lineType,
menuItemPaddingInline = token.menuItemPaddingInline;
return _defineProperty$1({}, componentCls + "-horizontal", (_ref = {
lineHeight: menuHorizontalHeight + "px",
border: 0,
borderBottom: lineWidth + "px " + lineType + " " + colorSplit,
boxShadow: 'none',
'&::after': {
display: 'block',
clear: 'both',
height: 0,
content: '"\\20"'
}
}, _defineProperty$1(_ref, componentCls + "-item, " + componentCls + "-submenu", {
position: 'relative',
display: 'inline-block',
verticalAlign: 'bottom',
paddingInline: menuItemPaddingInline
}), _defineProperty$1(_ref, "> " + componentCls + "-item:hover,\n > " + componentCls + "-item-active,\n > " + componentCls + "-submenu " + componentCls + "-submenu-title:hover", {
backgroundColor: 'transparent'
}), _defineProperty$1(_ref, componentCls + "-item, " + componentCls + "-submenu-title", {
transition: ["border-color " + motionDurationSlow, "background " + motionDurationSlow].join(',')
}), _defineProperty$1(_ref, componentCls + "-submenu-arrow", {
display: 'none'
}), _ref));
};
var getHorizontalStyle$1 = getHorizontalStyle;
var getRTLStyle = function getRTLStyle(_ref) {
var _ref3;
var componentCls = _ref.componentCls,
menuArrowOffset = _ref.menuArrowOffset;
return _ref3 = {}, _defineProperty$1(_ref3, componentCls + "-rtl", {
direction: 'rtl'
}), _defineProperty$1(_ref3, componentCls + "-submenu-rtl", {
transformOrigin: '100% 0'
}), _defineProperty$1(_ref3, componentCls + "-rtl" + componentCls + "-vertical,\n " + componentCls + "-submenu-rtl " + componentCls + "-vertical", _defineProperty$1({}, componentCls + "-submenu-arrow", {
'&::before': {
transform: "rotate(-45deg) translateY(-" + menuArrowOffset + ")"
},
'&::after': {
transform: "rotate(45deg) translateY(" + menuArrowOffset + ")"
}
})), _ref3;
};
var getRTLStyle$1 = getRTLStyle;
var accessibilityFocus = function accessibilityFocus(token) {
return _extends$1({}, genFocusOutline(token));
};
var getThemeStyle = function getThemeStyle(token, themeSuffix) {
var _ref3, _ref5, _ref6, _ref9, _ref12, _ref13;
var componentCls = token.componentCls,
colorItemText = token.colorItemText,
colorItemTextSelected = token.colorItemTextSelected,
colorItemTextSelectedHorizontal = token.colorItemTextSelectedHorizontal,
colorGroupTitle = token.colorGroupTitle,
colorItemBg = token.colorItemBg,
colorSubItemBg = token.colorSubItemBg,
colorItemBgSelectedHorizontal = token.colorItemBgSelectedHorizontal,
colorItemBgSelected = token.colorItemBgSelected,
colorActiveBarHeight = token.colorActiveBarHeight,
colorActiveBarWidth = token.colorActiveBarWidth,
colorActiveBarBorderSize = token.colorActiveBarBorderSize,
motionDurationSlow = token.motionDurationSlow,
motionEaseInOut = token.motionEaseInOut,
motionEaseOut = token.motionEaseOut,
menuItemPaddingInline = token.menuItemPaddingInline,
motionDurationMid = token.motionDurationMid,
colorItemTextHover = token.colorItemTextHover,
lineType = token.lineType,
colorSplit = token.colorSplit,
colorItemTextDisabled = token.colorItemTextDisabled,
colorDangerItemText = token.colorDangerItemText,
colorDangerItemTextHover = token.colorDangerItemTextHover,
colorDangerItemTextSelected = token.colorDangerItemTextSelected,
colorDangerItemBgActive = token.colorDangerItemBgActive,
colorDangerItemBgSelected = token.colorDangerItemBgSelected,
colorItemBgHover = token.colorItemBgHover,
menuSubMenuBg = token.menuSubMenuBg;
return _defineProperty$1({}, componentCls + "-" + themeSuffix, (_ref13 = {
color: colorItemText,
background: colorItemBg
}, _defineProperty$1(_ref13, "&" + componentCls + "-root:focus-visible", _extends$1({}, accessibilityFocus(token))), _defineProperty$1(_ref13, componentCls + "-item-group-title", {
color: colorGroupTitle
}), _defineProperty$1(_ref13, componentCls + "-submenu-selected", _defineProperty$1({}, "> " + componentCls + "-submenu-title", {
color: colorItemTextSelected
})), _defineProperty$1(_ref13, componentCls + "-item-disabled, " + componentCls + "-submenu-disabled", {
color: colorItemTextDisabled + " !important"
}), _defineProperty$1(_ref13, componentCls + "-item:hover, " + componentCls + "-submenu-title:hover", _defineProperty$1({}, "&:not(" + componentCls + "-item-selected):not(" + componentCls + "-submenu-selected)", {
color: colorItemTextHover
})), _defineProperty$1(_ref13, "&:not(" + componentCls + "-horizontal)", (_ref3 = {}, _defineProperty$1(_ref3, componentCls + "-item:not(" + componentCls + "-item-selected)", {
'&:hover': {
backgroundColor: colorItemBgHover
},
'&:active': {
backgroundColor: colorItemBgSelected
}
}), _defineProperty$1(_ref3, componentCls + "-submenu-title", {
'&:hover': {
backgroundColor: colorItemBgHover
},
'&:active': {
backgroundColor: colorItemBgSelected
}
}), _ref3)), _defineProperty$1(_ref13, componentCls + "-item-danger", (_ref5 = {
color: colorDangerItemText
}, _defineProperty$1(_ref5, "&" + componentCls + "-item:hover", _defineProperty$1({}, "&:not(" + componentCls + "-item-selected):not(" + componentCls + "-submenu-selected)", {
color: colorDangerItemTextHover
})), _defineProperty$1(_ref5, "&" + componentCls + "-item:active", {
background: colorDangerItemBgActive
}), _ref5)), _defineProperty$1(_ref13, componentCls + "-item a", {
'&, &:hover': {
color: 'inherit'
}
}), _defineProperty$1(_ref13, componentCls + "-item-selected", (_ref6 = {
color: colorItemTextSelected
}, _defineProperty$1(_ref6, "&" + componentCls + "-item-danger", {
color: colorDangerItemTextSelected
}), _defineProperty$1(_ref6, "a, a:hover", {
color: 'inherit'
}), _ref6)), _defineProperty$1(_ref13, "&:not(" + componentCls + "-horizontal) " + componentCls + "-item-selected", _defineProperty$1({
backgroundColor: colorItemBgSelected
}, "&" + componentCls + "-item-danger", {
backgroundColor: colorDangerItemBgSelected
})), _defineProperty$1(_ref13, componentCls + "-item, " + componentCls + "-submenu-title", _defineProperty$1({}, "&:not(" + componentCls + "-item-disabled):focus-visible", _extends$1({}, accessibilityFocus(token)))), _defineProperty$1(_ref13, "&" + componentCls + "-submenu > " + componentCls, {
backgroundColor: menuSubMenuBg
}), _defineProperty$1(_ref13, "&" + componentCls + "-popup > " + componentCls, {
backgroundColor: colorItemBg
}), _defineProperty$1(_ref13, "&" + componentCls + "-horizontal", _extends$1(_extends$1({}, themeSuffix === 'dark' ? {
borderBottom: 0
} : {}), _defineProperty$1({}, "> " + componentCls + "-item, > " + componentCls + "-submenu", (_ref9 = {
top: colorActiveBarBorderSize,
marginTop: -colorActiveBarBorderSize,
marginBottom: 0,
borderRadius: token.radiusItem,
'&::after': {
position: 'absolute',
insetInline: menuItemPaddingInline,
bottom: 0,
borderBottom: colorActiveBarHeight + "px solid transparent",
transition: "border-color " + motionDurationSlow + " " + motionEaseInOut,
content: '""'
}
}, _defineProperty$1(_ref9, "&:hover, &-active, &-open", {
'&::after': {
borderWidth: colorActiveBarHeight + "px",
borderBottomColor: colorItemTextSelectedHorizontal
}
}), _defineProperty$1(_ref9, "&-selected", {
color: colorItemTextSelectedHorizontal,
backgroundColor: colorItemBgSelectedHorizontal,
'&::after': {
borderWidth: colorActiveBarHeight + "px",
borderBottomColor: colorItemTextSelectedHorizontal
}
}), _ref9)))), _defineProperty$1(_ref13, "&" + componentCls + "-root", _defineProperty$1({}, "&" + componentCls + "-inline, &" + componentCls + "-vertical", {
borderInlineEnd: colorActiveBarBorderSize + "px " + lineType + " " + colorSplit
})), _defineProperty$1(_ref13, "&" + componentCls + "-inline", (_ref12 = {}, _defineProperty$1(_ref12, componentCls + "-sub" + componentCls + "-inline", {
background: colorSubItemBg
}), _defineProperty$1(_ref12, componentCls + "-item, " + componentCls + "-submenu-title", colorActiveBarBorderSize && colorActiveBarWidth ? {
width: "calc(100% + " + colorActiveBarBorderSize + "px)"
} : {}), _defineProperty$1(_ref12, componentCls + "-item", _defineProperty$1({
position: 'relative',
'&::after': {
position: 'absolute',
insetBlock: 0,
insetInlineEnd: 0,
borderInlineEnd: colorActiveBarWidth + "px solid " + colorItemTextSelected,
transform: 'scaleY(0.0001)',
opacity: 0,
transition: ["transform " + motionDurationMid + " " + motionEaseOut, "opacity " + motionDurationMid + " " + motionEaseOut].join(','),
content: '""'
}
}, "&" + componentCls + "-item-danger", {
'&::after': {
borderInlineEndColor: colorDangerItemTextSelected
}
})), _defineProperty$1(_ref12, componentCls + "-selected, " + componentCls + "-item-selected", {
'&::after': {
transform: 'scaleY(1)',
opacity: 1,
transition: ["transform " + motionDurationMid + " " + motionEaseInOut, "opacity " + motionDurationMid + " " + motionEaseInOut].join(',')
}
}), _ref12)), _ref13));
};
var getThemeStyle$1 = getThemeStyle;
var getVerticalInlineStyle = function getVerticalInlineStyle(token) {
var _ref;
var componentCls = token.componentCls,
menuItemHeight = token.menuItemHeight,
itemMarginInline = token.itemMarginInline,
padding = token.padding,
menuArrowSize = token.menuArrowSize,
marginXS = token.marginXS,
marginXXS = token.marginXXS;
var paddingWithArrow = padding + menuArrowSize + marginXS;
return _ref = {}, _defineProperty$1(_ref, componentCls + "-item", {
position: 'relative'
}), _defineProperty$1(_ref, componentCls + "-item, " + componentCls + "-submenu-title", {
height: menuItemHeight,
lineHeight: menuItemHeight + "px",
paddingInline: padding,
overflow: 'hidden',
textOverflow: 'ellipsis',
marginInline: itemMarginInline,
marginBlock: marginXXS,
width: "calc(100% - " + itemMarginInline * 2 + "px)"
}), _defineProperty$1(_ref, componentCls + "-submenu", {
paddingBottom: 0.02
}), _defineProperty$1(_ref, "> " + componentCls + "-item,\n > " + componentCls + "-submenu > " + componentCls + "-submenu-title", {
height: menuItemHeight,
lineHeight: menuItemHeight + "px"
}), _defineProperty$1(_ref, componentCls + "-item-group-list " + componentCls + "-submenu-title,\n " + componentCls + "-submenu-title", {
paddingInlineEnd: paddingWithArrow
}), _ref;
};
var getVerticalStyle = function getVerticalStyle(token) {
var _ref3, _ref5, _ref7, _ref8, _ref12, _tooltip, _ref13;
var componentCls = token.componentCls,
iconCls = token.iconCls,
menuItemHeight = token.menuItemHeight,
colorTextLightSolid = token.colorTextLightSolid,
dropdownWidth = token.dropdownWidth,
controlHeightLG = token.controlHeightLG,
motionDurationMid = token.motionDurationMid,
motionEaseOut = token.motionEaseOut,
paddingXL = token.paddingXL,
fontSizeSM = token.fontSizeSM,
fontSizeLG = token.fontSizeLG,
motionDurationSlow = token.motionDurationSlow,
paddingXS = token.paddingXS,
boxShadowSecondary = token.boxShadowSecondary;
var inlineItemStyle = {
height: menuItemHeight,
lineHeight: menuItemHeight + "px",
listStylePosition: 'inside',
listStyleType: 'disc'
};
return [(_ref3 = {}, _defineProperty$1(_ref3, componentCls, _defineProperty$1({}, "&-inline, &-vertical", _extends$1(_defineProperty$1({}, "&" + componentCls + "-root", {
boxShadow: 'none'
}), getVerticalInlineStyle(token)))), _defineProperty$1(_ref3, componentCls + "-submenu-popup", _defineProperty$1({}, componentCls + "-vertical", _extends$1(_extends$1({}, getVerticalInlineStyle(token)), {
boxShadow: boxShadowSecondary
}))), _ref3),
// Vertical only
_defineProperty$1({}, componentCls + "-submenu-popup " + componentCls + "-vertical" + componentCls + "-sub", {
minWidth: dropdownWidth,
maxHeight: "calc(100vh - " + controlHeightLG * 2.5 + "px)",
padding: '0',
overflow: 'hidden',
borderInlineEnd: 0,
// https://github.com/ant-design/ant-design/issues/22244
// https://github.com/ant-design/ant-design/issues/26812
"&:not([class*='-active'])": {
overflowX: 'hidden',
overflowY: 'auto'
}
}),
// Inline Only
_defineProperty$1({}, componentCls + "-inline", (_ref8 = {
width: '100%'
}, _defineProperty$1(_ref8, "&" + componentCls + "-root", _defineProperty$1({}, componentCls + "-item, " + componentCls + "-submenu-title", (_ref5 = {
display: 'flex',
alignItems: 'center',
transition: ["border-color " + motionDurationSlow, "background " + motionDurationSlow, "padding " + motionDurationMid + " " + motionEaseOut]
}, _defineProperty$1(_ref5, "> " + componentCls + "-title-content", {
flex: 'auto',
minWidth: 0,
overflow: 'hidden',
textOverflow: 'ellipsis'
}), _defineProperty$1(_ref5, '> *', {
flex: 'none'
}), _ref5))), _defineProperty$1(_ref8, componentCls + "-sub" + componentCls + "-inline", (_ref7 = {
padding: 0,
border: 0,
borderRadius: 0,
boxShadow: 'none'
}, _defineProperty$1(_ref7, "& > " + componentCls + "-submenu > " + componentCls + "-submenu-title", inlineItemStyle), _defineProperty$1(_ref7, "& " + componentCls + "-item-group-title", {
paddingInlineStart: paddingXL
}), _ref7)), _defineProperty$1(_ref8, componentCls + "-item", inlineItemStyle), _ref8)),
// Inline Collapse Only
_defineProperty$1({}, componentCls + "-inline-collapsed", (_ref13 = {
width: menuItemHeight * 2
}, _defineProperty$1(_ref13, "&" + componentCls + "-root", _defineProperty$1({}, componentCls + "-item, " + componentCls + "-submenu " + componentCls + "-submenu-title", _defineProperty$1({}, "> " + componentCls + "-inline-collapsed-noicon", {
fontSize: fontSizeLG,
textAlign: 'center'
}))), _defineProperty$1(_ref13, "> " + componentCls + "-item,\n > " + componentCls + "-item-group > " + componentCls + "-item-group-list > " + componentCls + "-item,\n > " + componentCls + "-item-group > " + componentCls + "-item-group-list > " + componentCls + "-submenu > " + componentCls + "-submenu-title,\n > " + componentCls + "-submenu > " + componentCls + "-submenu-title", (_ref12 = {
insetInlineStart: 0,
paddingInline: "calc(50% - " + fontSizeSM + "px)",
textOverflow: 'clip'
}, _defineProperty$1(_ref12, componentCls + "-submenu-arrow", {
opacity: 0
}), _defineProperty$1(_ref12, componentCls + "-item-icon, " + iconCls, {
margin: 0,
fontSize: fontSizeLG,
lineHeight: menuItemHeight + "px",
'+ span': {
display: 'inline-block',
opacity: 0
}
}), _ref12)), _defineProperty$1(_ref13, componentCls + "-item-icon, " + iconCls, {
display: 'inline-block'
}), _defineProperty$1(_ref13, '&-tooltip', (_tooltip = {
pointerEvents: 'none'
}, _defineProperty$1(_tooltip, componentCls + "-item-icon, " + iconCls, {
display: 'none'
}), _defineProperty$1(_tooltip, 'a, a:hover', {
color: colorTextLightSolid
}), _tooltip)), _defineProperty$1(_ref13, componentCls + "-item-group-title", _extends$1(_extends$1({}, textEllipsis), {
paddingInline: paddingXS
})), _ref13))];
};
var getVerticalStyle$1 = getVerticalStyle;
var genMenuItemStyle = function genMenuItemStyle(token) {
var _ref2, _ref4;
var componentCls = token.componentCls,
fontSize = token.fontSize,
motionDurationSlow = token.motionDurationSlow,
motionDurationMid = token.motionDurationMid,
motionEaseInOut = token.motionEaseInOut,
motionEaseOut = token.motionEaseOut,
iconCls = token.iconCls,
controlHeightSM = token.controlHeightSM;
return _ref4 = {}, _defineProperty$1(_ref4, componentCls + "-item, " + componentCls + "-submenu-title", (_ref2 = {
position: 'relative',
display: 'block',
margin: 0,
whiteSpace: 'nowrap',
cursor: 'pointer',
transition: ["border-color " + motionDurationSlow, "background " + motionDurationSlow, "padding " + motionDurationSlow + " " + motionEaseInOut].join(',')
}, _defineProperty$1(_ref2, componentCls + "-item-icon, " + iconCls, {
minWidth: fontSize,
fontSize: fontSize,
transition: ["font-size " + motionDurationMid + " " + motionEaseOut, "margin " + motionDurationSlow + " " + motionEaseInOut, "color " + motionDurationSlow].join(','),
'+ span': {
marginInlineStart: controlHeightSM - fontSize,
opacity: 1,
transition: ["opacity " + motionDurationSlow + " " + motionEaseInOut, "margin " + motionDurationSlow, "color " + motionDurationSlow].join(',')
}
}), _defineProperty$1(_ref2, componentCls + "-item-icon", _extends$1({}, resetIcon())), _defineProperty$1(_ref2, "&" + componentCls + "-item-only-child", _defineProperty$1({}, "> " + iconCls + ", > " + componentCls + "-item-icon", {
marginInlineEnd: 0
})), _ref2)), _defineProperty$1(_ref4, componentCls + "-item-disabled, " + componentCls + "-submenu-disabled", _defineProperty$1({
background: 'none !important',
cursor: 'not-allowed',
'&::after': {
borderColor: 'transparent !important'
},
a: {
color: 'inherit !important'
}
}, "> " + componentCls + "-submenu-title", {
color: 'inherit !important',
cursor: 'not-allowed'
})), _ref4;
};
var genSubMenuArrowStyle = function genSubMenuArrowStyle(token) {
var _ref5;
var componentCls = token.componentCls,
motionDurationSlow = token.motionDurationSlow,
motionEaseInOut = token.motionEaseInOut,
borderRadius = token.borderRadius,
menuArrowSize = token.menuArrowSize,
menuArrowOffset = token.menuArrowOffset;
return _defineProperty$1({}, componentCls + "-submenu", (_ref5 = {}, _defineProperty$1(_ref5, "&-expand-icon, &-arrow", {
position: 'absolute',
top: '50%',
insetInlineEnd: token.margin,
width: menuArrowSize,
color: 'currentcolor',
transform: 'translateY(-50%)',
transition: "transform " + motionDurationSlow + " " + motionEaseInOut
}), _defineProperty$1(_ref5, '&-arrow', {
// →
'&::before, &::after': {
position: 'absolute',
width: menuArrowSize * 0.6,
height: menuArrowSize * 0.15,
backgroundColor: 'currentcolor',
borderRadius: borderRadius,
transition: ["background " + motionDurationSlow + " " + motionEaseInOut, "transform " + motionDurationSlow + " " + motionEaseInOut, "top " + motionDurationSlow + " " + motionEaseInOut, "color " + motionDurationSlow + " " + motionEaseInOut].join(','),
content: '""'
},
'&::before': {
transform: "rotate(45deg) translateY(-" + menuArrowOffset + ")"
},
'&::after': {
transform: "rotate(-45deg) translateY(" + menuArrowOffset + ")"
}
}), _ref5));
};
// =============================== Base ===============================
var getBaseStyle = function getBaseStyle(token) {
var _extends3, _extends4, _extends5, _extends6;
var antCls = token.antCls,
componentCls = token.componentCls,
fontSize = token.fontSize,
motionDurationSlow = token.motionDurationSlow,
motionDurationMid = token.motionDurationMid,
motionEaseInOut = token.motionEaseInOut,
lineHeight = token.lineHeight,
paddingXS = token.paddingXS,
padding = token.padding,
colorSplit = token.colorSplit,
lineWidth = token.lineWidth,
zIndexPopup = token.zIndexPopup,
borderRadiusLG = token.borderRadiusLG,
radiusSubMenuItem = token.radiusSubMenuItem,
menuArrowSize = token.menuArrowSize,
menuArrowOffset = token.menuArrowOffset,
lineType = token.lineType,
menuPanelMaskInset = token.menuPanelMaskInset;
return [
// Misc
_defineProperty$1({
'': _defineProperty$1({}, "" + componentCls, _extends$1(_extends$1({}, clearFix()), _defineProperty$1({}, "&-hidden", {
display: 'none'
})))
}, componentCls + "-submenu-hidden", {
display: 'none'
}), _defineProperty$1({}, componentCls, _extends$1(_extends$1(_extends$1(_extends$1(_extends$1(_extends$1(_extends$1({}, resetComponent(token)), clearFix()), (_extends3 = {
marginBottom: 0,
paddingInlineStart: 0,
// Override default ul/ol
fontSize: fontSize,
lineHeight: 0,
listStyle: 'none',
outline: 'none',
transition: ["background " + motionDurationSlow,
// Magic cubic here but smooth transition
"width " + motionDurationSlow + " cubic-bezier(0.2, 0, 0, 1) 0s"].join(',')
}, _defineProperty$1(_extends3, "ul, ol", {
margin: 0,
padding: 0,
listStyle: 'none'
}), _defineProperty$1(_extends3, "&-overflow", _defineProperty$1({
display: 'flex'
}, componentCls + "-item", {
flex: 'none'
})), _defineProperty$1(_extends3, componentCls + "-item, " + componentCls + "-submenu, " + componentCls + "-submenu-title", {
borderRadius: token.radiusItem
}), _defineProperty$1(_extends3, componentCls + "-item-group-title", {
padding: paddingXS + "px " + padding + "px",
fontSize: fontSize,
lineHeight: lineHeight,
transition: "all " + motionDurationSlow
}), _defineProperty$1(_extends3, "&-horizontal " + componentCls + "-submenu", {
transition: ["border-color " + motionDurationSlow + " " + motionEaseInOut, "background " + motionDurationSlow + " " + motionEaseInOut].join(',')
}), _defineProperty$1(_extends3, componentCls + "-submenu, " + componentCls + "-submenu-inline", {
transition: ["border-color " + motionDurationSlow + " " + motionEaseInOut, "background " + motionDurationSlow + " " + motionEaseInOut, "padding " + motionDurationMid + " " + motionEaseInOut].join(',')
}), _defineProperty$1(_extends3, componentCls + "-submenu " + componentCls + "-sub", {
cursor: 'initial',
transition: ["background " + motionDurationSlow + " " + motionEaseInOut, "padding " + motionDurationSlow + " " + motionEaseInOut]
}), _defineProperty$1(_extends3, componentCls + "-title-content", {
transition: "color " + motionDurationSlow
}), _defineProperty$1(_extends3, componentCls + "-item a", {
'&::before': {
position: 'absolute',
inset: 0,
backgroundColor: 'transparent',
content: '""'
}
}), _defineProperty$1(_extends3, componentCls + "-item-divider", {
overflow: 'hidden',
lineHeight: 0,
borderColor: colorSplit,
borderStyle: lineType,
borderTopWidth: lineWidth,
marginBlock: lineWidth,
padding: 0,
'&-dashed': {
borderStyle: 'dashed'
}
}), _extends3)), genMenuItemStyle(token)), (_extends5 = {}, _defineProperty$1(_extends5, componentCls + "-item-group", _defineProperty$1({}, componentCls + "-item-group-list", _defineProperty$1({
margin: 0,
padding: 0
}, componentCls + "-item, " + componentCls + "-submenu-title", {
paddingInline: fontSize * 2 + "px " + padding + "px"
}))), _defineProperty$1(_extends5, '&-submenu', _defineProperty$1({
'&-popup': {
position: 'absolute',
zIndex: zIndexPopup,
background: 'transparent',
borderRadius: borderRadiusLG,
boxShadow: 'none',
transformOrigin: '0 0',
// https://github.com/ant-design/ant-design/issues/13955
'&::before': {
position: 'absolute',
inset: menuPanelMaskInset + "px 0 0",
zIndex: -1,
width: '100%',
height: '100%',
opacity: 0,
content: '""'
}
},
// https://github.com/ant-design/ant-design/issues/13955
'&-placement-rightTop::before': {
top: 0,
insetInlineStart: menuPanelMaskInset
}
}, "> " + componentCls, _extends$1(_extends$1(_extends$1({
borderRadius: borderRadiusLG
}, genMenuItemStyle(token)), genSubMenuArrowStyle(token)), (_extends4 = {}, _defineProperty$1(_extends4, componentCls + "-item, " + componentCls + "-submenu > " + componentCls + "-submenu-title", {
borderRadius: radiusSubMenuItem
}), _defineProperty$1(_extends4, componentCls + "-submenu-title::after", {
transition: "transform " + motionDurationSlow + " " + motionEaseInOut
}), _extends4)))), _extends5)), genSubMenuArrowStyle(token)), (_extends6 = {}, _defineProperty$1(_extends6, "&-inline-collapsed " + componentCls + "-submenu-arrow,\n &-inline " + componentCls + "-submenu-arrow", {
// ↓
'&::before': {
transform: "rotate(-45deg) translateX(" + menuArrowOffset + ")"
},
'&::after': {
transform: "rotate(45deg) translateX(-" + menuArrowOffset + ")"
}
}), _defineProperty$1(_extends6, componentCls + "-submenu-open" + componentCls + "-submenu-inline > " + componentCls + "-submenu-title > " + componentCls + "-submenu-arrow", {
// ↑
transform: "translateY(-" + menuArrowSize * 0.2 + "px)",
'&::after': {
transform: "rotate(-45deg) translateX(-" + menuArrowOffset + ")"
},
'&::before': {
transform: "rotate(45deg) translateX(" + menuArrowOffset + ")"
}
}), _extends6))),
// Integration with header element so menu items have the same height
_defineProperty$1({}, antCls + "-layout-header", _defineProperty$1({}, componentCls, {
lineHeight: 'inherit'
}))];
};
// ============================== Export ==============================
var useStyle$4 = (function (prefixCls, injectStyle) {
var useOriginHook = genComponentStyleHook('Menu', function (token, _ref14) {
var overrideComponentToken = _ref14.overrideComponentToken;
// Dropdown will handle menu style self. We do not need to handle this.
if (injectStyle === false) {
return [];
}
var colorBgElevated = token.colorBgElevated,
colorPrimary = token.colorPrimary,
colorError = token.colorError,
colorErrorHover = token.colorErrorHover,
colorTextLightSolid = token.colorTextLightSolid,
colorTextSecondary = token.colorTextSecondary;
var controlHeightLG = token.controlHeightLG,
fontSize = token.fontSize;
var menuArrowSize = fontSize / 7 * 5;
// Menu Token
var menuToken = merge(token, {
menuItemHeight: controlHeightLG,
menuItemPaddingInline: token.margin,
menuArrowSize: menuArrowSize,
menuHorizontalHeight: controlHeightLG * 1.15,
menuArrowOffset: menuArrowSize * 0.25 + "px",
menuPanelMaskInset: -7,
menuSubMenuBg: colorBgElevated
});
var menuDarkToken = merge(menuToken, {
colorItemText: new TinyColor(colorTextLightSolid).setAlpha(0.65).toRgbString(),
colorItemTextHover: colorTextLightSolid,
colorGroupTitle: colorTextSecondary,
colorItemTextSelected: colorTextLightSolid,
colorItemBg: '#001529',
colorSubItemBg: '#000c17',
colorItemBgActive: 'transparent',
colorItemBgSelected: colorPrimary,
colorActiveBarWidth: 0,
colorActiveBarHeight: 0,
colorActiveBarBorderSize: 0,
// Disabled
colorItemTextDisabled: new TinyColor(colorTextLightSolid).setAlpha(0.25).toRgbString(),
// Danger
colorDangerItemText: colorError,
colorDangerItemTextHover: colorErrorHover,
colorDangerItemTextSelected: colorTextLightSolid,
colorDangerItemBgActive: colorError,
colorDangerItemBgSelected: colorError,
menuSubMenuBg: '#001529'
}, _extends$1({}, overrideComponentToken));
return [
// Basic
getBaseStyle(menuToken),
// Horizontal
getHorizontalStyle$1(menuToken),
// Vertical
getVerticalStyle$1(menuToken),
// Theme
getThemeStyle$1(menuToken, 'light'), getThemeStyle$1(menuDarkToken, 'dark'),
// RTL
getRTLStyle$1(menuToken),
// Motion
genCollapseMotion$1(menuToken), initSlideMotion(menuToken, 'slide-up'), initSlideMotion(menuToken, 'slide-down'), initZoomMotion(menuToken, 'zoom-big')];
}, function (token) {
var colorPrimary = token.colorPrimary,
colorError = token.colorError,
colorTextDisabled = token.colorTextDisabled,
colorErrorBg = token.colorErrorBg,
colorText = token.colorText,
colorTextDescription = token.colorTextDescription,
colorBgContainer = token.colorBgContainer,
colorFillAlter = token.colorFillAlter,
colorFillContent = token.colorFillContent,
lineWidth = token.lineWidth,
lineWidthBold = token.lineWidthBold,
controlItemBgActiveHover = token.controlItemBgActiveHover,
colorBgTextHover = token.colorBgTextHover;
return {
dropdownWidth: 160,
zIndexPopup: token.zIndexPopupBase + 50,
radiusItem: token.borderRadiusLG,
radiusSubMenuItem: token.borderRadiusSM,
colorItemText: colorText,
colorItemTextHover: colorText,
colorItemTextHoverHorizontal: colorPrimary,
colorGroupTitle: colorTextDescription,
colorItemTextSelected: colorText,
colorItemTextSelectedHorizontal: colorPrimary,
colorItemBg: colorBgContainer,
colorItemBgHover: colorBgTextHover,
colorItemBgActive: colorFillContent,
colorSubItemBg: colorFillAlter,
colorItemBgSelected: controlItemBgActiveHover,
colorItemBgSelectedHorizontal: 'transparent',
colorActiveBarWidth: 0,
colorActiveBarHeight: lineWidthBold,
colorActiveBarBorderSize: lineWidth,
// Disabled
colorItemTextDisabled: colorTextDisabled,
// Danger
colorDangerItemText: colorError,
colorDangerItemTextHover: colorError,
colorDangerItemTextSelected: colorError,
colorDangerItemBgActive: colorErrorBg,
colorDangerItemBgSelected: colorErrorBg,
itemMarginInline: token.marginXXS
};
});
return useOriginHook(prefixCls);
});
var __rest$a = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
/** @internal Only used for Dropdown component. Do not use this in your production. */
var OverrideContext = /*#__PURE__*/React.createContext(null);
/** @internal Only used for Dropdown component. Do not use this in your production. */
var OverrideProvider = function OverrideProvider(_a) {
var children = _a.children,
restProps = __rest$a(_a, ["children"]);
var override = React.useContext(OverrideContext);
var context = React.useMemo(function () {
return _extends$1(_extends$1({}, override), restProps);
}, [override, restProps.prefixCls,
// restProps.expandIcon, Not mark as deps since this is a ReactNode
restProps.mode, restProps.selectable
// restProps.validator, Not mark as deps since this is a function
]);
return /*#__PURE__*/React.createElement(OverrideContext.Provider, {
value: context
}, children);
};
var __rest$9 = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var MenuDivider = function MenuDivider(_a) {
var customizePrefixCls = _a.prefixCls,
className = _a.className,
dashed = _a.dashed,
restProps = __rest$9(_a, ["prefixCls", "className", "dashed"]);
var _React$useContext = React.useContext(ConfigContext),
getPrefixCls = _React$useContext.getPrefixCls;
var prefixCls = getPrefixCls('menu', customizePrefixCls);
var classString = classNames(_defineProperty$1({}, prefixCls + "-item-divider-dashed", !!dashed), className);
return /*#__PURE__*/React.createElement(Divider, _extends$1({
className: classString
}, restProps));
};
var MenuDivider$1 = MenuDivider;
var BarsOutlined = function BarsOutlined(props, ref) {
return /*#__PURE__*/React.createElement(AntdIcon, _objectSpread2$1(_objectSpread2$1({}, props), {}, {
ref: ref,
icon: BarsOutlinedSvg
}));
};
BarsOutlined.displayName = 'BarsOutlined';
var BarsOutlined$1 = /*#__PURE__*/React.forwardRef(BarsOutlined);
var LeftOutlined = function LeftOutlined(props, ref) {
return /*#__PURE__*/React.createElement(AntdIcon, _objectSpread2$1(_objectSpread2$1({}, props), {}, {
ref: ref,
icon: LeftOutlinedSvg
}));
};
LeftOutlined.displayName = 'LeftOutlined';
var LeftOutlined$1 = /*#__PURE__*/React.forwardRef(LeftOutlined);
var RightOutlined = function RightOutlined(props, ref) {
return /*#__PURE__*/React.createElement(AntdIcon, _objectSpread2$1(_objectSpread2$1({}, props), {}, {
ref: ref,
icon: RightOutlinedSvg
}));
};
RightOutlined.displayName = 'RightOutlined';
var RightOutlined$1 = /*#__PURE__*/React.forwardRef(RightOutlined);
var isNumeric = function isNumeric(value) {
return !isNaN(parseFloat(value)) && isFinite(value);
};
var isNumeric$1 = isNumeric;
var genLayoutLightStyle = function genLayoutLightStyle(token) {
var _ref;
var componentCls = token.componentCls,
colorBgContainer = token.colorBgContainer,
colorBgBody = token.colorBgBody,
colorText = token.colorText;
return _defineProperty$1({}, componentCls + "-sider-light", (_ref = {
background: colorBgContainer
}, _defineProperty$1(_ref, componentCls + "-sider-trigger", {
color: colorText,
background: colorBgContainer
}), _defineProperty$1(_ref, componentCls + "-sider-zero-width-trigger", {
color: colorText,
background: colorBgContainer,
border: "1px solid " + colorBgBody,
borderInlineStart: 0
}), _ref));
};
var genLayoutLightStyle$1 = genLayoutLightStyle;
var genLayoutStyle = function genLayoutStyle(token) {
var _extends2;
var antCls = token.antCls,
componentCls = token.componentCls,
colorText = token.colorText,
colorTextLightSolid = token.colorTextLightSolid,
colorBgHeader = token.colorBgHeader,
colorBgBody = token.colorBgBody,
colorBgTrigger = token.colorBgTrigger,
layoutHeaderHeight = token.layoutHeaderHeight,
layoutHeaderPaddingInline = token.layoutHeaderPaddingInline,
layoutHeaderColor = token.layoutHeaderColor,
layoutFooterPadding = token.layoutFooterPadding,
layoutTriggerHeight = token.layoutTriggerHeight,
layoutZeroTriggerSize = token.layoutZeroTriggerSize,
motionDurationMid = token.motionDurationMid,
motionDurationSlow = token.motionDurationSlow,
fontSize = token.fontSize,
borderRadius = token.borderRadius;
return _defineProperty$1({}, componentCls, _extends$1(_extends$1((_extends2 = {
display: 'flex',
flex: 'auto',
flexDirection: 'column',
/* fix firefox can't set height smaller than content on flex item */
minHeight: 0,
background: colorBgBody,
'&, *': {
boxSizing: 'border-box'
}
}, _defineProperty$1(_extends2, "&" + componentCls + "-has-sider", _defineProperty$1({
flexDirection: 'row'
}, "> " + componentCls + ", > " + componentCls + "-content", {
// https://segmentfault.com/a/1190000019498300
width: 0
})), _defineProperty$1(_extends2, componentCls + "-header, &" + componentCls + "-footer", {
flex: '0 0 auto'
}), _defineProperty$1(_extends2, componentCls + "-header", _defineProperty$1({
height: layoutHeaderHeight,
paddingInline: layoutHeaderPaddingInline,
color: layoutHeaderColor,
lineHeight: layoutHeaderHeight + "px",
background: colorBgHeader
}, antCls + "-menu", {
lineHeight: 'inherit'
})), _defineProperty$1(_extends2, componentCls + "-footer", {
padding: layoutFooterPadding,
color: colorText,
fontSize: fontSize,
background: colorBgBody
}), _defineProperty$1(_extends2, componentCls + "-content", {
flex: 'auto',
// fix firefox can't set height smaller than content on flex item
minHeight: 0
}), _defineProperty$1(_extends2, componentCls + "-sider", {
position: 'relative',
// fix firefox can't set width smaller than content on flex item
minWidth: 0,
background: colorBgHeader,
transition: "all " + motionDurationMid,
'&-children': _defineProperty$1({
height: '100%',
// Hack for fixing margin collapse bug
// https://github.com/ant-design/ant-design/issues/7967
// solution from https://stackoverflow.com/a/33132624/3040605
marginTop: -0.1,
paddingTop: 0.1
}, antCls + "-menu" + antCls + "-menu-inline-collapsed", {
width: 'auto'
}),
'&-has-trigger': {
paddingBottom: layoutTriggerHeight
},
'&-right': {
order: 1
},
'&-trigger': {
position: 'fixed',
bottom: 0,
zIndex: 1,
height: layoutTriggerHeight,
color: colorTextLightSolid,
lineHeight: layoutTriggerHeight + "px",
textAlign: 'center',
background: colorBgTrigger,
cursor: 'pointer',
transition: "all " + motionDurationMid
},
'&-zero-width': {
'> *': {
overflow: 'hidden'
},
'&-trigger': {
position: 'absolute',
top: layoutHeaderHeight,
insetInlineEnd: -layoutZeroTriggerSize,
zIndex: 1,
width: layoutZeroTriggerSize,
height: layoutZeroTriggerSize,
color: colorTextLightSolid,
fontSize: token.fontSizeXL,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: colorBgHeader,
borderStartStartRadius: 0,
borderStartEndRadius: borderRadius,
borderEndEndRadius: borderRadius,
borderEndStartRadius: 0,
cursor: 'pointer',
transition: "background " + motionDurationSlow + " ease",
'&::after': {
position: 'absolute',
inset: 0,
background: 'transparent',
transition: "all " + motionDurationSlow,
content: '""'
},
'&:hover::after': {
// FIXME: Hardcode, but seems no need to create a token for this
background: "rgba(255, 255, 255, 0.2)"
},
'&-right': {
insetInlineStart: -layoutZeroTriggerSize,
borderStartStartRadius: borderRadius,
borderStartEndRadius: 0,
borderEndEndRadius: 0,
borderEndStartRadius: borderRadius
}
}
}
}), _extends2), genLayoutLightStyle$1(token)), {
// RTL
'&-rtl': {
direction: 'rtl'
}
}));
};
// ============================== Export ==============================
var useStyle$3 = genComponentStyleHook('Layout', function (token) {
var colorText = token.colorText,
controlHeightSM = token.controlHeightSM,
controlHeight = token.controlHeight,
controlHeightLG = token.controlHeightLG,
marginXXS = token.marginXXS;
var layoutHeaderPaddingInline = controlHeightLG * 1.25;
var layoutToken = merge(token, {
// Layout
layoutHeaderHeight: controlHeight * 2,
layoutHeaderPaddingInline: layoutHeaderPaddingInline,
layoutHeaderColor: colorText,
layoutFooterPadding: controlHeightSM + "px " + layoutHeaderPaddingInline + "px",
layoutTriggerHeight: controlHeightLG + marginXXS * 2,
layoutZeroTriggerSize: controlHeightLG
});
return [genLayoutStyle(layoutToken)];
}, function (token) {
var colorBgLayout = token.colorBgLayout;
return {
colorBgHeader: '#001529',
colorBgBody: colorBgLayout,
colorBgTrigger: '#002140'
};
});
var __rest$8 = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var LayoutContext = /*#__PURE__*/React.createContext({
siderHook: {
addSider: function addSider() {
return null;
},
removeSider: function removeSider() {
return null;
}
}
});
function generator(_ref) {
var suffixCls = _ref.suffixCls,
tagName = _ref.tagName,
displayName = _ref.displayName;
return function (BasicComponent) {
var Adapter = /*#__PURE__*/React.forwardRef(function (props, ref) {
var _React$useContext = React.useContext(ConfigContext),
getPrefixCls = _React$useContext.getPrefixCls;
var customizePrefixCls = props.prefixCls;
var prefixCls = getPrefixCls(suffixCls, customizePrefixCls);
return /*#__PURE__*/React.createElement(BasicComponent, _extends$1({
ref: ref,
prefixCls: prefixCls,
tagName: tagName
}, props));
});
if (process.env.NODE_ENV !== 'production') {
Adapter.displayName = displayName;
}
return Adapter;
};
}
var Basic = /*#__PURE__*/React.forwardRef(function (props, ref) {
var prefixCls = props.prefixCls,
className = props.className,
children = props.children,
tagName = props.tagName,
others = __rest$8(props, ["prefixCls", "className", "children", "tagName"]);
var classString = classNames(prefixCls, className);
return /*#__PURE__*/React.createElement(tagName, _extends$1(_extends$1({
className: classString
}, others), {
ref: ref
}), children);
});
var BasicLayout = /*#__PURE__*/React.forwardRef(function (props, ref) {
var _classNames;
var _React$useContext2 = React.useContext(ConfigContext),
direction = _React$useContext2.direction;
var _React$useState = React.useState([]),
_React$useState2 = _slicedToArray(_React$useState, 2),
siders = _React$useState2[0],
setSiders = _React$useState2[1];
var prefixCls = props.prefixCls,
className = props.className,
children = props.children,
hasSider = props.hasSider,
Tag = props.tagName,
others = __rest$8(props, ["prefixCls", "className", "children", "hasSider", "tagName"]);
var _useStyle = useStyle$3(prefixCls),
_useStyle2 = _slicedToArray(_useStyle, 2),
wrapSSR = _useStyle2[0],
hashId = _useStyle2[1];
var classString = classNames(prefixCls, (_classNames = {}, _defineProperty$1(_classNames, prefixCls + "-has-sider", typeof hasSider === 'boolean' ? hasSider : siders.length > 0), _defineProperty$1(_classNames, prefixCls + "-rtl", direction === 'rtl'), _classNames), className, hashId);
var contextValue = React.useMemo(function () {
return {
siderHook: {
addSider: function addSider(id) {
setSiders(function (prev) {
return [].concat(_toConsumableArray(prev), [id]);
});
},
removeSider: function removeSider(id) {
setSiders(function (prev) {
return prev.filter(function (currentId) {
return currentId !== id;
});
});
}
}
};
}, []);
return wrapSSR( /*#__PURE__*/React.createElement(LayoutContext.Provider, {
value: contextValue
}, /*#__PURE__*/React.createElement(Tag, _extends$1({
ref: ref,
className: classString
}, others), children)));
});
generator({
suffixCls: 'layout',
tagName: 'section',
displayName: 'Layout'
})(BasicLayout);
generator({
suffixCls: 'layout-header',
tagName: 'header',
displayName: 'Header'
})(Basic);
generator({
suffixCls: 'layout-footer',
tagName: 'footer',
displayName: 'Footer'
})(Basic);
generator({
suffixCls: 'layout-content',
tagName: 'main',
displayName: 'Content'
})(Basic);
var __rest$7 = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var dimensionMaxMap = {
xs: '479.98px',
sm: '575.98px',
md: '767.98px',
lg: '991.98px',
xl: '1199.98px',
xxl: '1599.98px'
};
var SiderContext = /*#__PURE__*/React.createContext({});
var generateId = function () {
var i = 0;
return function () {
var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
i += 1;
return "" + prefix + i;
};
}();
var Sider = /*#__PURE__*/React.forwardRef(function (_a, ref) {
var customizePrefixCls = _a.prefixCls,
className = _a.className,
trigger = _a.trigger,
children = _a.children,
_a$defaultCollapsed = _a.defaultCollapsed,
defaultCollapsed = _a$defaultCollapsed === void 0 ? false : _a$defaultCollapsed,
_a$theme = _a.theme,
theme = _a$theme === void 0 ? 'dark' : _a$theme,
_a$style = _a.style,
style = _a$style === void 0 ? {} : _a$style,
_a$collapsible = _a.collapsible,
collapsible = _a$collapsible === void 0 ? false : _a$collapsible,
_a$reverseArrow = _a.reverseArrow,
reverseArrow = _a$reverseArrow === void 0 ? false : _a$reverseArrow,
_a$width = _a.width,
width = _a$width === void 0 ? 200 : _a$width,
_a$collapsedWidth = _a.collapsedWidth,
collapsedWidth = _a$collapsedWidth === void 0 ? 80 : _a$collapsedWidth,
zeroWidthTriggerStyle = _a.zeroWidthTriggerStyle,
breakpoint = _a.breakpoint,
onCollapse = _a.onCollapse,
onBreakpoint = _a.onBreakpoint,
props = __rest$7(_a, ["prefixCls", "className", "trigger", "children", "defaultCollapsed", "theme", "style", "collapsible", "reverseArrow", "width", "collapsedWidth", "zeroWidthTriggerStyle", "breakpoint", "onCollapse", "onBreakpoint"]);
var _useContext = useContext(LayoutContext),
siderHook = _useContext.siderHook;
var _useState = useState('collapsed' in props ? props.collapsed : defaultCollapsed),
_useState2 = _slicedToArray(_useState, 2),
collapsed = _useState2[0],
setCollapsed = _useState2[1];
var _useState3 = useState(false),
_useState4 = _slicedToArray(_useState3, 2),
below = _useState4[0],
setBelow = _useState4[1];
useEffect(function () {
if ('collapsed' in props) {
setCollapsed(props.collapsed);
}
}, [props.collapsed]);
var handleSetCollapsed = function handleSetCollapsed(value, type) {
if (!('collapsed' in props)) {
setCollapsed(value);
}
onCollapse === null || onCollapse === void 0 ? void 0 : onCollapse(value, type);
};
// ========================= Responsive =========================
var responsiveHandlerRef = useRef();
responsiveHandlerRef.current = function (mql) {
setBelow(mql.matches);
onBreakpoint === null || onBreakpoint === void 0 ? void 0 : onBreakpoint(mql.matches);
if (collapsed !== mql.matches) {
handleSetCollapsed(mql.matches, 'responsive');
}
};
useEffect(function () {
function responsiveHandler(mql) {
return responsiveHandlerRef.current(mql);
}
var mql;
if (typeof window !== 'undefined') {
var _window = window,
matchMedia = _window.matchMedia;
if (matchMedia && breakpoint && breakpoint in dimensionMaxMap) {
mql = matchMedia("(max-width: " + dimensionMaxMap[breakpoint] + ")");
try {
mql.addEventListener('change', responsiveHandler);
} catch (error) {
mql.addListener(responsiveHandler);
}
responsiveHandler(mql);
}
}
return function () {
try {
mql === null || mql === void 0 ? void 0 : mql.removeEventListener('change', responsiveHandler);
} catch (error) {
mql === null || mql === void 0 ? void 0 : mql.removeListener(responsiveHandler);
}
};
}, [breakpoint]); // in order to accept dynamic 'breakpoint' property, we need to add 'breakpoint' into dependency array.
useEffect(function () {
var uniqueId = generateId('ant-sider-');
siderHook.addSider(uniqueId);
return function () {
return siderHook.removeSider(uniqueId);
};
}, []);
var toggle = function toggle() {
handleSetCollapsed(!collapsed, 'clickTrigger');
};
var _useContext2 = useContext(ConfigContext),
getPrefixCls = _useContext2.getPrefixCls;
var renderSider = function renderSider() {
var _classNames;
var prefixCls = getPrefixCls('layout-sider', customizePrefixCls);
var divProps = omit(props, ['collapsed']);
var rawWidth = collapsed ? collapsedWidth : width;
// use "px" as fallback unit for width
var siderWidth = isNumeric$1(rawWidth) ? rawWidth + "px" : String(rawWidth);
// special trigger when collapsedWidth == 0
var zeroWidthTrigger = parseFloat(String(collapsedWidth || 0)) === 0 ? /*#__PURE__*/React.createElement("span", {
onClick: toggle,
className: classNames(prefixCls + "-zero-width-trigger", prefixCls + "-zero-width-trigger-" + (reverseArrow ? 'right' : 'left')),
style: zeroWidthTriggerStyle
}, trigger || /*#__PURE__*/React.createElement(BarsOutlined$1, null)) : null;
var iconObj = {
expanded: reverseArrow ? /*#__PURE__*/React.createElement(RightOutlined$1, null) : /*#__PURE__*/React.createElement(LeftOutlined$1, null),
collapsed: reverseArrow ? /*#__PURE__*/React.createElement(LeftOutlined$1, null) : /*#__PURE__*/React.createElement(RightOutlined$1, null)
};
var status = collapsed ? 'collapsed' : 'expanded';
var defaultTrigger = iconObj[status];
var triggerDom = trigger !== null ? zeroWidthTrigger || /*#__PURE__*/React.createElement("div", {
className: prefixCls + "-trigger",
onClick: toggle,
style: {
width: siderWidth
}
}, trigger || defaultTrigger) : null;
var divStyle = _extends$1(_extends$1({}, style), {
flex: "0 0 " + siderWidth,
maxWidth: siderWidth,
minWidth: siderWidth,
width: siderWidth
});
var siderCls = classNames(prefixCls, prefixCls + "-" + theme, (_classNames = {}, _defineProperty$1(_classNames, prefixCls + "-collapsed", !!collapsed), _defineProperty$1(_classNames, prefixCls + "-has-trigger", collapsible && trigger !== null && !zeroWidthTrigger), _defineProperty$1(_classNames, prefixCls + "-below", !!below), _defineProperty$1(_classNames, prefixCls + "-zero-width", parseFloat(siderWidth) === 0), _classNames), className);
return /*#__PURE__*/React.createElement("aside", _extends$1({
className: siderCls
}, divProps, {
style: divStyle,
ref: ref
}), /*#__PURE__*/React.createElement("div", {
className: prefixCls + "-children"
}, children), collapsible || below && zeroWidthTrigger ? triggerDom : null);
};
var contextValue = React.useMemo(function () {
return {
siderCollapsed: collapsed
};
}, [collapsed]);
return /*#__PURE__*/React.createElement(SiderContext.Provider, {
value: contextValue
}, renderSider());
});
if (process.env.NODE_ENV !== 'production') {
Sider.displayName = 'Sider';
}
var MenuContext = /*#__PURE__*/createContext({
prefixCls: '',
firstLevel: true,
inlineCollapsed: false
});
var MenuContext$1 = MenuContext;
var __rest$6 = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var MenuItem = /*#__PURE__*/function (_React$Component) {
_inherits(MenuItem, _React$Component);
var _super = _createSuper(MenuItem);
function MenuItem() {
var _this;
_classCallCheck(this, MenuItem);
_this = _super.apply(this, arguments);
_this.renderItem = function (_ref) {
var _classNames;
var siderCollapsed = _ref.siderCollapsed;
var _a;
var _this$context = _this.context,
prefixCls = _this$context.prefixCls,
firstLevel = _this$context.firstLevel,
inlineCollapsed = _this$context.inlineCollapsed,
direction = _this$context.direction,
disableMenuItemTitleTooltip = _this$context.disableMenuItemTitleTooltip;
var _this$props = _this.props,
className = _this$props.className,
children = _this$props.children;
var _b = _this.props,
title = _b.title,
icon = _b.icon,
danger = _b.danger,
rest = __rest$6(_b, ["title", "icon", "danger"]);
var tooltipTitle = title;
if (typeof title === 'undefined') {
tooltipTitle = firstLevel ? children : '';
} else if (title === false) {
tooltipTitle = '';
}
var tooltipProps = {
title: tooltipTitle
};
if (!siderCollapsed && !inlineCollapsed) {
tooltipProps.title = null;
// Reset `open` to fix control mode tooltip display not correct
// ref: https://github.com/ant-design/ant-design/issues/16742
tooltipProps.open = false;
}
var childrenLength = toArray$1(children).length;
var returnNode = /*#__PURE__*/React.createElement(MenuItem$2, _extends$1({}, rest, {
className: classNames((_classNames = {}, _defineProperty$1(_classNames, prefixCls + "-item-danger", danger), _defineProperty$1(_classNames, prefixCls + "-item-only-child", (icon ? childrenLength + 1 : childrenLength) === 1), _classNames), className),
title: typeof title === 'string' ? title : undefined
}), cloneElement(icon, {
className: classNames(isValidElement(icon) ? (_a = icon.props) === null || _a === void 0 ? void 0 : _a.className : '', prefixCls + "-item-icon")
}), _this.renderItemChildren(inlineCollapsed));
if (!disableMenuItemTitleTooltip) {
returnNode = /*#__PURE__*/React.createElement(Tooltip$1, _extends$1({}, tooltipProps, {
placement: direction === 'rtl' ? 'left' : 'right',
overlayClassName: prefixCls + "-inline-collapsed-tooltip"
}), returnNode);
}
return returnNode;
};
return _this;
}
_createClass(MenuItem, [{
key: "renderItemChildren",
value: function renderItemChildren(inlineCollapsed) {
var _this$context2 = this.context,
prefixCls = _this$context2.prefixCls,
firstLevel = _this$context2.firstLevel;
var _this$props2 = this.props,
icon = _this$props2.icon,
children = _this$props2.children;
var wrapNode = /*#__PURE__*/React.createElement("span", {
className: prefixCls + "-title-content"
}, children);
// inline-collapsed.md demo 依赖 span 来隐藏文字,有 icon 属性,则内部包裹一个 span
// ref: https://github.com/ant-design/ant-design/pull/23456
if (!icon || isValidElement(children) && children.type === 'span') {
if (children && inlineCollapsed && firstLevel && typeof children === 'string') {
return /*#__PURE__*/React.createElement("div", {
className: prefixCls + "-inline-collapsed-noicon"
}, children.charAt(0));
}
}
return wrapNode;
}
}, {
key: "render",
value: function render() {
return /*#__PURE__*/React.createElement(SiderContext.Consumer, null, this.renderItem);
}
}]);
return MenuItem;
}(React.Component);
MenuItem.contextType = MenuContext$1;
function SubMenu(props) {
var _a;
var popupClassName = props.popupClassName,
icon = props.icon,
title = props.title,
customTheme = props.theme;
var context = React.useContext(MenuContext$1);
var prefixCls = context.prefixCls,
inlineCollapsed = context.inlineCollapsed,
contextTheme = context.theme,
mode = context.mode;
var parentPath = useFullPath();
var titleNode;
if (!icon) {
titleNode = inlineCollapsed && !parentPath.length && title && typeof title === 'string' ? /*#__PURE__*/React.createElement("div", {
className: prefixCls + "-inline-collapsed-noicon"
}, title.charAt(0)) : /*#__PURE__*/React.createElement("span", {
className: prefixCls + "-title-content"
}, title);
} else {
// inline-collapsed.md demo 依赖 span 来隐藏文字,有 icon 属性,则内部包裹一个 span
// ref: https://github.com/ant-design/ant-design/pull/23456
var titleIsSpan = isValidElement(title) && title.type === 'span';
titleNode = /*#__PURE__*/React.createElement(React.Fragment, null, cloneElement(icon, {
className: classNames(isValidElement(icon) ? (_a = icon.props) === null || _a === void 0 ? void 0 : _a.className : '', prefixCls + "-item-icon")
}), titleIsSpan ? title : /*#__PURE__*/React.createElement("span", {
className: prefixCls + "-title-content"
}, title));
}
var contextValue = React.useMemo(function () {
return _extends$1(_extends$1({}, context), {
firstLevel: false
});
}, [context]);
var popupOffset = mode === 'horizontal' ? [0, 8] : [10, 0];
return /*#__PURE__*/React.createElement(MenuContext$1.Provider, {
value: contextValue
}, /*#__PURE__*/React.createElement(SubMenu$1, _extends$1({
popupOffset: popupOffset
}, omit(props, ['icon']), {
title: titleNode,
popupClassName: classNames(prefixCls, popupClassName, prefixCls + "-" + (customTheme || contextTheme))
})));
}
var __rest$5 = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
function convertItemsToNodes(list) {
return (list || []).map(function (opt, index) {
if (opt && _typeof$1(opt) === 'object') {
var _a = opt,
label = _a.label,
children = _a.children,
key = _a.key,
type = _a.type,
restProps = __rest$5(_a, ["label", "children", "key", "type"]);
var mergedKey = key !== null && key !== void 0 ? key : "tmp-" + index;
// MenuItemGroup & SubMenuItem
if (children || type === 'group') {
if (type === 'group') {
// Group
return /*#__PURE__*/React.createElement(MenuItemGroup, _extends$1({
key: mergedKey
}, restProps, {
title: label
}), convertItemsToNodes(children));
}
// Sub Menu
return /*#__PURE__*/React.createElement(SubMenu, _extends$1({
key: mergedKey
}, restProps, {
title: label
}), convertItemsToNodes(children));
}
// MenuItem & Divider
if (type === 'divider') {
return /*#__PURE__*/React.createElement(MenuDivider$1, _extends$1({
key: mergedKey
}, restProps));
}
return /*#__PURE__*/React.createElement(MenuItem, _extends$1({
key: mergedKey
}, restProps), label);
}
return null;
}).filter(function (opt) {
return opt;
});
}
// FIXME: Move logic here in v5
/**
* We simply convert `items` to ReactNode for reuse origin component logic. But we need move all the
* logic from component into this hooks when in v5
*/
function useItems(items) {
return React.useMemo(function () {
if (!items) {
return items;
}
return convertItemsToNodes(items);
}, [items]);
}
var __rest$4 = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var InternalMenu = /*#__PURE__*/forwardRef(function (props, ref) {
var _a;
var override = React.useContext(OverrideContext);
var overrideObj = override || {};
var _React$useContext = React.useContext(ConfigContext),
getPrefixCls = _React$useContext.getPrefixCls,
getPopupContainer = _React$useContext.getPopupContainer,
direction = _React$useContext.direction;
var rootPrefixCls = getPrefixCls();
var customizePrefixCls = props.prefixCls,
className = props.className,
_props$theme = props.theme,
theme = _props$theme === void 0 ? 'light' : _props$theme,
expandIcon = props.expandIcon,
_internalDisableMenuItemTitleTooltip = props._internalDisableMenuItemTitleTooltip,
inlineCollapsed = props.inlineCollapsed,
siderCollapsed = props.siderCollapsed,
items = props.items,
children = props.children,
rootClassName = props.rootClassName,
mode = props.mode,
selectable = props.selectable,
onClick = props.onClick,
restProps = __rest$4(props, ["prefixCls", "className", "theme", "expandIcon", "_internalDisableMenuItemTitleTooltip", "inlineCollapsed", "siderCollapsed", "items", "children", "rootClassName", "mode", "selectable", "onClick"]);
var passedProps = omit(restProps, ['collapsedWidth']);
// ========================= Items ===========================
var mergedChildren = useItems(items) || children;
// ======================== Warning ==========================
process.env.NODE_ENV !== "production" ? warning$2(!('inlineCollapsed' in props && mode !== 'inline'), 'Menu', '`inlineCollapsed` should only be used when `mode` is inline.') : void 0;
process.env.NODE_ENV !== "production" ? warning$2(!(props.siderCollapsed !== undefined && 'inlineCollapsed' in props), 'Menu', '`inlineCollapsed` not control Menu under Sider. Should set `collapsed` on Sider instead.') : void 0;
process.env.NODE_ENV !== "production" ? warning$2('items' in props && !children, 'Menu', '`children` will be removed in next major version. Please use `items` instead.') : void 0;
(_a = overrideObj.validator) === null || _a === void 0 ? void 0 : _a.call(overrideObj, {
mode: mode
});
// ========================== Click ==========================
// Tell dropdown that item clicked
var onItemClick = useEvent(function () {
var _a;
onClick === null || onClick === void 0 ? void 0 : onClick.apply(void 0, arguments);
(_a = overrideObj.onClick) === null || _a === void 0 ? void 0 : _a.call(overrideObj);
});
// ========================== Mode ===========================
var mergedMode = overrideObj.mode || mode;
// ======================= Selectable ========================
var mergedSelectable = selectable !== null && selectable !== void 0 ? selectable : overrideObj.selectable;
// ======================== Collapsed ========================
// Inline Collapsed
var mergedInlineCollapsed = React.useMemo(function () {
if (siderCollapsed !== undefined) {
return siderCollapsed;
}
return inlineCollapsed;
}, [inlineCollapsed, siderCollapsed]);
var defaultMotions = {
horizontal: {
motionName: rootPrefixCls + "-slide-up"
},
inline: initCollapseMotion(rootPrefixCls),
other: {
motionName: rootPrefixCls + "-zoom-big"
}
};
var prefixCls = getPrefixCls('menu', customizePrefixCls || overrideObj.prefixCls);
var _useStyle = useStyle$4(prefixCls, !override),
_useStyle2 = _slicedToArray(_useStyle, 2),
wrapSSR = _useStyle2[0],
hashId = _useStyle2[1];
var menuClassName = classNames(prefixCls + "-" + theme, className);
// ====================== Expand Icon ========================
var mergedExpandIcon;
if (typeof expandIcon === 'function') {
mergedExpandIcon = expandIcon;
} else {
mergedExpandIcon = cloneElement(expandIcon || overrideObj.expandIcon, {
className: prefixCls + "-submenu-expand-icon"
});
}
// ======================== Context ==========================
var contextValue = React.useMemo(function () {
return {
prefixCls: prefixCls,
inlineCollapsed: mergedInlineCollapsed || false,
direction: direction,
firstLevel: true,
theme: theme,
mode: mergedMode,
disableMenuItemTitleTooltip: _internalDisableMenuItemTitleTooltip
};
}, [prefixCls, mergedInlineCollapsed, direction, _internalDisableMenuItemTitleTooltip, theme]);
// ========================= Render ==========================
return wrapSSR( /*#__PURE__*/React.createElement(OverrideContext.Provider, {
value: null
}, /*#__PURE__*/React.createElement(MenuContext$1.Provider, {
value: contextValue
}, /*#__PURE__*/React.createElement(ExportMenu, _extends$1({
getPopupContainer: getPopupContainer,
overflowedIndicator: /*#__PURE__*/React.createElement(EllipsisOutlined$1, null),
overflowedIndicatorPopupClassName: prefixCls + "-" + theme,
mode: mergedMode,
selectable: mergedSelectable,
onClick: onItemClick
}, passedProps, {
inlineCollapsed: mergedInlineCollapsed,
className: menuClassName,
prefixCls: prefixCls,
direction: direction,
defaultMotions: defaultMotions,
expandIcon: mergedExpandIcon,
ref: ref,
rootClassName: classNames(rootClassName, hashId)
}), mergedChildren))));
});
var InternalMenu$1 = InternalMenu;
var Menu = /*#__PURE__*/forwardRef(function (props, ref) {
var menuRef = useRef(null);
var context = React.useContext(SiderContext);
useImperativeHandle(ref, function () {
return {
focus: function focus(options) {
var _a;
(_a = menuRef.current) === null || _a === void 0 ? void 0 : _a.focus(options);
},
menu: menuRef.current
};
});
return /*#__PURE__*/React.createElement(InternalMenu$1, _extends$1({
ref: menuRef
}, props, context));
});
Menu.Divider = MenuDivider$1;
Menu.Item = MenuItem;
Menu.SubMenu = SubMenu;
Menu.ItemGroup = MenuItemGroup;
var Menu$1 = Menu;
var autoAdjustOverflow = {
adjustX: 1,
adjustY: 1
};
var targetOffset = [0, 0];
var placements = {
topLeft: {
points: ['bl', 'tl'],
overflow: autoAdjustOverflow,
offset: [0, -4],
targetOffset: targetOffset
},
topCenter: {
points: ['bc', 'tc'],
overflow: autoAdjustOverflow,
offset: [0, -4],
targetOffset: targetOffset
},
topRight: {
points: ['br', 'tr'],
overflow: autoAdjustOverflow,
offset: [0, -4],
targetOffset: targetOffset
},
bottomLeft: {
points: ['tl', 'bl'],
overflow: autoAdjustOverflow,
offset: [0, 4],
targetOffset: targetOffset
},
bottomCenter: {
points: ['tc', 'bc'],
overflow: autoAdjustOverflow,
offset: [0, 4],
targetOffset: targetOffset
},
bottomRight: {
points: ['tr', 'br'],
overflow: autoAdjustOverflow,
offset: [0, 4],
targetOffset: targetOffset
}
};
var ESC = KeyCode.ESC,
TAB = KeyCode.TAB;
function useAccessibility(_ref) {
var visible = _ref.visible,
setTriggerVisible = _ref.setTriggerVisible,
triggerRef = _ref.triggerRef,
onVisibleChange = _ref.onVisibleChange,
autoFocus = _ref.autoFocus;
var focusMenuRef = React.useRef(false);
var handleCloseMenuAndReturnFocus = function handleCloseMenuAndReturnFocus() {
if (visible && triggerRef.current) {
var _triggerRef$current, _triggerRef$current$t, _triggerRef$current$t2, _triggerRef$current$t3;
(_triggerRef$current = triggerRef.current) === null || _triggerRef$current === void 0 ? void 0 : (_triggerRef$current$t = _triggerRef$current.triggerRef) === null || _triggerRef$current$t === void 0 ? void 0 : (_triggerRef$current$t2 = _triggerRef$current$t.current) === null || _triggerRef$current$t2 === void 0 ? void 0 : (_triggerRef$current$t3 = _triggerRef$current$t2.focus) === null || _triggerRef$current$t3 === void 0 ? void 0 : _triggerRef$current$t3.call(_triggerRef$current$t2);
setTriggerVisible(false);
if (typeof onVisibleChange === 'function') {
onVisibleChange(false);
}
}
};
var focusMenu = function focusMenu() {
var _triggerRef$current2, _triggerRef$current2$, _triggerRef$current2$2, _triggerRef$current2$3;
var elements = getFocusNodeList((_triggerRef$current2 = triggerRef.current) === null || _triggerRef$current2 === void 0 ? void 0 : (_triggerRef$current2$ = _triggerRef$current2.popupRef) === null || _triggerRef$current2$ === void 0 ? void 0 : (_triggerRef$current2$2 = _triggerRef$current2$.current) === null || _triggerRef$current2$2 === void 0 ? void 0 : (_triggerRef$current2$3 = _triggerRef$current2$2.getElement) === null || _triggerRef$current2$3 === void 0 ? void 0 : _triggerRef$current2$3.call(_triggerRef$current2$2));
var firstElement = elements[0];
if (firstElement === null || firstElement === void 0 ? void 0 : firstElement.focus) {
firstElement.focus();
focusMenuRef.current = true;
return true;
}
return false;
};
var handleKeyDown = function handleKeyDown(event) {
switch (event.keyCode) {
case ESC:
handleCloseMenuAndReturnFocus();
break;
case TAB:
{
var focusResult = false;
if (!focusMenuRef.current) {
focusResult = focusMenu();
}
if (focusResult) {
event.preventDefault();
} else {
handleCloseMenuAndReturnFocus();
}
break;
}
}
};
React.useEffect(function () {
if (visible) {
window.addEventListener('keydown', handleKeyDown);
if (autoFocus) {
// FIXME: hack with raf
wrapperRaf$1(focusMenu, 3);
}
return function () {
window.removeEventListener('keydown', handleKeyDown);
focusMenuRef.current = false;
};
}
return function () {
focusMenuRef.current = false;
};
}, [visible]); // eslint-disable-line react-hooks/exhaustive-deps
}
var _excluded = ["arrow", "prefixCls", "transitionName", "animation", "align", "placement", "placements", "getPopupContainer", "showAction", "hideAction", "overlayClassName", "overlayStyle", "visible", "trigger", "autoFocus"];
function Dropdown$2(props, ref) {
var _props$arrow = props.arrow,
arrow = _props$arrow === void 0 ? false : _props$arrow,
_props$prefixCls = props.prefixCls,
prefixCls = _props$prefixCls === void 0 ? 'rc-dropdown' : _props$prefixCls,
transitionName = props.transitionName,
animation = props.animation,
align = props.align,
_props$placement = props.placement,
placement = _props$placement === void 0 ? 'bottomLeft' : _props$placement,
_props$placements = props.placements,
placements$1 = _props$placements === void 0 ? placements : _props$placements,
getPopupContainer = props.getPopupContainer,
showAction = props.showAction,
hideAction = props.hideAction,
overlayClassName = props.overlayClassName,
overlayStyle = props.overlayStyle,
visible = props.visible,
_props$trigger = props.trigger,
trigger = _props$trigger === void 0 ? ['hover'] : _props$trigger,
autoFocus = props.autoFocus,
otherProps = _objectWithoutProperties(props, _excluded);
var _React$useState = React.useState(),
_React$useState2 = _slicedToArray(_React$useState, 2),
triggerVisible = _React$useState2[0],
setTriggerVisible = _React$useState2[1];
var mergedVisible = 'visible' in props ? visible : triggerVisible;
var triggerRef = React.useRef(null);
React.useImperativeHandle(ref, function () {
return triggerRef.current;
});
useAccessibility({
visible: mergedVisible,
setTriggerVisible: setTriggerVisible,
triggerRef: triggerRef,
onVisibleChange: props.onVisibleChange,
autoFocus: autoFocus
});
var getOverlayElement = function getOverlayElement() {
var overlay = props.overlay;
var overlayElement;
if (typeof overlay === 'function') {
overlayElement = overlay();
} else {
overlayElement = overlay;
}
return overlayElement;
};
var onClick = function onClick(e) {
var onOverlayClick = props.onOverlayClick;
setTriggerVisible(false);
if (onOverlayClick) {
onOverlayClick(e);
}
};
var onVisibleChange = function onVisibleChange(newVisible) {
var onVisibleChangeProp = props.onVisibleChange;
setTriggerVisible(newVisible);
if (typeof onVisibleChangeProp === 'function') {
onVisibleChangeProp(newVisible);
}
};
var getMenuElement = function getMenuElement() {
var overlayElement = getOverlayElement();
return /*#__PURE__*/React.createElement(React.Fragment, null, arrow && /*#__PURE__*/React.createElement("div", {
className: "".concat(prefixCls, "-arrow")
}), overlayElement);
};
var getMenuElementOrLambda = function getMenuElementOrLambda() {
var overlay = props.overlay;
if (typeof overlay === 'function') {
return getMenuElement;
}
return getMenuElement();
};
var getMinOverlayWidthMatchTrigger = function getMinOverlayWidthMatchTrigger() {
var minOverlayWidthMatchTrigger = props.minOverlayWidthMatchTrigger,
alignPoint = props.alignPoint;
if ('minOverlayWidthMatchTrigger' in props) {
return minOverlayWidthMatchTrigger;
}
return !alignPoint;
};
var getOpenClassName = function getOpenClassName() {
var openClassName = props.openClassName;
if (openClassName !== undefined) {
return openClassName;
}
return "".concat(prefixCls, "-open");
};
var renderChildren = function renderChildren() {
var children = props.children;
var childrenProps = children.props ? children.props : {};
var childClassName = classNames(childrenProps.className, getOpenClassName());
return mergedVisible && children ? /*#__PURE__*/React.cloneElement(children, {
className: childClassName
}) : children;
};
var triggerHideAction = hideAction;
if (!triggerHideAction && trigger.indexOf('contextMenu') !== -1) {
triggerHideAction = ['click'];
}
return /*#__PURE__*/React.createElement(Trigger, _objectSpread2$1(_objectSpread2$1({
builtinPlacements: placements$1
}, otherProps), {}, {
prefixCls: prefixCls,
ref: triggerRef,
popupClassName: classNames(overlayClassName, _defineProperty$1({}, "".concat(prefixCls, "-show-arrow"), arrow)),
popupStyle: overlayStyle,
action: trigger,
showAction: showAction,
hideAction: triggerHideAction || [],
popupPlacement: placement,
popupAlign: align,
popupTransitionName: transitionName,
popupAnimation: animation,
popupVisible: mergedVisible,
stretch: getMinOverlayWidthMatchTrigger() ? 'minWidth' : '',
popup: getMenuElementOrLambda(),
onPopupVisibleChange: onVisibleChange,
onPopupClick: onClick,
getPopupContainer: getPopupContainer
}), renderChildren());
}
var Dropdown$3 = /*#__PURE__*/React.forwardRef(Dropdown$2);
var id = 0;
var ids = {};
// Support call raf with delay specified frame
function wrapperRaf(callback) {
var delayFrames = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var myId = id++;
var restFrames = delayFrames;
function internalCallback() {
restFrames -= 1;
if (restFrames <= 0) {
callback();
delete ids[myId];
} else {
ids[myId] = wrapperRaf$1(internalCallback);
}
}
ids[myId] = wrapperRaf$1(internalCallback);
return myId;
}
wrapperRaf.cancel = function cancel(pid) {
if (pid === undefined) return;
wrapperRaf$1.cancel(ids[pid]);
delete ids[pid];
};
wrapperRaf.ids = ids; // export this for test usage
var genWaveStyle = function genWaveStyle(token) {
var _ref;
var waveEffect = new Keyframe('waveEffect', {
'100%': {
boxShadow: "0 0 0 6px var(--antd-wave-shadow-color)"
}
});
var fadeEffect = new Keyframe('fadeEffect', {
'100%': {
opacity: 0
}
});
return [(_ref = {}, _defineProperty$1(_ref, token.clickAnimatingWithoutExtraNodeTrue + ",\n " + token.clickAnimatingTrue, {
'--antd-wave-shadow-color': token.colorPrimary,
'--scroll-bar': 0,
position: 'relative'
}), _defineProperty$1(_ref, token.clickAnimatingWithoutExtraNodeTrueAfter + ",\n & " + token.clickAnimatingNode, {
position: 'absolute',
top: 0,
insetInlineStart: 0,
insetInlineEnd: 0,
bottom: 0,
display: 'block',
borderRadius: 'inherit',
boxShadow: "0 0 0 0 var(--antd-wave-shadow-color)",
opacity: 0.2,
animation: {
_skip_check_: true,
value: fadeEffect.getName(token.hashId) + " 2s " + token.motionEaseOutCirc + ", " + waveEffect.getName(token.hashId) + " 0.4s " + token.motionEaseOutCirc
},
animationFillMode: 'forwards',
content: '""',
pointerEvents: 'none'
}), _ref), {}, waveEffect, fadeEffect];
};
var useStyle$2 = (function () {
var _useToken = useToken(),
_useToken2 = _slicedToArray(_useToken, 3),
theme = _useToken2[0],
token = _useToken2[1],
hashId = _useToken2[2];
var _useContext = useContext(ConfigContext),
getPrefixCls = _useContext.getPrefixCls;
var rootPrefixCls = getPrefixCls();
var clickAnimatingTrue = "[" + rootPrefixCls + "-click-animating='true']";
var clickAnimatingWithoutExtraNodeTrue = "[" + rootPrefixCls + "-click-animating-without-extra-node='true']";
var clickAnimatingNode = "." + rootPrefixCls + "-click-animating-node";
var waveToken = _extends$1(_extends$1({}, token), {
hashId: hashId,
clickAnimatingNode: clickAnimatingNode,
clickAnimatingTrue: clickAnimatingTrue,
clickAnimatingWithoutExtraNodeTrue: clickAnimatingWithoutExtraNodeTrue,
clickAnimatingWithoutExtraNodeTrueAfter: clickAnimatingWithoutExtraNodeTrue + "::after"
});
return [useStyleRegister({
theme: theme,
token: token,
hashId: hashId,
path: ['wave']
}, function () {
return [genWaveStyle(waveToken)];
}), hashId];
});
var styleForPseudo;
// Where el is the DOM element you'd like to test for visibility
function isHidden(element) {
if (process.env.NODE_ENV === 'test') {
return false;
}
return !element || element.offsetParent === null || element.hidden;
}
function getValidateContainer(nodeRoot) {
if (nodeRoot instanceof Document) {
return nodeRoot.body;
}
return Array.from(nodeRoot.childNodes).find(function (ele) {
return (ele === null || ele === void 0 ? void 0 : ele.nodeType) === Node.ELEMENT_NODE;
});
}
function isNotGrey(color) {
// eslint-disable-next-line no-useless-escape
var match = (color || '').match(/rgba?\((\d*), (\d*), (\d*)(, [\d.]*)?\)/);
if (match && match[1] && match[2] && match[3]) {
return !(match[1] === match[2] && match[2] === match[3]);
}
return true;
}
function isValidWaveColor(color) {
return color && color !== '#fff' && color !== '#ffffff' && color !== 'rgb(255, 255, 255)' && color !== 'rgba(255, 255, 255, 1)' && isNotGrey(color) && !/rgba\((?:\d*, ){3}0\)/.test(color) &&
// any transparent rgba color
color !== 'transparent';
}
function getTargetWaveColor(node) {
var computedStyle = getComputedStyle(node);
var borderTopColor = computedStyle.getPropertyValue('border-top-color');
var borderColor = computedStyle.getPropertyValue('border-color');
var backgroundColor = computedStyle.getPropertyValue('background-color');
if (isValidWaveColor(borderTopColor)) {
return borderTopColor;
}
if (isValidWaveColor(borderColor)) {
return borderColor;
}
return backgroundColor;
}
var InternalWave = /*#__PURE__*/function (_React$Component) {
_inherits(InternalWave, _React$Component);
var _super = _createSuper(InternalWave);
function InternalWave() {
var _this;
_classCallCheck(this, InternalWave);
_this = _super.apply(this, arguments);
_this.containerRef = /*#__PURE__*/React.createRef();
_this.animationStart = false;
_this.destroyed = false;
_this.onClick = function (node, waveColor) {
var _a, _b;
var _this$props = _this.props,
insertExtraNode = _this$props.insertExtraNode,
disabled = _this$props.disabled;
if (disabled || !node || isHidden(node) || node.className.includes('-leave')) {
return;
}
_this.extraNode = document.createElement('div');
var _assertThisInitialize = _assertThisInitialized(_this),
extraNode = _assertThisInitialize.extraNode;
var getPrefixCls = _this.context.getPrefixCls;
extraNode.className = getPrefixCls('') + "-click-animating-node";
var attributeName = _this.getAttributeName();
node.setAttribute(attributeName, 'true');
// Not white or transparent or grey
if (isValidWaveColor(waveColor)) {
extraNode.style.borderColor = waveColor;
var nodeRoot = ((_a = node.getRootNode) === null || _a === void 0 ? void 0 : _a.call(node)) || node.ownerDocument;
var nodeBody = (_b = getValidateContainer(nodeRoot)) !== null && _b !== void 0 ? _b : nodeRoot;
styleForPseudo = updateCSS("\n [" + getPrefixCls('') + "-click-animating-without-extra-node='true']::after, ." + getPrefixCls('') + "-click-animating-node {\n --antd-wave-shadow-color: " + waveColor + ";\n }", 'antd-wave', {
csp: _this.csp,
attachTo: nodeBody
});
}
if (insertExtraNode) {
node.appendChild(extraNode);
}
['transition', 'animation'].forEach(function (name) {
node.addEventListener(name + "start", _this.onTransitionStart);
node.addEventListener(name + "end", _this.onTransitionEnd);
});
};
_this.onTransitionStart = function (e) {
if (_this.destroyed) {
return;
}
var node = _this.containerRef.current;
if (!e || e.target !== node || _this.animationStart) {
return;
}
_this.resetEffect(node);
};
_this.onTransitionEnd = function (e) {
if (!e || e.animationName !== 'fadeEffect') {
return;
}
_this.resetEffect(e.target);
};
_this.bindAnimationEvent = function (node) {
if (!node || !node.getAttribute || node.getAttribute('disabled') || node.className.includes('disabled')) {
return;
}
var onClick = function onClick(e) {
// Fix radio button click twice
if (e.target.tagName === 'INPUT' || isHidden(e.target)) {
return;
}
_this.resetEffect(node);
// Get wave color from target
var waveColor = getTargetWaveColor(node);
_this.clickWaveTimeoutId = window.setTimeout(function () {
return _this.onClick(node, waveColor);
}, 0);
wrapperRaf.cancel(_this.animationStartId);
_this.animationStart = true;
// Render to trigger transition event cost 3 frames. Let's delay 10 frames to reset this.
_this.animationStartId = wrapperRaf(function () {
_this.animationStart = false;
}, 10);
};
node.addEventListener('click', onClick, true);
return {
cancel: function cancel() {
node.removeEventListener('click', onClick, true);
}
};
};
_this.renderWave = function (_ref) {
var csp = _ref.csp;
var children = _this.props.children;
_this.csp = csp;
if (! /*#__PURE__*/React.isValidElement(children)) return children;
var ref = _this.containerRef;
if (supportRef(children)) {
ref = composeRef(children.ref, _this.containerRef);
}
return cloneElement(children, {
ref: ref
});
};
return _this;
}
_createClass(InternalWave, [{
key: "componentDidMount",
value: function componentDidMount() {
this.destroyed = false;
var node = this.containerRef.current;
if (!node || node.nodeType !== 1) {
return;
}
this.instance = this.bindAnimationEvent(node);
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.instance) {
this.instance.cancel();
}
if (this.clickWaveTimeoutId) {
clearTimeout(this.clickWaveTimeoutId);
}
this.destroyed = true;
}
}, {
key: "getAttributeName",
value: function getAttributeName() {
var getPrefixCls = this.context.getPrefixCls;
var insertExtraNode = this.props.insertExtraNode;
return insertExtraNode ? getPrefixCls('') + "-click-animating" : getPrefixCls('') + "-click-animating-without-extra-node";
}
}, {
key: "resetEffect",
value: function resetEffect(node) {
var _this2 = this;
if (!node || node === this.extraNode || !(node instanceof Element)) {
return;
}
var insertExtraNode = this.props.insertExtraNode;
var attributeName = this.getAttributeName();
node.setAttribute(attributeName, 'false'); // edge has bug on `removeAttribute` #14466
if (styleForPseudo) {
styleForPseudo.innerHTML = '';
}
if (insertExtraNode && this.extraNode && node.contains(this.extraNode)) {
node.removeChild(this.extraNode);
}
['transition', 'animation'].forEach(function (name) {
node.removeEventListener(name + "start", _this2.onTransitionStart);
node.removeEventListener(name + "end", _this2.onTransitionEnd);
});
}
}, {
key: "render",
value: function render() {
return /*#__PURE__*/React.createElement(ConfigConsumer, null, this.renderWave);
}
}]);
return InternalWave;
}(React.Component);
InternalWave.contextType = ConfigContext;
var Wave = /*#__PURE__*/forwardRef(function (props, ref) {
useStyle$2();
return /*#__PURE__*/React.createElement(InternalWave, _extends$1({
ref: ref
}, props));
});
var Wave$1 = Wave;
var __rest$3 = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var GroupSizeContext = /*#__PURE__*/React.createContext(undefined);
var ButtonGroup = function ButtonGroup(props) {
var _classNames;
var _React$useContext = React.useContext(ConfigContext),
getPrefixCls = _React$useContext.getPrefixCls,
direction = _React$useContext.direction;
var customizePrefixCls = props.prefixCls,
size = props.size,
className = props.className,
others = __rest$3(props, ["prefixCls", "size", "className"]);
var prefixCls = getPrefixCls('btn-group', customizePrefixCls);
// Here we only need hashId
var _useToken = useToken(),
_useToken2 = _slicedToArray(_useToken, 3),
hashId = _useToken2[2];
// large => lg
// small => sm
var sizeCls = '';
switch (size) {
case 'large':
sizeCls = 'lg';
break;
case 'small':
sizeCls = 'sm';
break;
case 'middle':
case undefined:
break;
default:
process.env.NODE_ENV !== "production" ? warning$2(!size, 'Button.Group', 'Invalid prop `size`.') : void 0;
}
var classes = classNames(prefixCls, (_classNames = {}, _defineProperty$1(_classNames, prefixCls + "-" + sizeCls, sizeCls), _defineProperty$1(_classNames, prefixCls + "-rtl", direction === 'rtl'), _classNames), className, hashId);
return /*#__PURE__*/React.createElement(GroupSizeContext.Provider, {
value: size
}, /*#__PURE__*/React.createElement("div", _extends$1({}, others, {
className: classes
})));
};
var Group = ButtonGroup;
var getCollapsedWidth = function getCollapsedWidth() {
return {
width: 0,
opacity: 0,
transform: 'scale(0)'
};
};
var getRealWidth = function getRealWidth(node) {
return {
width: node.scrollWidth,
opacity: 1,
transform: 'scale(1)'
};
};
var LoadingIcon = function LoadingIcon(_ref) {
var prefixCls = _ref.prefixCls,
loading = _ref.loading,
existIcon = _ref.existIcon;
var visible = !!loading;
if (existIcon) {
return /*#__PURE__*/React__default.createElement("span", {
className: prefixCls + "-loading-icon"
}, /*#__PURE__*/React__default.createElement(LoadingOutlined$1, null));
}
return /*#__PURE__*/React__default.createElement(CSSMotion, {
visible: visible,
// We do not really use this motionName
motionName: prefixCls + "-loading-icon-motion",
removeOnLeave: true,
onAppearStart: getCollapsedWidth,
onAppearActive: getRealWidth,
onEnterStart: getCollapsedWidth,
onEnterActive: getRealWidth,
onLeaveStart: getRealWidth,
onLeaveActive: getCollapsedWidth
}, function (_ref2, ref) {
var className = _ref2.className,
style = _ref2.style;
return /*#__PURE__*/React__default.createElement("span", {
className: prefixCls + "-loading-icon",
style: style,
ref: ref
}, /*#__PURE__*/React__default.createElement(LoadingOutlined$1, {
className: className
}));
});
};
var LoadingIcon$1 = LoadingIcon;
var genButtonBorderStyle = function genButtonBorderStyle(buttonTypeCls, borderColor) {
return _defineProperty$1({}, "> span, > " + buttonTypeCls, {
'&:not(:last-child)': _defineProperty$1({}, "&, & > " + buttonTypeCls, {
'&:not(:disabled)': {
borderInlineEndColor: borderColor
}
}),
'&:not(:first-child)': _defineProperty$1({}, "&, & > " + buttonTypeCls, {
'&:not(:disabled)': {
borderInlineStartColor: borderColor
}
})
});
};
var genGroupStyle = function genGroupStyle(token) {
var _componentCls, _ref2;
var componentCls = token.componentCls,
fontSize = token.fontSize,
lineWidth = token.lineWidth,
colorPrimaryHover = token.colorPrimaryHover,
colorErrorHover = token.colorErrorHover;
return _defineProperty$1({}, componentCls + "-group", [(_ref2 = {
position: 'relative',
display: 'inline-flex'
}, _defineProperty$1(_ref2, "> span, > " + componentCls, {
'&:not(:last-child)': _defineProperty$1({}, "&, & > " + componentCls, {
borderStartEndRadius: 0,
borderEndEndRadius: 0
}),
'&:not(:first-child)': _defineProperty$1({
marginInlineStart: -lineWidth
}, "&, & > " + componentCls, {
borderStartStartRadius: 0,
borderEndStartRadius: 0
})
}), _defineProperty$1(_ref2, componentCls, (_componentCls = {
position: 'relative',
zIndex: 1
}, _defineProperty$1(_componentCls, "&:hover,\n &:focus,\n &:active", {
zIndex: 2
}), _defineProperty$1(_componentCls, '&[disabled]', {
zIndex: 0
}), _componentCls)), _defineProperty$1(_ref2, componentCls + "-icon-only", {
fontSize: fontSize
}), _ref2),
// Border Color
genButtonBorderStyle(componentCls + "-primary", colorPrimaryHover), genButtonBorderStyle(componentCls + "-danger", colorErrorHover)]);
};
var genGroupStyle$1 = genGroupStyle;
function compactItemVerticalBorder(token) {
return {
// border collapse
'&-item:not(&-last-item)': {
marginBottom: -token.lineWidth
},
'&-item': {
'&:hover,&:focus,&:active': {
zIndex: 2
},
'&[disabled]': {
zIndex: 0
}
}
};
}
function compactItemBorderVerticalRadius(prefixCls) {
return {
'&-item:not(&-first-item):not(&-last-item)': {
borderRadius: 0
},
'&-item&-first-item:not(&-last-item)': _defineProperty$1({}, "&, &" + prefixCls + "-sm, &" + prefixCls + "-lg", {
borderEndEndRadius: 0,
borderEndStartRadius: 0
}),
'&-item&-last-item:not(&-first-item)': _defineProperty$1({}, "&, &" + prefixCls + "-sm, &" + prefixCls + "-lg", {
borderStartStartRadius: 0,
borderStartEndRadius: 0
})
};
}
function genCompactItemVerticalStyle(token, prefixCls) {
return {
'&-compact-vertical': _extends$1(_extends$1({}, compactItemVerticalBorder(token)), compactItemBorderVerticalRadius(prefixCls))
};
}
// ============================== Shared ==============================
var genSharedButtonStyle = function genSharedButtonStyle(token) {
var _extends2, _extends3;
var componentCls = token.componentCls,
iconCls = token.iconCls;
return _defineProperty$1({}, componentCls, _extends$1(_extends$1(_extends$1((_extends2 = {
outline: 'none',
position: 'relative',
display: 'inline-block',
fontWeight: 400,
whiteSpace: 'nowrap',
textAlign: 'center',
backgroundImage: 'none',
backgroundColor: 'transparent',
border: token.lineWidth + "px " + token.lineType + " transparent",
cursor: 'pointer',
transition: "all " + token.motionDurationMid + " " + token.motionEaseInOut,
userSelect: 'none',
touchAction: 'manipulation',
lineHeight: token.lineHeight,
color: token.colorText,
'> span': {
display: 'inline-block'
}
}, _defineProperty$1(_extends2, "> " + iconCls + " + span, > span + " + iconCls, {
marginInlineStart: token.marginXS
}), _defineProperty$1(_extends2, '&:not(:disabled)', _extends$1({}, genFocusStyle(token))), _extends2), genCompactItemStyle(token, componentCls, {
focus: false
})), genCompactItemVerticalStyle(token, componentCls)), (_extends3 = {
// make `btn-icon-only` not too narrow
'&-icon-only&-compact-item': {
flex: 'none'
}
}, _defineProperty$1(_extends3, "&-compact-item" + componentCls + "-primary", {
'&:not([disabled]) + &:not([disabled])': {
position: 'relative',
'&:before': {
position: 'absolute',
top: -token.lineWidth,
insetInlineStart: -token.lineWidth,
display: 'inline-block',
width: token.lineWidth,
height: "calc(100% + " + token.lineWidth * 2 + "px)",
backgroundColor: token.colorPrimaryHover,
content: '""'
}
}
}), _defineProperty$1(_extends3, '&-compact-vertical-item', _defineProperty$1({}, "&" + componentCls + "-primary", {
'&:not([disabled]) + &:not([disabled])': {
position: 'relative',
'&:before': {
position: 'absolute',
top: -token.lineWidth,
insetInlineStart: -token.lineWidth,
display: 'inline-block',
width: "calc(100% + " + token.lineWidth * 2 + "px)",
height: token.lineWidth,
backgroundColor: token.colorPrimaryHover,
content: '""'
}
}
})), _extends3)));
};
var genHoverActiveButtonStyle = function genHoverActiveButtonStyle(hoverStyle, activeStyle) {
return {
'&:not(:disabled)': {
'&:hover': hoverStyle,
'&:active': activeStyle
}
};
};
// ============================== Shape ===============================
var genCircleButtonStyle = function genCircleButtonStyle(token) {
return {
minWidth: token.controlHeight,
paddingInlineStart: 0,
paddingInlineEnd: 0,
borderRadius: '50%'
};
};
var genRoundButtonStyle = function genRoundButtonStyle(token) {
return {
borderRadius: token.controlHeight,
paddingInlineStart: token.controlHeight / 2,
paddingInlineEnd: token.controlHeight / 2,
width: 'auto'
};
};
// =============================== Type ===============================
var genGhostButtonStyle = function genGhostButtonStyle(btnCls, textColor, borderColor, textColorDisabled, borderColorDisabled, hoverStyle, activeStyle) {
return _defineProperty$1({}, "&" + btnCls + "-background-ghost", _extends$1(_extends$1({
color: textColor || undefined,
backgroundColor: 'transparent',
borderColor: borderColor || undefined,
boxShadow: 'none'
}, genHoverActiveButtonStyle(_extends$1({
backgroundColor: 'transparent'
}, hoverStyle), _extends$1({
backgroundColor: 'transparent'
}, activeStyle))), {
'&:disabled': {
cursor: 'not-allowed',
color: textColorDisabled || undefined,
borderColor: borderColorDisabled || undefined
}
}));
};
var genSolidDisabledButtonStyle = function genSolidDisabledButtonStyle(token) {
return {
'&:disabled': {
cursor: 'not-allowed',
borderColor: token.colorBorder,
color: token.colorTextDisabled,
backgroundColor: token.colorBgContainerDisabled,
boxShadow: 'none'
}
};
};
var genSolidButtonStyle = function genSolidButtonStyle(token) {
return _extends$1({}, genSolidDisabledButtonStyle(token));
};
var genPureDisabledButtonStyle = function genPureDisabledButtonStyle(token) {
return {
'&:disabled': {
cursor: 'not-allowed',
color: token.colorTextDisabled
}
};
};
// Type: Default
var genDefaultButtonStyle = function genDefaultButtonStyle(token) {
return _extends$1(_extends$1(_extends$1(_extends$1(_extends$1({}, genSolidButtonStyle(token)), {
backgroundColor: token.colorBgContainer,
borderColor: token.colorBorder,
boxShadow: "0 " + token.controlOutlineWidth + "px 0 " + token.controlTmpOutline
}), genHoverActiveButtonStyle({
color: token.colorPrimaryHover,
borderColor: token.colorPrimaryHover
}, {
color: token.colorPrimaryActive,
borderColor: token.colorPrimaryActive
})), genGhostButtonStyle(token.componentCls, token.colorBgContainer, token.colorBgContainer, token.colorTextDisabled, token.colorBorder)), _defineProperty$1({}, "&" + token.componentCls + "-dangerous", _extends$1(_extends$1(_extends$1({
color: token.colorError,
borderColor: token.colorError
}, genHoverActiveButtonStyle({
color: token.colorErrorHover,
borderColor: token.colorErrorBorderHover
}, {
color: token.colorErrorActive,
borderColor: token.colorErrorActive
})), genGhostButtonStyle(token.componentCls, token.colorError, token.colorError, token.colorTextDisabled, token.colorBorder)), genSolidDisabledButtonStyle(token))));
};
// Type: Primary
var genPrimaryButtonStyle = function genPrimaryButtonStyle(token) {
return _extends$1(_extends$1(_extends$1(_extends$1(_extends$1({}, genSolidButtonStyle(token)), {
color: token.colorTextLightSolid,
backgroundColor: token.colorPrimary,
boxShadow: "0 " + token.controlOutlineWidth + "px 0 " + token.controlOutline
}), genHoverActiveButtonStyle({
color: token.colorTextLightSolid,
backgroundColor: token.colorPrimaryHover
}, {
color: token.colorTextLightSolid,
backgroundColor: token.colorPrimaryActive
})), genGhostButtonStyle(token.componentCls, token.colorPrimary, token.colorPrimary, token.colorTextDisabled, token.colorBorder, {
color: token.colorPrimaryHover,
borderColor: token.colorPrimaryHover
}, {
color: token.colorPrimaryActive,
borderColor: token.colorPrimaryActive
})), _defineProperty$1({}, "&" + token.componentCls + "-dangerous", _extends$1(_extends$1(_extends$1({
backgroundColor: token.colorError,
boxShadow: "0 " + token.controlOutlineWidth + "px 0 " + token.colorErrorOutline
}, genHoverActiveButtonStyle({
backgroundColor: token.colorErrorHover
}, {
backgroundColor: token.colorErrorActive
})), genGhostButtonStyle(token.componentCls, token.colorError, token.colorError, token.colorTextDisabled, token.colorBorder, {
color: token.colorErrorHover,
borderColor: token.colorErrorHover
}, {
color: token.colorErrorActive,
borderColor: token.colorErrorActive
})), genSolidDisabledButtonStyle(token))));
};
// Type: Dashed
var genDashedButtonStyle = function genDashedButtonStyle(token) {
return _extends$1(_extends$1({}, genDefaultButtonStyle(token)), {
borderStyle: 'dashed'
});
};
// Type: Link
var genLinkButtonStyle = function genLinkButtonStyle(token) {
return _extends$1(_extends$1(_extends$1({
color: token.colorLink
}, genHoverActiveButtonStyle({
color: token.colorLinkHover
}, {
color: token.colorLinkActive
})), genPureDisabledButtonStyle(token)), _defineProperty$1({}, "&" + token.componentCls + "-dangerous", _extends$1(_extends$1({
color: token.colorError
}, genHoverActiveButtonStyle({
color: token.colorErrorHover
}, {
color: token.colorErrorActive
})), genPureDisabledButtonStyle(token))));
};
// Type: Text
var genTextButtonStyle = function genTextButtonStyle(token) {
return _extends$1(_extends$1(_extends$1({}, genHoverActiveButtonStyle({
color: token.colorText,
backgroundColor: token.colorBgTextHover
}, {
color: token.colorText,
backgroundColor: token.colorBgTextActive
})), genPureDisabledButtonStyle(token)), _defineProperty$1({}, "&" + token.componentCls + "-dangerous", _extends$1(_extends$1({
color: token.colorError
}, genPureDisabledButtonStyle(token)), genHoverActiveButtonStyle({
color: token.colorErrorHover,
backgroundColor: token.colorErrorBg
}, {
color: token.colorErrorHover,
backgroundColor: token.colorErrorBg
}))));
};
var genTypeButtonStyle = function genTypeButtonStyle(token) {
var _ref3;
var componentCls = token.componentCls;
return _ref3 = {}, _defineProperty$1(_ref3, componentCls + "-default", genDefaultButtonStyle(token)), _defineProperty$1(_ref3, componentCls + "-primary", genPrimaryButtonStyle(token)), _defineProperty$1(_ref3, componentCls + "-dashed", genDashedButtonStyle(token)), _defineProperty$1(_ref3, componentCls + "-link", genLinkButtonStyle(token)), _defineProperty$1(_ref3, componentCls + "-text", genTextButtonStyle(token)), _ref3;
};
// =============================== Size ===============================
var genSizeButtonStyle = function genSizeButtonStyle(token) {
var _ref4;
var sizePrefixCls = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var componentCls = token.componentCls,
iconCls = token.iconCls;
var paddingVertical = Math.max(0, (token.controlHeight - token.fontSize * token.lineHeight) / 2 - token.lineWidth);
var paddingHorizontal = token.buttonPaddingHorizontal - token.lineWidth;
var iconOnlyCls = componentCls + "-icon-only";
return [
// Size
_defineProperty$1({}, "" + componentCls + sizePrefixCls, (_ref4 = {
fontSize: token.fontSize,
height: token.controlHeight,
padding: paddingVertical + "px " + paddingHorizontal + "px",
borderRadius: token.borderRadius
}, _defineProperty$1(_ref4, "&" + iconOnlyCls, {
width: token.controlHeight,
paddingInlineStart: 0,
paddingInlineEnd: 0,
'> span': {
transform: 'scale(1.143)' // 14px -> 16px
}
}), _defineProperty$1(_ref4, "&" + componentCls + "-loading", {
opacity: token.opacityLoading,
cursor: 'default'
}), _defineProperty$1(_ref4, componentCls + "-loading-icon", {
transition: "width " + token.motionDurationSlow + " " + token.motionEaseInOut + ", opacity " + token.motionDurationSlow + " " + token.motionEaseInOut
}), _defineProperty$1(_ref4, "&:not(" + iconOnlyCls + ") " + componentCls + "-loading-icon > " + iconCls, {
marginInlineEnd: token.marginXS
}), _ref4)),
// Shape - patch prefixCls again to override solid border radius style
_defineProperty$1({}, "" + componentCls + componentCls + "-circle" + sizePrefixCls, genCircleButtonStyle(token)), _defineProperty$1({}, "" + componentCls + componentCls + "-round" + sizePrefixCls, genRoundButtonStyle(token))];
};
var genSizeBaseButtonStyle = function genSizeBaseButtonStyle(token) {
return genSizeButtonStyle(token);
};
var genSizeSmallButtonStyle = function genSizeSmallButtonStyle(token) {
var smallToken = merge(token, {
controlHeight: token.controlHeightSM,
padding: token.paddingXS,
buttonPaddingHorizontal: 8,
borderRadius: token.borderRadiusSM
});
return genSizeButtonStyle(smallToken, token.componentCls + "-sm");
};
var genSizeLargeButtonStyle = function genSizeLargeButtonStyle(token) {
var largeToken = merge(token, {
controlHeight: token.controlHeightLG,
fontSize: token.fontSizeLG,
borderRadius: token.borderRadiusLG
});
return genSizeButtonStyle(largeToken, token.componentCls + "-lg");
};
var genBlockButtonStyle = function genBlockButtonStyle(token) {
var componentCls = token.componentCls;
return _defineProperty$1({}, componentCls, _defineProperty$1({}, "&" + componentCls + "-block", {
width: '100%'
}));
};
// ============================== Export ==============================
var useStyle$1 = genComponentStyleHook('Button', function (token) {
var controlTmpOutline = token.controlTmpOutline,
paddingContentHorizontal = token.paddingContentHorizontal;
var buttonToken = merge(token, {
colorOutlineDefault: controlTmpOutline,
buttonPaddingHorizontal: paddingContentHorizontal
});
return [
// Shared
genSharedButtonStyle(buttonToken),
// Size
genSizeSmallButtonStyle(buttonToken), genSizeBaseButtonStyle(buttonToken), genSizeLargeButtonStyle(buttonToken),
// Block
genBlockButtonStyle(buttonToken),
// Group (type, ghost, danger, disabled, loading)
genTypeButtonStyle(buttonToken),
// Button Group
genGroupStyle$1(buttonToken)];
});
var __rest$2 = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var rxTwoCNChar = /^[\u4e00-\u9fa5]{2}$/;
var isTwoCNChar = rxTwoCNChar.test.bind(rxTwoCNChar);
function isString(str) {
return typeof str === 'string';
}
function isUnBorderedButtonType(type) {
return type === 'text' || type === 'link';
}
// Insert one space between two chinese characters automatically.
function insertSpace(child, needInserted) {
// Check the child if is undefined or null.
if (child === null || child === undefined) {
return;
}
var SPACE = needInserted ? ' ' : '';
// strictNullChecks oops.
if (typeof child !== 'string' && typeof child !== 'number' && isString(child.type) && isTwoCNChar(child.props.children)) {
return cloneElement(child, {
children: child.props.children.split('').join(SPACE)
});
}
if (typeof child === 'string') {
return isTwoCNChar(child) ? /*#__PURE__*/React.createElement("span", null, child.split('').join(SPACE)) : /*#__PURE__*/React.createElement("span", null, child);
}
if (isFragment(child)) {
return /*#__PURE__*/React.createElement("span", null, child);
}
return child;
}
function spaceChildren(children, needInserted) {
var isPrevChildPure = false;
var childList = [];
React.Children.forEach(children, function (child) {
var type = _typeof$1(child);
var isCurrentChildPure = type === 'string' || type === 'number';
if (isPrevChildPure && isCurrentChildPure) {
var lastIndex = childList.length - 1;
var lastChild = childList[lastIndex];
childList[lastIndex] = "" + lastChild + child;
} else {
childList.push(child);
}
isPrevChildPure = isCurrentChildPure;
});
// Pass to React.Children.map to auto fill key
return React.Children.map(childList, function (child) {
return insertSpace(child, needInserted);
});
}
tuple('default', 'primary', 'ghost', 'dashed', 'link', 'text');
tuple('default', 'circle', 'round');
tuple('submit', 'button', 'reset');
var InternalButton = function InternalButton(props, ref) {
var _classNames;
var _props$loading = props.loading,
loading = _props$loading === void 0 ? false : _props$loading,
customizePrefixCls = props.prefixCls,
_props$type = props.type,
type = _props$type === void 0 ? 'default' : _props$type,
danger = props.danger,
_props$shape = props.shape,
shape = _props$shape === void 0 ? 'default' : _props$shape,
customizeSize = props.size,
customDisabled = props.disabled,
className = props.className,
children = props.children,
icon = props.icon,
_props$ghost = props.ghost,
ghost = _props$ghost === void 0 ? false : _props$ghost,
_props$block = props.block,
block = _props$block === void 0 ? false : _props$block,
_props$htmlType = props.htmlType,
htmlType = _props$htmlType === void 0 ? 'button' : _props$htmlType,
rest = __rest$2(props, ["loading", "prefixCls", "type", "danger", "shape", "size", "disabled", "className", "children", "icon", "ghost", "block", "htmlType"]);
var _React$useContext = React.useContext(ConfigContext),
getPrefixCls = _React$useContext.getPrefixCls,
autoInsertSpaceInButton = _React$useContext.autoInsertSpaceInButton,
direction = _React$useContext.direction;
var prefixCls = getPrefixCls('btn', customizePrefixCls);
// Style
var _useStyle = useStyle$1(prefixCls),
_useStyle2 = _slicedToArray(_useStyle, 2),
wrapSSR = _useStyle2[0],
hashId = _useStyle2[1];
var size = React.useContext(SizeContext$1);
// ===================== Disabled =====================
var disabled = React.useContext(DisabledContext$1);
var mergedDisabled = customDisabled !== null && customDisabled !== void 0 ? customDisabled : disabled;
var groupSize = React.useContext(GroupSizeContext);
var _React$useState = React.useState(!!loading),
_React$useState2 = _slicedToArray(_React$useState, 2),
innerLoading = _React$useState2[0],
setLoading = _React$useState2[1];
var _React$useState3 = React.useState(false),
_React$useState4 = _slicedToArray(_React$useState3, 2),
hasTwoCNChar = _React$useState4[0],
setHasTwoCNChar = _React$useState4[1];
var buttonRef = ref || /*#__PURE__*/React.createRef();
var isNeedInserted = function isNeedInserted() {
return React.Children.count(children) === 1 && !icon && !isUnBorderedButtonType(type);
};
var fixTwoCNChar = function fixTwoCNChar() {
// Fix for HOC usage like <FormatMessage />
if (!buttonRef || !buttonRef.current || autoInsertSpaceInButton === false) {
return;
}
var buttonText = buttonRef.current.textContent;
if (isNeedInserted() && isTwoCNChar(buttonText)) {
if (!hasTwoCNChar) {
setHasTwoCNChar(true);
}
} else if (hasTwoCNChar) {
setHasTwoCNChar(false);
}
};
// =============== Update Loading ===============
var loadingOrDelay = typeof loading === 'boolean' ? loading : (loading === null || loading === void 0 ? void 0 : loading.delay) || true;
React.useEffect(function () {
var delayTimer = null;
if (typeof loadingOrDelay === 'number') {
delayTimer = window.setTimeout(function () {
delayTimer = null;
setLoading(loadingOrDelay);
}, loadingOrDelay);
} else {
setLoading(loadingOrDelay);
}
return function () {
if (delayTimer) {
// in order to not perform a React state update on an unmounted component
// and clear timer after 'loadingOrDelay' updated.
window.clearTimeout(delayTimer);
delayTimer = null;
}
};
}, [loadingOrDelay]);
React.useEffect(fixTwoCNChar, [buttonRef]);
var handleClick = function handleClick(e) {
var onClick = props.onClick;
// https://github.com/ant-design/ant-design/issues/30207
if (innerLoading || mergedDisabled) {
e.preventDefault();
return;
}
onClick === null || onClick === void 0 ? void 0 : onClick(e);
};
process.env.NODE_ENV !== "production" ? warning$2(!(typeof icon === 'string' && icon.length > 2), 'Button', "`icon` is using ReactNode instead of string naming in v4. Please check `" + icon + "` at https://ant.design/components/icon") : void 0;
process.env.NODE_ENV !== "production" ? warning$2(!(ghost && isUnBorderedButtonType(type)), 'Button', "`link` or `text` button can't be a `ghost` button.") : void 0;
var autoInsertSpace = autoInsertSpaceInButton !== false;
var _useCompactItemContex = useCompactItemContext(prefixCls, direction),
compactSize = _useCompactItemContex.compactSize,
compactItemClassnames = _useCompactItemContex.compactItemClassnames;
var sizeClassNameMap = {
large: 'lg',
small: 'sm',
middle: undefined
};
var sizeFullname = compactSize || groupSize || customizeSize || size;
var sizeCls = sizeFullname ? sizeClassNameMap[sizeFullname] || '' : '';
var iconType = innerLoading ? 'loading' : icon;
var linkButtonRestProps = omit(rest, ['navigate']);
var classes = classNames(prefixCls, hashId, (_classNames = {}, _defineProperty$1(_classNames, prefixCls + "-" + shape, shape !== 'default' && shape), _defineProperty$1(_classNames, prefixCls + "-" + type, type), _defineProperty$1(_classNames, prefixCls + "-" + sizeCls, sizeCls), _defineProperty$1(_classNames, prefixCls + "-icon-only", !children && children !== 0 && !!iconType), _defineProperty$1(_classNames, prefixCls + "-background-ghost", ghost && !isUnBorderedButtonType(type)), _defineProperty$1(_classNames, prefixCls + "-loading", innerLoading), _defineProperty$1(_classNames, prefixCls + "-two-chinese-chars", hasTwoCNChar && autoInsertSpace && !innerLoading), _defineProperty$1(_classNames, prefixCls + "-block", block), _defineProperty$1(_classNames, prefixCls + "-dangerous", !!danger), _defineProperty$1(_classNames, prefixCls + "-rtl", direction === 'rtl'), _defineProperty$1(_classNames, prefixCls + "-disabled", linkButtonRestProps.href !== undefined && mergedDisabled), _classNames), compactItemClassnames, className);
var iconNode = icon && !innerLoading ? icon : /*#__PURE__*/React.createElement(LoadingIcon$1, {
existIcon: !!icon,
prefixCls: prefixCls,
loading: !!innerLoading
});
var kids = children || children === 0 ? spaceChildren(children, isNeedInserted() && autoInsertSpace) : null;
if (linkButtonRestProps.href !== undefined) {
return wrapSSR( /*#__PURE__*/React.createElement("a", _extends$1({}, linkButtonRestProps, {
className: classes,
onClick: handleClick,
ref: buttonRef
}), iconNode, kids));
}
var buttonNode = /*#__PURE__*/React.createElement("button", _extends$1({}, rest, {
type: htmlType,
className: classes,
onClick: handleClick,
disabled: mergedDisabled,
ref: buttonRef
}), iconNode, kids);
if (!isUnBorderedButtonType(type)) {
buttonNode = /*#__PURE__*/React.createElement(Wave$1, {
disabled: !!innerLoading
}, buttonNode);
}
return wrapSSR(buttonNode);
};
var Button = /*#__PURE__*/React.forwardRef(InternalButton);
if (process.env.NODE_ENV !== 'production') {
Button.displayName = 'Button';
}
Button.Group = Group;
Button.__ANT_BUTTON = true;
var Button$1 = Button;
var canUseDocElement = function canUseDocElement() {
return canUseDom() && window.document.documentElement;
};
var flexGapSupported;
var detectFlexGapSupported = function detectFlexGapSupported() {
if (!canUseDocElement()) {
return false;
}
if (flexGapSupported !== undefined) {
return flexGapSupported;
}
// create flex container with row-gap set
var flex = document.createElement('div');
flex.style.display = 'flex';
flex.style.flexDirection = 'column';
flex.style.rowGap = '1px';
// create two, elements inside it
flex.appendChild(document.createElement('div'));
flex.appendChild(document.createElement('div'));
// append to the DOM (needed to obtain scrollHeight)
document.body.appendChild(flex);
flexGapSupported = flex.scrollHeight === 1; // flex container should be 1px high from the row-gap
document.body.removeChild(flex);
return flexGapSupported;
};
var useFlexGapSupport = (function () {
var _React$useState = React.useState(false),
_React$useState2 = _slicedToArray(_React$useState, 2),
flexible = _React$useState2[0],
setFlexible = _React$useState2[1];
React.useEffect(function () {
setFlexible(detectFlexGapSupported());
}, []);
return flexible;
});
function Item(_ref) {
var className = _ref.className,
direction = _ref.direction,
index = _ref.index,
marginDirection = _ref.marginDirection,
children = _ref.children,
split = _ref.split,
wrap = _ref.wrap;
var _React$useContext = React.useContext(SpaceContext),
horizontalSize = _React$useContext.horizontalSize,
verticalSize = _React$useContext.verticalSize,
latestIndex = _React$useContext.latestIndex,
supportFlexGap = _React$useContext.supportFlexGap;
var style = {};
if (!supportFlexGap) {
if (direction === 'vertical') {
if (index < latestIndex) {
style = {
marginBottom: horizontalSize / (split ? 2 : 1)
};
}
} else {
style = _extends$1(_extends$1({}, index < latestIndex && _defineProperty$1({}, marginDirection, horizontalSize / (split ? 2 : 1))), wrap && {
paddingBottom: verticalSize
});
}
}
if (children === null || children === undefined) {
return null;
}
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
className: className,
style: style
}, children), index < latestIndex && split && /*#__PURE__*/React.createElement("span", {
className: className + "-split",
style: style
}, split));
}
var __rest$1 = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var SpaceContext = /*#__PURE__*/React.createContext({
latestIndex: 0,
horizontalSize: 0,
verticalSize: 0,
supportFlexGap: false
});
var spaceSize = {
small: 8,
middle: 16,
large: 24
};
function getNumberSize(size) {
return typeof size === 'string' ? spaceSize[size] : size || 0;
}
var Space = function Space(props) {
var _classNames;
var _React$useContext = React.useContext(ConfigContext),
getPrefixCls = _React$useContext.getPrefixCls,
space = _React$useContext.space,
directionConfig = _React$useContext.direction;
var _props$size = props.size,
size = _props$size === void 0 ? (space === null || space === void 0 ? void 0 : space.size) || 'small' : _props$size,
align = props.align,
className = props.className,
children = props.children,
_props$direction = props.direction,
direction = _props$direction === void 0 ? 'horizontal' : _props$direction,
customizePrefixCls = props.prefixCls,
split = props.split,
style = props.style,
_props$wrap = props.wrap,
wrap = _props$wrap === void 0 ? false : _props$wrap,
otherProps = __rest$1(props, ["size", "align", "className", "children", "direction", "prefixCls", "split", "style", "wrap"]);
var supportFlexGap = useFlexGapSupport();
var _React$useMemo = React.useMemo(function () {
return (Array.isArray(size) ? size : [size, size]).map(function (item) {
return getNumberSize(item);
});
}, [size]),
_React$useMemo2 = _slicedToArray(_React$useMemo, 2),
horizontalSize = _React$useMemo2[0],
verticalSize = _React$useMemo2[1];
var childNodes = toArray$1(children, {
keepEmpty: true
});
var mergedAlign = align === undefined && direction === 'horizontal' ? 'center' : align;
var prefixCls = getPrefixCls('space', customizePrefixCls);
var _useStyle = useStyle$7(prefixCls),
_useStyle2 = _slicedToArray(_useStyle, 2),
wrapSSR = _useStyle2[0],
hashId = _useStyle2[1];
var cn = classNames(prefixCls, hashId, prefixCls + "-" + direction, (_classNames = {}, _defineProperty$1(_classNames, prefixCls + "-rtl", directionConfig === 'rtl'), _defineProperty$1(_classNames, prefixCls + "-align-" + mergedAlign, mergedAlign), _classNames), className);
var itemClassName = prefixCls + "-item";
var marginDirection = directionConfig === 'rtl' ? 'marginLeft' : 'marginRight';
// Calculate latest one
var latestIndex = 0;
var nodes = childNodes.map(function (child, i) {
if (child !== null && child !== undefined) {
latestIndex = i;
}
var key = child && child.key || itemClassName + "-" + i;
return /*#__PURE__*/React.createElement(Item, {
className: itemClassName,
key: key,
direction: direction,
index: i,
marginDirection: marginDirection,
split: split,
wrap: wrap
}, child);
});
var spaceContext = React.useMemo(function () {
return {
horizontalSize: horizontalSize,
verticalSize: verticalSize,
latestIndex: latestIndex,
supportFlexGap: supportFlexGap
};
}, [horizontalSize, verticalSize, latestIndex, supportFlexGap]);
// =========================== Render ===========================
if (childNodes.length === 0) {
return null;
}
var gapStyle = {};
if (wrap) {
gapStyle.flexWrap = 'wrap';
// Patch for gap not support
if (!supportFlexGap) {
gapStyle.marginBottom = -verticalSize;
}
}
if (supportFlexGap) {
gapStyle.columnGap = horizontalSize;
gapStyle.rowGap = verticalSize;
}
return wrapSSR( /*#__PURE__*/React.createElement("div", _extends$1({
className: cn,
style: _extends$1(_extends$1({}, gapStyle), style)
}, otherProps), /*#__PURE__*/React.createElement(SpaceContext.Provider, {
value: spaceContext
}, nodes)));
};
var CompoundedSpace = Space;
CompoundedSpace.Compact = Compact$1;
var Space$1 = CompoundedSpace;
var genButtonStyle = function genButtonStyle(token) {
var _ref;
var componentCls = token.componentCls,
antCls = token.antCls,
paddingXS = token.paddingXS,
opacityLoading = token.opacityLoading;
return _defineProperty$1({}, componentCls + "-button", _defineProperty$1({
whiteSpace: 'nowrap'
}, "&" + antCls + "-btn-group > " + antCls + "-btn", (_ref = {}, _defineProperty$1(_ref, "&-loading, &-loading + " + antCls + "-btn", {
cursor: 'default',
pointerEvents: 'none',
opacity: opacityLoading
}), _defineProperty$1(_ref, "&:last-child:not(:first-child):not(" + antCls + "-btn-icon-only)", {
paddingInline: paddingXS
}), _ref)));
};
var genButtonStyle$1 = genButtonStyle;
var genStatusStyle = function genStatusStyle(token) {
var componentCls = token.componentCls,
menuCls = token.menuCls,
colorError = token.colorError,
colorTextLightSolid = token.colorTextLightSolid;
var itemCls = menuCls + "-item";
return _defineProperty$1({}, componentCls + ", " + componentCls + "-menu-submenu", _defineProperty$1({}, menuCls + " " + itemCls, _defineProperty$1({}, "&" + itemCls + "-danger", {
color: colorError,
'&:hover': {
color: colorTextLightSolid,
backgroundColor: colorError
}
})));
};
var genStatusStyle$1 = genStatusStyle;
// =============================== Base ===============================
var genBaseStyle = function genBaseStyle(token) {
var _ref, _extends2, _extends5, _ref7;
var componentCls = token.componentCls,
menuCls = token.menuCls,
zIndexPopup = token.zIndexPopup,
dropdownArrowDistance = token.dropdownArrowDistance,
dropdownArrowOffset = token.dropdownArrowOffset,
sizePopupArrow = token.sizePopupArrow,
antCls = token.antCls,
iconCls = token.iconCls,
motionDurationMid = token.motionDurationMid,
dropdownPaddingVertical = token.dropdownPaddingVertical,
fontSize = token.fontSize,
dropdownEdgeChildPadding = token.dropdownEdgeChildPadding,
borderRadius = token.borderRadius,
colorTextDisabled = token.colorTextDisabled,
fontSizeIcon = token.fontSizeIcon,
controlPaddingHorizontal = token.controlPaddingHorizontal,
colorBgElevated = token.colorBgElevated,
boxShadowPopoverArrow = token.boxShadowPopoverArrow;
return [_defineProperty$1({}, componentCls, _extends$1(_extends$1({}, resetComponent(token)), (_extends2 = {
position: 'absolute',
top: -9999,
left: {
_skip_check_: true,
value: -9999
},
zIndex: zIndexPopup,
display: 'block',
// A placeholder out of dropdown visible range to avoid close when user moving
'&::before': {
position: 'absolute',
insetBlock: -dropdownArrowDistance + sizePopupArrow / 2,
// insetInlineStart: -7, // FIXME: Seems not work for hidden element
zIndex: -9999,
opacity: 0.0001,
content: '""'
}
}, _defineProperty$1(_extends2, componentCls + "-wrap", (_ref = {
position: 'relative'
}, _defineProperty$1(_ref, antCls + "-btn > " + iconCls + "-down", {
fontSize: fontSizeIcon
}), _defineProperty$1(_ref, iconCls + "-down::before", {
transition: "transform " + motionDurationMid
}), _ref)), _defineProperty$1(_extends2, componentCls + "-wrap-open", _defineProperty$1({}, iconCls + "-down::before", {
transform: "rotate(180deg)"
})), _defineProperty$1(_extends2, "\n &-hidden,\n &-menu-hidden,\n &-menu-submenu-hidden\n ", {
display: 'none'
}), _defineProperty$1(_extends2, "\n &-show-arrow&-placement-topLeft,\n &-show-arrow&-placement-top,\n &-show-arrow&-placement-topRight\n ", {
paddingBottom: dropdownArrowDistance
}), _defineProperty$1(_extends2, "\n &-show-arrow&-placement-bottomLeft,\n &-show-arrow&-placement-bottom,\n &-show-arrow&-placement-bottomRight\n ", {
paddingTop: dropdownArrowDistance
}), _defineProperty$1(_extends2, componentCls + "-arrow", _extends$1({
position: 'absolute',
zIndex: 1,
display: 'block'
}, roundedArrow(sizePopupArrow, token.borderRadiusXS, token.borderRadiusOuter, colorBgElevated, boxShadowPopoverArrow))), _defineProperty$1(_extends2, "\n &-placement-top > " + componentCls + "-arrow,\n &-placement-topLeft > " + componentCls + "-arrow,\n &-placement-topRight > " + componentCls + "-arrow\n ", {
bottom: dropdownArrowDistance,
transform: 'translateY(100%) rotate(180deg)'
}), _defineProperty$1(_extends2, "&-placement-top > " + componentCls + "-arrow", {
left: {
_skip_check_: true,
value: '50%'
},
transform: 'translateX(-50%) translateY(100%) rotate(180deg)'
}), _defineProperty$1(_extends2, "&-placement-topLeft > " + componentCls + "-arrow", {
left: {
_skip_check_: true,
value: dropdownArrowOffset
}
}), _defineProperty$1(_extends2, "&-placement-topRight > " + componentCls + "-arrow", {
right: {
_skip_check_: true,
value: dropdownArrowOffset
}
}), _defineProperty$1(_extends2, "\n &-placement-bottom > " + componentCls + "-arrow,\n &-placement-bottomLeft > " + componentCls + "-arrow,\n &-placement-bottomRight > " + componentCls + "-arrow\n ", {
top: dropdownArrowDistance,
transform: "translateY(-100%)"
}), _defineProperty$1(_extends2, "&-placement-bottom > " + componentCls + "-arrow", {
left: {
_skip_check_: true,
value: '50%'
},
transform: "translateY(-100%) translateX(-50%)"
}), _defineProperty$1(_extends2, "&-placement-bottomLeft > " + componentCls + "-arrow", {
left: {
_skip_check_: true,
value: dropdownArrowOffset
}
}), _defineProperty$1(_extends2, "&-placement-bottomRight > " + componentCls + "-arrow", {
right: {
_skip_check_: true,
value: dropdownArrowOffset
}
}), _defineProperty$1(_extends2, "&" + antCls + "-slide-down-enter" + antCls + "-slide-down-enter-active&-placement-bottomLeft,\n &" + antCls + "-slide-down-appear" + antCls + "-slide-down-appear-active&-placement-bottomLeft\n &" + antCls + "-slide-down-enter" + antCls + "-slide-down-enter-active&-placement-bottom,\n &" + antCls + "-slide-down-appear" + antCls + "-slide-down-appear-active&-placement-bottom,\n &" + antCls + "-slide-down-enter" + antCls + "-slide-down-enter-active&-placement-bottomRight,\n &" + antCls + "-slide-down-appear" + antCls + "-slide-down-appear-active&-placement-bottomRight", {
animationName: slideUpIn
}), _defineProperty$1(_extends2, "&" + antCls + "-slide-up-enter" + antCls + "-slide-up-enter-active&-placement-topLeft,\n &" + antCls + "-slide-up-appear" + antCls + "-slide-up-appear-active&-placement-topLeft,\n &" + antCls + "-slide-up-enter" + antCls + "-slide-up-enter-active&-placement-top,\n &" + antCls + "-slide-up-appear" + antCls + "-slide-up-appear-active&-placement-top,\n &" + antCls + "-slide-up-enter" + antCls + "-slide-up-enter-active&-placement-topRight,\n &" + antCls + "-slide-up-appear" + antCls + "-slide-up-appear-active&-placement-topRight", {
animationName: slideDownIn
}), _defineProperty$1(_extends2, "&" + antCls + "-slide-down-leave" + antCls + "-slide-down-leave-active&-placement-bottomLeft,\n &" + antCls + "-slide-down-leave" + antCls + "-slide-down-leave-active&-placement-bottom,\n &" + antCls + "-slide-down-leave" + antCls + "-slide-down-leave-active&-placement-bottomRight", {
animationName: slideUpOut
}), _defineProperty$1(_extends2, "&" + antCls + "-slide-up-leave" + antCls + "-slide-up-leave-active&-placement-topLeft,\n &" + antCls + "-slide-up-leave" + antCls + "-slide-up-leave-active&-placement-top,\n &" + antCls + "-slide-up-leave" + antCls + "-slide-up-leave-active&-placement-topRight", {
animationName: slideDownOut
}), _extends2))), (_ref7 = {}, _defineProperty$1(_ref7, componentCls + " " + menuCls, {
position: 'relative',
margin: 0
}), _defineProperty$1(_ref7, menuCls + "-submenu-popup", {
position: 'absolute',
zIndex: zIndexPopup,
background: 'transparent',
boxShadow: 'none',
transformOrigin: '0 0',
'ul,li': {
listStyle: 'none'
},
ul: {
marginInline: '0.3em'
}
}), _defineProperty$1(_ref7, componentCls + ", " + componentCls + "-menu-submenu", _defineProperty$1({}, menuCls, _extends$1(_extends$1({
padding: dropdownEdgeChildPadding,
listStyleType: 'none',
backgroundColor: colorBgElevated,
backgroundClip: 'padding-box',
borderRadius: token.borderRadiusLG,
outline: 'none',
boxShadow: token.boxShadowSecondary
}, genFocusStyle(token)), (_extends5 = {}, _defineProperty$1(_extends5, menuCls + "-item-group-title", {
padding: dropdownPaddingVertical + "px " + controlPaddingHorizontal + "px",
color: token.colorTextDescription,
transition: "all " + motionDurationMid
}), _defineProperty$1(_extends5, menuCls + "-item", {
position: 'relative',
display: 'flex',
alignItems: 'center',
borderRadius: token.borderRadiusSM
}), _defineProperty$1(_extends5, menuCls + "-item-icon", {
minWidth: fontSize,
marginInlineEnd: token.marginXS,
fontSize: token.fontSizeSM
}), _defineProperty$1(_extends5, menuCls + "-title-content", {
flex: 'auto',
'> a': {
color: 'inherit',
transition: "all " + motionDurationMid,
'&:hover': {
color: 'inherit'
},
'&::after': {
position: 'absolute',
inset: 0,
content: '""'
}
}
}), _defineProperty$1(_extends5, menuCls + "-item, " + menuCls + "-submenu-title", _extends$1(_extends$1(_defineProperty$1({
clear: 'both',
margin: 0,
padding: dropdownPaddingVertical + "px " + controlPaddingHorizontal + "px",
color: token.colorText,
fontWeight: 'normal',
fontSize: fontSize,
lineHeight: token.lineHeight,
cursor: 'pointer',
transition: "all " + motionDurationMid,
'&:first-child': !dropdownEdgeChildPadding ? {
borderRadius: borderRadius + "px " + borderRadius + "px 0 0"
} : [],
'&:last-child': !dropdownEdgeChildPadding ? {
borderRadius: "0 0 " + borderRadius + "px " + borderRadius + "px"
} : []
}, "&:hover, &-active", {
backgroundColor: token.controlItemBgHover
}), genFocusStyle(token)), _defineProperty$1({
'&-selected': {
color: token.colorPrimary,
backgroundColor: token.controlItemBgActive,
'&:hover, &-active': {
backgroundColor: token.controlItemBgActiveHover
}
},
'&-disabled': {
color: colorTextDisabled,
cursor: 'not-allowed',
'&:hover': {
color: colorTextDisabled,
backgroundColor: colorBgElevated,
cursor: 'not-allowed'
},
a: {
pointerEvents: 'none'
}
},
'&-divider': {
height: 1,
margin: token.marginXXS + "px 0",
overflow: 'hidden',
lineHeight: 0,
backgroundColor: token.colorSplit
}
}, componentCls + "-menu-submenu-expand-icon", _defineProperty$1({
position: 'absolute',
insetInlineEnd: token.paddingXS
}, componentCls + "-menu-submenu-arrow-icon", {
marginInlineEnd: '0 !important',
color: token.colorTextDescription,
fontSize: fontSizeIcon,
fontStyle: 'normal'
})))), _defineProperty$1(_extends5, menuCls + "-item-group-list", {
margin: "0 " + token.marginXS + "px",
padding: 0,
listStyle: 'none'
}), _defineProperty$1(_extends5, menuCls + "-submenu-title", {
paddingInlineEnd: controlPaddingHorizontal + token.fontSizeSM
}), _defineProperty$1(_extends5, menuCls + "-submenu-vertical", {
position: 'relative'
}), _defineProperty$1(_extends5, menuCls + "-submenu" + menuCls + "-submenu-disabled " + componentCls + "-menu-submenu-title", _defineProperty$1({}, "&, " + componentCls + "-menu-submenu-arrow-icon", {
color: colorTextDisabled,
backgroundColor: colorBgElevated,
cursor: 'not-allowed'
})), _defineProperty$1(_extends5, menuCls + "-submenu-selected " + componentCls + "-menu-submenu-title", {
color: token.colorPrimary
}), _extends5)))), _ref7),
// Follow code may reuse in other components
[initSlideMotion(token, 'slide-up'), initSlideMotion(token, 'slide-down'), initMoveMotion(token, 'move-up'), initMoveMotion(token, 'move-down'), initZoomMotion(token, 'zoom-big')]];
};
// ============================== Export ==============================
var useStyle = genComponentStyleHook('Dropdown', function (token, _ref8) {
var rootPrefixCls = _ref8.rootPrefixCls;
var marginXXS = token.marginXXS,
sizePopupArrow = token.sizePopupArrow,
controlHeight = token.controlHeight,
fontSize = token.fontSize,
lineHeight = token.lineHeight,
paddingXXS = token.paddingXXS,
componentCls = token.componentCls,
borderRadiusOuter = token.borderRadiusOuter,
borderRadiusLG = token.borderRadiusLG;
var dropdownPaddingVertical = (controlHeight - fontSize * lineHeight) / 2;
var _getArrowOffset = getArrowOffset({
sizePopupArrow: sizePopupArrow,
contentRadius: borderRadiusLG,
borderRadiusOuter: borderRadiusOuter
}),
dropdownArrowOffset = _getArrowOffset.dropdownArrowOffset;
var dropdownToken = merge(token, {
menuCls: componentCls + "-menu",
rootPrefixCls: rootPrefixCls,
dropdownArrowDistance: sizePopupArrow / 2 + marginXXS,
dropdownArrowOffset: dropdownArrowOffset,
dropdownPaddingVertical: dropdownPaddingVertical,
dropdownEdgeChildPadding: paddingXXS
});
return [genBaseStyle(dropdownToken), genButtonStyle$1(dropdownToken), genStatusStyle$1(dropdownToken)];
}, function (token) {
return {
zIndexPopup: token.zIndexPopupBase + 50
};
});
var __rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var DropdownButton = function DropdownButton(props) {
var _React$useContext = React.useContext(ConfigContext),
getContextPopupContainer = _React$useContext.getPopupContainer,
getPrefixCls = _React$useContext.getPrefixCls,
direction = _React$useContext.direction;
var customizePrefixCls = props.prefixCls,
_props$type = props.type,
type = _props$type === void 0 ? 'default' : _props$type,
danger = props.danger,
disabled = props.disabled,
loading = props.loading,
onClick = props.onClick,
htmlType = props.htmlType,
children = props.children,
className = props.className,
menu = props.menu,
arrow = props.arrow,
autoFocus = props.autoFocus,
overlay = props.overlay,
trigger = props.trigger,
align = props.align,
open = props.open,
onOpenChange = props.onOpenChange,
placement = props.placement,
getPopupContainer = props.getPopupContainer,
href = props.href,
_props$icon = props.icon,
icon = _props$icon === void 0 ? /*#__PURE__*/React.createElement(EllipsisOutlined$1, null) : _props$icon,
title = props.title,
_props$buttonsRender = props.buttonsRender,
buttonsRender = _props$buttonsRender === void 0 ? function (buttons) {
return buttons;
} : _props$buttonsRender,
mouseEnterDelay = props.mouseEnterDelay,
mouseLeaveDelay = props.mouseLeaveDelay,
overlayClassName = props.overlayClassName,
overlayStyle = props.overlayStyle,
destroyPopupOnHide = props.destroyPopupOnHide,
dropdownRender = props.dropdownRender,
restProps = __rest(props, ["prefixCls", "type", "danger", "disabled", "loading", "onClick", "htmlType", "children", "className", "menu", "arrow", "autoFocus", "overlay", "trigger", "align", "open", "onOpenChange", "placement", "getPopupContainer", "href", "icon", "title", "buttonsRender", "mouseEnterDelay", "mouseLeaveDelay", "overlayClassName", "overlayStyle", "destroyPopupOnHide", "dropdownRender"]);
var prefixCls = getPrefixCls('dropdown', customizePrefixCls);
var buttonPrefixCls = prefixCls + "-button";
var _useStyle = useStyle(prefixCls),
_useStyle2 = _slicedToArray(_useStyle, 2),
wrapSSR = _useStyle2[0],
hashId = _useStyle2[1];
var dropdownProps = {
menu: menu,
arrow: arrow,
autoFocus: autoFocus,
align: align,
disabled: disabled,
trigger: disabled ? [] : trigger,
onOpenChange: onOpenChange,
getPopupContainer: getPopupContainer || getContextPopupContainer,
mouseEnterDelay: mouseEnterDelay,
mouseLeaveDelay: mouseLeaveDelay,
overlayClassName: overlayClassName,
overlayStyle: overlayStyle,
destroyPopupOnHide: destroyPopupOnHide,
dropdownRender: dropdownRender
};
var _useCompactItemContex = useCompactItemContext(prefixCls, direction),
compactSize = _useCompactItemContex.compactSize,
compactItemClassnames = _useCompactItemContex.compactItemClassnames;
var classes = classNames(buttonPrefixCls, compactItemClassnames, className, hashId);
if ('overlay' in props) {
dropdownProps.overlay = overlay;
}
if ('open' in props) {
dropdownProps.open = open;
}
if ('placement' in props) {
dropdownProps.placement = placement;
} else {
dropdownProps.placement = direction === 'rtl' ? 'bottomLeft' : 'bottomRight';
}
var leftButton = /*#__PURE__*/React.createElement(Button$1, {
type: type,
danger: danger,
disabled: disabled,
loading: loading,
onClick: onClick,
htmlType: htmlType,
href: href,
title: title
}, children);
var rightButton = /*#__PURE__*/React.createElement(Button$1, {
type: type,
danger: danger,
icon: icon
});
var _buttonsRender = buttonsRender([leftButton, rightButton]),
_buttonsRender2 = _slicedToArray(_buttonsRender, 2),
leftButtonToRender = _buttonsRender2[0],
rightButtonToRender = _buttonsRender2[1];
return wrapSSR( /*#__PURE__*/React.createElement(Space$1.Compact, _extends$1({
className: classes,
size: compactSize,
block: true
}, restProps), leftButtonToRender, /*#__PURE__*/React.createElement(Dropdown$1, _extends$1({}, dropdownProps), rightButtonToRender)));
};
DropdownButton.__ANT_BUTTON = true;
var DropdownButton$1 = DropdownButton;
tuple('topLeft', 'topCenter', 'topRight', 'bottomLeft', 'bottomCenter', 'bottomRight', 'top', 'bottom');
var Dropdown = function Dropdown(props) {
var _React$useContext = React.useContext(ConfigContext),
getContextPopupContainer = _React$useContext.getPopupContainer,
getPrefixCls = _React$useContext.getPrefixCls,
direction = _React$useContext.direction;
// Warning for deprecated usage
if (process.env.NODE_ENV !== 'production') {
[['visible', 'open'], ['onVisibleChange', 'onOpenChange']].forEach(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
deprecatedName = _ref2[0],
newName = _ref2[1];
process.env.NODE_ENV !== "production" ? warning$2(!(deprecatedName in props), 'Dropdown', "`" + deprecatedName + "` is deprecated which will be removed in next major version, please use `" + newName + "` instead.") : void 0;
});
process.env.NODE_ENV !== "production" ? warning$2(!('overlay' in props), 'Dropdown', '`overlay` is deprecated. Please use `menu` instead.') : void 0;
}
var getTransitionName = function getTransitionName() {
var rootPrefixCls = getPrefixCls();
var _props$placement = props.placement,
placement = _props$placement === void 0 ? '' : _props$placement,
transitionName = props.transitionName;
if (transitionName !== undefined) {
return transitionName;
}
if (placement.includes('top')) {
return rootPrefixCls + "-slide-down";
}
return rootPrefixCls + "-slide-up";
};
var getPlacement = function getPlacement() {
var placement = props.placement;
if (!placement) {
return direction === 'rtl' ? 'bottomRight' : 'bottomLeft';
}
if (placement.includes('Center')) {
var newPlacement = placement.slice(0, placement.indexOf('Center'));
process.env.NODE_ENV !== "production" ? warning$2(!placement.includes('Center'), 'Dropdown', "You are using '" + placement + "' placement in Dropdown, which is deprecated. Try to use '" + newPlacement + "' instead.") : void 0;
return newPlacement;
}
return placement;
};
var menu = props.menu,
arrow = props.arrow,
customizePrefixCls = props.prefixCls,
children = props.children,
trigger = props.trigger,
disabled = props.disabled,
dropdownRender = props.dropdownRender,
getPopupContainer = props.getPopupContainer,
overlayClassName = props.overlayClassName,
open = props.open,
onOpenChange = props.onOpenChange,
visible = props.visible,
onVisibleChange = props.onVisibleChange,
_props$mouseEnterDela = props.mouseEnterDelay,
mouseEnterDelay = _props$mouseEnterDela === void 0 ? 0.15 : _props$mouseEnterDela,
_props$mouseLeaveDela = props.mouseLeaveDelay,
mouseLeaveDelay = _props$mouseLeaveDela === void 0 ? 0.1 : _props$mouseLeaveDela;
if (process.env.NODE_ENV !== 'production') {
[['visible', 'open'], ['onVisibleChange', 'onOpenChange']].forEach(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
deprecatedName = _ref4[0],
newName = _ref4[1];
process.env.NODE_ENV !== "production" ? warning$2(!(deprecatedName in props), 'Dropdown', "`" + deprecatedName + "` is deprecated, please use `" + newName + "` instead.") : void 0;
});
}
var prefixCls = getPrefixCls('dropdown', customizePrefixCls);
var _useStyle = useStyle(prefixCls),
_useStyle2 = _slicedToArray(_useStyle, 2),
wrapSSR = _useStyle2[0],
hashId = _useStyle2[1];
var child = React.Children.only(children);
var dropdownTrigger = cloneElement(child, {
className: classNames(prefixCls + "-trigger", _defineProperty$1({}, prefixCls + "-rtl", direction === 'rtl'), child.props.className),
disabled: disabled
});
var triggerActions = disabled ? [] : trigger;
var alignPoint;
if (triggerActions && triggerActions.includes('contextMenu')) {
alignPoint = true;
}
// =========================== Open ============================
var _useMergedState = useMergedState(false, {
value: open !== null && open !== void 0 ? open : visible
}),
_useMergedState2 = _slicedToArray(_useMergedState, 2),
mergedOpen = _useMergedState2[0],
setOpen = _useMergedState2[1];
var onInnerOpenChange = useEvent(function (nextOpen) {
onOpenChange === null || onOpenChange === void 0 ? void 0 : onOpenChange(nextOpen);
onVisibleChange === null || onVisibleChange === void 0 ? void 0 : onVisibleChange(nextOpen);
setOpen(nextOpen);
});
// =========================== Overlay ============================
var overlayClassNameCustomized = classNames(overlayClassName, hashId, _defineProperty$1({}, prefixCls + "-rtl", direction === 'rtl'));
var builtinPlacements = getPlacements({
arrowPointAtCenter: _typeof$1(arrow) === 'object' && arrow.pointAtCenter,
autoAdjustOverflow: true
});
var onMenuClick = React.useCallback(function () {
setOpen(false);
}, []);
var renderOverlay = function renderOverlay() {
// rc-dropdown already can process the function of overlay, but we have check logic here.
// So we need render the element to check and pass back to rc-dropdown.
var overlay = props.overlay;
var overlayNode;
if (menu === null || menu === void 0 ? void 0 : menu.items) {
overlayNode = /*#__PURE__*/React.createElement(Menu$1, _extends$1({}, menu));
} else if (typeof overlay === 'function') {
overlayNode = overlay();
} else {
overlayNode = overlay;
}
if (dropdownRender) {
overlayNode = dropdownRender(overlayNode);
}
overlayNode = React.Children.only(typeof overlayNode === 'string' ? /*#__PURE__*/React.createElement("span", null, overlayNode) : overlayNode);
return /*#__PURE__*/React.createElement(OverrideProvider, {
prefixCls: prefixCls + "-menu",
expandIcon: /*#__PURE__*/React.createElement("span", {
className: prefixCls + "-menu-submenu-arrow"
}, /*#__PURE__*/React.createElement(RightOutlined$1, {
className: prefixCls + "-menu-submenu-arrow-icon"
})),
mode: "vertical",
selectable: false,
onClick: onMenuClick,
validator: function validator(_ref5) {
var mode = _ref5.mode;
// Warning if use other mode
process.env.NODE_ENV !== "production" ? warning$2(!mode || mode === 'vertical', 'Dropdown', "mode=\"" + mode + "\" is not supported for Dropdown's Menu.") : void 0;
}
}, /*#__PURE__*/React.createElement(NoCompactStyle, null, overlayNode));
};
// ============================ Render ============================
return wrapSSR( /*#__PURE__*/React.createElement(Dropdown$3, _extends$1({
alignPoint: alignPoint
}, props, {
mouseEnterDelay: mouseEnterDelay,
mouseLeaveDelay: mouseLeaveDelay,
visible: mergedOpen,
builtinPlacements: builtinPlacements,
arrow: !!arrow,
overlayClassName: overlayClassNameCustomized,
prefixCls: prefixCls,
getPopupContainer: getPopupContainer || getContextPopupContainer,
transitionName: getTransitionName(),
trigger: triggerActions,
overlay: renderOverlay,
placement: getPlacement(),
onVisibleChange: onInnerOpenChange
}), dropdownTrigger));
};
Dropdown.Button = DropdownButton$1;
// We don't care debug panel
var PurePanel = genPurePanel(Dropdown, 'dropdown', function (prefixCls) {
return prefixCls;
});
/* istanbul ignore next */
var WrapPurePanel = function WrapPurePanel(props) {
return /*#__PURE__*/React.createElement(PurePanel, _extends$1({}, props), /*#__PURE__*/React.createElement("span", null));
};
Dropdown._InternalPanelDoNotUseOrYouWillBeFired = WrapPurePanel;
var Dropdown$1 = Dropdown;
var TopBar = function (_a) {
var items = _a.items, notifications = _a.notifications, user = _a.user, avatar = _a.avatar, disableAllNotificationsLink = _a.disableAllNotificationsLink, app_logo = _a.app_logo;
var _b = useState([]), notificationsItems = _b[0], setNotificationsItems = _b[1];
var _c = useState(), appLogo = _c[0], setAppLogo = _c[1];
useEffect(function () {
var _a;
var items = [];
if (notifications === null || notifications === void 0 ? void 0 : notifications.amount) {
items = (_a = notifications === null || notifications === void 0 ? void 0 : notifications.messages) === null || _a === void 0 ? void 0 : _a.map(function (value, index) { return ({
label: (React__default.createElement("div", { className: styles$6.notification },
React__default.createElement("div", { className: styles$6.label }, value),
React__default.createElement(Tooltip$1, { title: "Marquer comme lue" },
React__default.createElement("div", { className: styles$6.unread, onClick: function (e) {
e === null || e === void 0 ? void 0 : e.stopPropagation();
if (notifications.onMarkAsRead !== null)
notifications.onMarkAsRead(notifications.ids[index]);
} })))),
key: index.toString(),
}); });
if (!disableAllNotificationsLink) {
items === null || items === void 0 ? void 0 : items.push({ type: 'divider' });
items === null || items === void 0 ? void 0 : items.push({
label: (React__default.createElement("span", { className: 'text-small notification-label' }, notifications.amount < 5
? 'Voir toutes les notifications'
: "Voir les ".concat(notifications.amount, " notifications"))),
key: ((items === null || items === void 0 ? void 0 : items.length) + 1).toString(),
onClick: function () {
window.location.replace(notifications === null || notifications === void 0 ? void 0 : notifications.page);
},
});
}
}
else {
items === null || items === void 0 ? void 0 : items.push({
label: React__default.createElement("span", { className: 'text-small' }, "Aucune notification."),
key: 0,
});
}
setNotificationsItems(items);
}, [notifications]);
useEffect(function () {
setAppLogo(app_logo);
}, []);
return (React__default.createElement("div", { className: styles$6.topBar },
React__default.createElement("nav", { className: styles$6.navigation },
React__default.createElement(Link, { href: "/", className: styles$6.homeLink },
React__default.createElement("svg", { width: "146", height: "32", viewBox: "0 0 146 32", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
React__default.createElement("g", { clipPath: "url(#clip0_2_135)" },
React__default.createElement("path", { d: "M29.7672 9.38667V16.419C29.7672 17.92 29.2491 18.5905 28.891 19.1848C28.4034 19.9848 27.7101 20.701 26.933 21.2114C26.8568 21.2571 26.773 21.3105 26.6891 21.3562C26.6815 21.3562 26.6739 21.3638 26.6663 21.3714C26.4225 21.5162 26.1634 21.6533 25.8968 21.76C25.8968 21.76 25.8587 21.7752 25.8358 21.7829C25.112 22.0876 24.3196 22.2476 23.4891 22.2476H6.2701C5.09677 22.2476 3.99962 21.92 3.05486 21.3562C1.22629 20.259 -0.00799561 18.2476 -0.00799561 15.939V6.30095C-0.000376559 2.83429 2.80343 0 6.2701 0H23.4968C26.5596 0 29.0968 2.20952 29.653 5.11238C29.6682 5.18095 29.6758 5.24952 29.691 5.3181C29.7063 5.38667 29.7139 5.45524 29.7215 5.53143C29.7596 5.79048 29.7672 6.04191 29.7672 6.30095V6.8419H25.8434V6.30095C25.8434 5.65333 25.592 5.07429 25.1806 4.64C24.7539 4.20571 24.1672 3.93905 23.4968 3.93905H6.2701C4.94438 3.93905 3.91581 4.98286 3.91581 6.29333V15.939C3.91581 17.2724 4.94438 18.301 6.2701 18.301H23.4968C24.213 18.301 24.8377 17.9962 25.2644 17.5086C25.3939 17.3562 25.5082 17.181 25.5996 16.9981V16.9829L28.6396 10.7429C28.5558 10.8267 27.1996 12.0838 26.1406 12.7086C25.3101 13.1962 23.3977 13.2876 22.5215 13.3029H14.3844C14.3691 11.139 16.1139 9.37905 18.2777 9.37905H25.8663H29.7672V9.38667Z", fill: "#A2C1D3" }),
React__default.createElement("path", { d: "M54.9562 15.6724V19.9924C54.9562 20.8152 54.7962 21.6 54.499 22.3238C53.5695 24.6248 51.3067 26.2629 48.6781 26.2629H29.8209V28.0838C29.8209 30.2476 28.0609 32.0076 25.8971 32.0076V28.0533C25.8971 24.8914 28.4571 22.3314 31.619 22.3314H48.6781C48.6781 22.3314 48.7314 22.3314 48.7619 22.3314C50.0343 22.2933 51.0324 21.28 51.0324 20V15.68C51.0324 14.3771 49.9809 13.3257 48.6857 13.3257H32.32V9.39429H48.6781C52.1295 9.39429 54.9562 12.2133 54.9562 15.6724V15.6724Z", fill: "#1E1E41" })),
(typeof appLogo === 'string') ?
(React__default.createElement("text", { x: "63", y: "17", fill: "black" }, appLogo)) : (appLogo ||
React__default.createElement("path", { d: "M73.667 5.136L70.179 9.664L66.691 5.12H64.739V16H66.691V8.336L70.179 12.88L73.667 8.336V16.016H75.6191V5.136H73.667ZM86.184 16H88.28L84.04 5.136H81.928L77.704 16H79.784L80.712 13.616H85.272L86.184 16ZM81.464 11.664L82.984 7.696L84.52 11.664H81.464ZM89.515 4.16C90.075 4.16 90.555 3.696 90.555 3.104C90.555 2.528 90.075 2.048 89.515 2.048C88.939 2.048 88.475 2.528 88.475 3.104C88.475 3.696 88.939 4.16 89.515 4.16ZM92.875 4.16C93.435 4.16 93.915 3.696 93.915 3.104C93.915 2.528 93.435 2.048 92.875 2.048C92.299 2.048 91.835 2.528 91.835 3.104C91.835 3.696 92.299 4.16 92.875 4.16ZM90.219 16H92.171V5.12H90.219V16ZM102.574 16H104.67L100.43 5.136H98.318L94.094 16H96.174L97.102 13.616H101.662L102.574 16ZM97.854 11.664L99.374 7.696L100.91 11.664H97.854Z", fill: "#1E1E42" })),
React__default.createElement("path", { d: "M65.2841 20.4023V22.3018C65.2841 22.5199 65.2776 22.7314 65.2646 22.9365C65.2548 23.1416 65.2467 23.3011 65.2401 23.415H65.2841C65.4306 23.1742 65.6422 22.9707 65.9189 22.8047C66.1955 22.6387 66.5487 22.5557 66.9784 22.5557C67.649 22.5557 68.1829 22.7884 68.58 23.2539C68.9804 23.7161 69.1806 24.4046 69.1806 25.3193C69.1806 25.9215 69.0894 26.4294 68.9071 26.8428C68.7248 27.2562 68.4677 27.5687 68.1357 27.7803C67.8036 27.9919 67.4114 28.0977 66.9589 28.0977C66.5357 28.0977 66.1874 28.0195 65.914 27.8633C65.6438 27.7038 65.4355 27.5101 65.289 27.2822H65.2255L65.0595 28H64.4735V20.4023H65.2841ZM66.8466 23.2344C66.4592 23.2344 66.1516 23.3109 65.9237 23.4639C65.6959 23.6136 65.5315 23.8415 65.4306 24.1475C65.3329 24.4502 65.2841 24.8343 65.2841 25.2998V25.3438C65.2841 26.0176 65.3964 26.5335 65.621 26.8916C65.8456 27.2464 66.2541 27.4238 66.8466 27.4238C67.3446 27.4238 67.7174 27.2415 67.9648 26.877C68.2154 26.5124 68.3407 25.9915 68.3407 25.3145C68.3407 24.6243 68.217 24.1051 67.9696 23.7568C67.7255 23.4085 67.3511 23.2344 66.8466 23.2344ZM69.7519 22.6484H70.621L71.8026 25.7539C71.871 25.9362 71.9345 26.112 71.9931 26.2812C72.0517 26.4473 72.1037 26.6068 72.1493 26.7598C72.1949 26.9128 72.2307 27.0609 72.2567 27.2041H72.2909C72.3365 27.0413 72.4016 26.8281 72.4862 26.5645C72.5709 26.2975 72.662 26.0257 72.7597 25.749L73.8778 22.6484H74.7519L72.4228 28.7861C72.2991 29.1149 72.1542 29.4014 71.9882 29.6455C71.8254 29.8896 71.6269 30.0768 71.3925 30.207C71.1581 30.3405 70.8749 30.4072 70.5429 30.4072C70.3899 30.4072 70.2548 30.3975 70.1376 30.3779C70.0204 30.3617 69.9195 30.3421 69.8349 30.3193V29.6699C69.9065 29.6862 69.9927 29.7008 70.0937 29.7139C70.1978 29.7269 70.3052 29.7334 70.4159 29.7334C70.6177 29.7334 70.7919 29.6943 70.9384 29.6162C71.0881 29.5413 71.2167 29.4307 71.3241 29.2842C71.4315 29.1377 71.5243 28.9635 71.6024 28.7617L71.8954 28.0098L69.7519 22.6484ZM81.3778 24.2598H83.873V27.7217C83.4986 27.8486 83.1129 27.943 82.7157 28.0049C82.3218 28.0667 81.8808 28.0977 81.3925 28.0977C80.6503 28.0977 80.0237 27.9495 79.5126 27.6533C79.0048 27.3571 78.619 26.9355 78.3554 26.3887C78.0917 25.8385 77.9599 25.1859 77.9599 24.4307C77.9599 23.6917 78.1047 23.0472 78.3944 22.4971C78.6874 21.9469 79.109 21.5205 79.6591 21.2178C80.2125 20.9118 80.8765 20.7588 81.6513 20.7588C82.0484 20.7588 82.4244 20.7962 82.7792 20.8711C83.1373 20.9427 83.4693 21.0452 83.7753 21.1787L83.4579 21.9014C83.1942 21.7874 82.9029 21.6898 82.5839 21.6084C82.2681 21.527 81.941 21.4863 81.6024 21.4863C81.0198 21.4863 80.5201 21.6068 80.1034 21.8477C79.69 22.0885 79.3726 22.4287 79.1513 22.8682C78.9332 23.3076 78.8241 23.8285 78.8241 24.4307C78.8241 25.0264 78.9202 25.5456 79.1122 25.9883C79.3043 26.4277 79.6037 26.7695 80.0107 27.0137C80.4176 27.2578 80.9416 27.3799 81.5829 27.3799C81.9052 27.3799 82.1819 27.362 82.413 27.3262C82.6441 27.2871 82.8541 27.2415 83.0429 27.1895V25.002H81.3778V24.2598ZM87.911 22.5508C88.0185 22.5508 88.1308 22.5573 88.248 22.5703C88.3651 22.5801 88.4693 22.5947 88.5605 22.6143L88.4579 23.3662C88.37 23.3434 88.2724 23.3255 88.1649 23.3125C88.0575 23.2995 87.9566 23.293 87.8622 23.293C87.6474 23.293 87.4439 23.3369 87.2519 23.4248C87.0631 23.5094 86.897 23.6331 86.7538 23.7959C86.6106 23.9554 86.4983 24.1491 86.4169 24.377C86.3355 24.6016 86.2948 24.8522 86.2948 25.1289V28H85.4794V22.6484H86.1532L86.2411 23.6348H86.2753C86.386 23.4362 86.5194 23.2555 86.6757 23.0928C86.8319 22.9268 87.0126 22.7949 87.2177 22.6973C87.426 22.5996 87.6571 22.5508 87.911 22.5508ZM94.1855 25.3145C94.1855 25.7539 94.1285 26.1462 94.0146 26.4912C93.9006 26.8363 93.7362 27.1276 93.5214 27.3652C93.3065 27.6029 93.0461 27.7852 92.7401 27.9121C92.4374 28.0358 92.094 28.0977 91.7099 28.0977C91.3518 28.0977 91.023 28.0358 90.7235 27.9121C90.4273 27.7852 90.1702 27.6029 89.9521 27.3652C89.7372 27.1276 89.5696 26.8363 89.4491 26.4912C89.3319 26.1462 89.2733 25.7539 89.2733 25.3145C89.2733 24.7285 89.3726 24.2305 89.5712 23.8203C89.7698 23.4069 90.053 23.0928 90.4208 22.8779C90.7919 22.6598 91.233 22.5508 91.744 22.5508C92.2323 22.5508 92.6588 22.6598 93.0233 22.8779C93.3912 23.096 93.676 23.4118 93.8778 23.8252C94.0829 24.2354 94.1855 24.7318 94.1855 25.3145ZM90.1132 25.3145C90.1132 25.7441 90.1702 26.1169 90.2841 26.4326C90.398 26.7484 90.5738 26.9925 90.8114 27.165C91.0491 27.3376 91.3551 27.4238 91.7294 27.4238C92.1005 27.4238 92.4049 27.3376 92.6425 27.165C92.8834 26.9925 93.0608 26.7484 93.1747 26.4326C93.2886 26.1169 93.3456 25.7441 93.3456 25.3145C93.3456 24.888 93.2886 24.5202 93.1747 24.2109C93.0608 23.8984 92.885 23.6576 92.6474 23.4883C92.4097 23.319 92.1021 23.2344 91.7245 23.2344C91.1679 23.2344 90.7593 23.4183 90.4989 23.7861C90.2418 24.154 90.1132 24.6634 90.1132 25.3145ZM100.006 22.6484V28H99.3417L99.2245 27.248H99.1806C99.0699 27.4336 98.9267 27.5898 98.7509 27.7168C98.5751 27.8438 98.3765 27.9382 98.1552 28C97.9371 28.0651 97.7043 28.0977 97.4569 28.0977C97.0338 28.0977 96.6789 28.0293 96.3925 27.8926C96.106 27.7559 95.8896 27.5443 95.7431 27.2578C95.5998 26.9714 95.5282 26.6035 95.5282 26.1543V22.6484H96.3485V26.0957C96.3485 26.5417 96.4495 26.8753 96.6513 27.0967C96.8531 27.3148 97.1607 27.4238 97.5741 27.4238C97.9713 27.4238 98.287 27.349 98.5214 27.1992C98.759 27.0495 98.9299 26.8298 99.0341 26.54C99.1383 26.2471 99.1903 25.889 99.1903 25.4658V22.6484H100.006ZM104.234 22.5508C104.902 22.5508 105.434 22.7803 105.831 23.2393C106.228 23.6982 106.427 24.3883 106.427 25.3096C106.427 25.9183 106.336 26.4294 106.153 26.8428C105.971 27.2562 105.714 27.5687 105.382 27.7803C105.053 27.9919 104.664 28.0977 104.215 28.0977C103.932 28.0977 103.683 28.0602 103.468 27.9854C103.253 27.9105 103.069 27.8096 102.916 27.6826C102.763 27.5557 102.636 27.4173 102.535 27.2676H102.476C102.486 27.3945 102.498 27.5475 102.511 27.7266C102.527 27.9056 102.535 28.0618 102.535 28.1953V30.3926H101.72V22.6484H102.389L102.496 23.4395H102.535C102.639 23.2767 102.766 23.1286 102.916 22.9951C103.066 22.8584 103.248 22.751 103.463 22.6729C103.681 22.5915 103.938 22.5508 104.234 22.5508ZM104.093 23.2344C103.722 23.2344 103.422 23.306 103.194 23.4492C102.97 23.5924 102.805 23.8073 102.701 24.0938C102.597 24.377 102.542 24.7334 102.535 25.1631V25.3193C102.535 25.7718 102.584 26.1543 102.682 26.4668C102.782 26.7793 102.947 27.0169 103.175 27.1797C103.406 27.3424 103.715 27.4238 104.102 27.4238C104.434 27.4238 104.711 27.3343 104.933 27.1553C105.154 26.9762 105.318 26.7272 105.426 26.4082C105.536 26.0859 105.592 25.7165 105.592 25.2998C105.592 24.6683 105.468 24.167 105.221 23.7959C104.976 23.4215 104.6 23.2344 104.093 23.2344ZM109.903 22.5508C110.359 22.5508 110.75 22.6517 111.075 22.8535C111.401 23.0553 111.65 23.3385 111.822 23.7031C111.995 24.0645 112.081 24.4876 112.081 24.9727V25.4756H108.385C108.394 26.1038 108.551 26.5824 108.853 26.9111C109.156 27.2399 109.583 27.4043 110.133 27.4043C110.471 27.4043 110.771 27.3734 111.031 27.3115C111.292 27.2497 111.562 27.1585 111.842 27.0381V27.751C111.572 27.8714 111.303 27.9593 111.036 28.0146C110.772 28.07 110.46 28.0977 110.099 28.0977C109.584 28.0977 109.135 27.9935 108.751 27.7852C108.37 27.5736 108.074 27.2643 107.862 26.8574C107.651 26.4505 107.545 25.9525 107.545 25.3633C107.545 24.7871 107.641 24.2891 107.833 23.8691C108.028 23.446 108.302 23.1204 108.653 22.8926C109.008 22.6647 109.425 22.5508 109.903 22.5508ZM109.893 23.2148C109.461 23.2148 109.115 23.3564 108.858 23.6396C108.601 23.9229 108.448 24.3184 108.399 24.8262H111.231C111.228 24.5072 111.178 24.2272 111.08 23.9863C110.986 23.7422 110.841 23.5534 110.645 23.4199C110.45 23.2832 110.199 23.2148 109.893 23.2148ZM118.043 20.8613C118.964 20.8613 119.636 21.042 120.059 21.4033C120.486 21.7614 120.699 22.2757 120.699 22.9463C120.699 23.249 120.649 23.5371 120.548 23.8105C120.45 24.0807 120.291 24.32 120.069 24.5283C119.848 24.7334 119.557 24.8962 119.195 25.0166C118.837 25.1338 118.398 25.1924 117.877 25.1924H117.008V28H116.178V20.8613H118.043ZM117.965 21.5693H117.008V24.4795H117.784C118.24 24.4795 118.619 24.4307 118.922 24.333C119.228 24.2354 119.457 24.0775 119.61 23.8594C119.763 23.638 119.84 23.3451 119.84 22.9805C119.84 22.5052 119.688 22.152 119.386 21.9209C119.083 21.6865 118.609 21.5693 117.965 21.5693ZM124.503 22.5508C124.61 22.5508 124.723 22.5573 124.84 22.5703C124.957 22.5801 125.061 22.5947 125.152 22.6143L125.05 23.3662C124.962 23.3434 124.864 23.3255 124.757 23.3125C124.649 23.2995 124.548 23.293 124.454 23.293C124.239 23.293 124.036 23.3369 123.844 23.4248C123.655 23.5094 123.489 23.6331 123.346 23.7959C123.202 23.9554 123.09 24.1491 123.009 24.377C122.927 24.6016 122.887 24.8522 122.887 25.1289V28H122.071V22.6484H122.745L122.833 23.6348H122.867C122.978 23.4362 123.111 23.2555 123.267 23.0928C123.424 22.9268 123.604 22.7949 123.809 22.6973C124.018 22.5996 124.249 22.5508 124.503 22.5508ZM130.777 25.3145C130.777 25.7539 130.72 26.1462 130.606 26.4912C130.492 26.8363 130.328 27.1276 130.113 27.3652C129.898 27.6029 129.638 27.7852 129.332 27.9121C129.029 28.0358 128.686 28.0977 128.302 28.0977C127.944 28.0977 127.615 28.0358 127.315 27.9121C127.019 27.7852 126.762 27.6029 126.544 27.3652C126.329 27.1276 126.161 26.8363 126.041 26.4912C125.924 26.1462 125.865 25.7539 125.865 25.3145C125.865 24.7285 125.964 24.2305 126.163 23.8203C126.362 23.4069 126.645 23.0928 127.013 22.8779C127.384 22.6598 127.825 22.5508 128.336 22.5508C128.824 22.5508 129.251 22.6598 129.615 22.8779C129.983 23.096 130.268 23.4118 130.47 23.8252C130.675 24.2354 130.777 24.7318 130.777 25.3145ZM126.705 25.3145C126.705 25.7441 126.762 26.1169 126.876 26.4326C126.99 26.7484 127.166 26.9925 127.403 27.165C127.641 27.3376 127.947 27.4238 128.321 27.4238C128.692 27.4238 128.997 27.3376 129.234 27.165C129.475 26.9925 129.653 26.7484 129.767 26.4326C129.88 26.1169 129.937 25.7441 129.937 25.3145C129.937 24.888 129.88 24.5202 129.767 24.2109C129.653 23.8984 129.477 23.6576 129.239 23.4883C129.002 23.319 128.694 23.2344 128.316 23.2344C127.76 23.2344 127.351 23.4183 127.091 23.7861C126.834 24.154 126.705 24.6634 126.705 25.3145ZM131.534 30.4023C131.368 30.4023 131.223 30.3893 131.1 30.3633C130.976 30.3405 130.868 30.3128 130.777 30.2803V29.6211C130.878 29.6536 130.981 29.6781 131.085 29.6943C131.189 29.7139 131.306 29.7236 131.436 29.7236C131.658 29.7236 131.837 29.6618 131.974 29.5381C132.11 29.4144 132.179 29.1898 132.179 28.8643V22.6484H132.989V28.8447C132.989 29.1702 132.937 29.4486 132.833 29.6797C132.729 29.9141 132.569 30.0931 132.354 30.2168C132.14 30.3405 131.866 30.4023 131.534 30.4023ZM132.105 21.1787C132.105 20.9964 132.151 20.863 132.242 20.7783C132.336 20.6904 132.454 20.6465 132.594 20.6465C132.727 20.6465 132.841 20.6904 132.935 20.7783C133.033 20.863 133.082 20.9964 133.082 21.1787C133.082 21.3577 133.033 21.4912 132.935 21.5791C132.841 21.667 132.727 21.7109 132.594 21.7109C132.454 21.7109 132.336 21.667 132.242 21.5791C132.151 21.4912 132.105 21.3577 132.105 21.1787ZM136.768 22.5508C137.224 22.5508 137.615 22.6517 137.94 22.8535C138.266 23.0553 138.515 23.3385 138.687 23.7031C138.86 24.0645 138.946 24.4876 138.946 24.9727V25.4756H135.25C135.26 26.1038 135.416 26.5824 135.719 26.9111C136.021 27.2399 136.448 27.4043 136.998 27.4043C137.336 27.4043 137.636 27.3734 137.896 27.3115C138.157 27.2497 138.427 27.1585 138.707 27.0381V27.751C138.437 27.8714 138.168 27.9593 137.901 28.0146C137.638 28.07 137.325 28.0977 136.964 28.0977C136.449 28.0977 136 27.9935 135.616 27.7852C135.235 27.5736 134.939 27.2643 134.727 26.8574C134.516 26.4505 134.41 25.9525 134.41 25.3633C134.41 24.7871 134.506 24.2891 134.698 23.8691C134.893 23.446 135.167 23.1204 135.518 22.8926C135.873 22.6647 136.29 22.5508 136.768 22.5508ZM136.759 23.2148C136.326 23.2148 135.981 23.3564 135.724 23.6396C135.466 23.9229 135.313 24.3184 135.265 24.8262H138.097C138.093 24.5072 138.043 24.2272 137.945 23.9863C137.851 23.7422 137.706 23.5534 137.511 23.4199C137.315 23.2832 137.065 23.2148 136.759 23.2148ZM141.598 25.2607L139.747 22.6484H140.675L142.086 24.709L143.492 22.6484H144.41L142.559 25.2607L144.513 28H143.585L142.086 25.8174L140.577 28H139.659L141.598 25.2607Z", fill: "#1E1E42" }),
React__default.createElement("defs", null,
React__default.createElement("clipPath", { id: "clip0_2_135" },
React__default.createElement("rect", { width: "55.619", height: "32", fill: "white" }))))),
React__default.createElement("ul", { className: styles$6.items }, items.map(function (item) { return (React__default.createElement("li", { key: item.label, className: styles$6.item },
React__default.createElement("a", { className: "text-tiny ".concat(styles$6.link, " ").concat(item.active ? styles$6.active : ''), href: item.href },
React__default.createElement("span", { className: styles$6.firstWord }, item.label.split(' ').length > 1 ? item.label.split(' ')[0] : item.label),
React__default.createElement("br", null),
item.label.split(' ').length > 1 ? item.label.split(' ').splice(1).join(' ') : ''))); }))),
React__default.createElement("div", { className: styles$6.rightSide },
React__default.createElement("button", { className: styles$6.showNotificationsButton },
React__default.createElement(Dropdown$1, { menu: { items: notificationsItems }, trigger: ['hover'], placement: 'bottomLeft', arrow: true },
React__default.createElement(Badge$1, { count: notifications === null || notifications === void 0 ? void 0 : notifications.amount, offset: [-5, 5] },
React__default.createElement(BellOutlined$1, { style: { fontSize: '24px' } })))),
React__default.createElement(Dropdown$1, { menu: { items: [{ label: React__default.createElement("a", { href: "/logout" }, "D\u00E9connexion"), key: '1', danger: true }] }, trigger: ['hover'] },
React__default.createElement("a", { onClick: function (e) { return e.preventDefault(); } },
React__default.createElement(Space$1, null,
React__default.createElement("div", null,
React__default.createElement(UserProfileWidget, { user: user, avatar: avatar })),
React__default.createElement(DownOutlined$1, null)))))));
};
var css_248z$5 = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.SideBar-module_sideBar__JrC80 {\n width: 15rem;\n height: 100%;\n max-height: 100%;\n background-color: #FFFFFF;\n color: #666666;\n border-right: 1px solid #DDE3EB;\n overflow: hidden;\n font-size: 1rem;\n line-height: 1.125rem;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n gap: 4rem;\n padding: 2rem;\n margin: 0;\n list-style: none;\n transition-duration: 0.3s;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_separator__xI0ch {\n width: 100%;\n height: 0.5px;\n background-color: #DDE3EB;\n}\n.SideBar-module_sideBar__JrC80 button {\n display: block;\n width: 100%;\n cursor: pointer;\n background: none;\n border: none;\n margin: 0;\n padding: 0;\n color: white;\n font-size: 1rem;\n line-height: 1.125rem;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_block__xQPlr {\n margin: 1.5rem 0;\n display: flex;\n flex-direction: column;\n overflow-y: auto;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_block__xQPlr:first-of-type {\n margin-top: 0;\n margin-bottom: 3.5rem;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_block__xQPlr:last-of-type {\n margin-bottom: 0;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_block__xQPlr.SideBar-module_body__KjE0e {\n max-height: 40vh;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_block__xQPlr.SideBar-module_foot__ni7dc {\n margin: 0;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_block__xQPlr .SideBar-module_item__qV5cH > .SideBar-module_link__F8ft9 {\n padding: 0.5rem 0;\n color: inherit;\n display: flex;\n align-items: center;\n gap: 0.75rem;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_block__xQPlr .SideBar-module_item__qV5cH > .SideBar-module_link__F8ft9 .SideBar-module_iconContainer__ztHYB {\n width: 1.5rem;\n min-width: 1.5rem;\n height: 1.5rem;\n min-height: 1.5rem;\n border: 2px solid white;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_block__xQPlr .SideBar-module_item__qV5cH > .SideBar-module_link__F8ft9 .SideBar-module_iconContainer__ztHYB.SideBar-module_hasIcon__57pAL {\n border: none;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_block__xQPlr .SideBar-module_item__qV5cH > .SideBar-module_link__F8ft9 .SideBar-module_iconContainer__ztHYB span,\n.SideBar-module_sideBar__JrC80 .SideBar-module_block__xQPlr .SideBar-module_item__qV5cH > .SideBar-module_link__F8ft9 .SideBar-module_iconContainer__ztHYB svg,\n.SideBar-module_sideBar__JrC80 .SideBar-module_block__xQPlr .SideBar-module_item__qV5cH > .SideBar-module_link__F8ft9 .SideBar-module_iconContainer__ztHYB img {\n width: 100%;\n height: 100%;\n object-fit: cover;\n object-position: center;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_block__xQPlr .SideBar-module_item__qV5cH > .SideBar-module_link__F8ft9.SideBar-module_toggleSideBarButton__7Os5m .SideBar-module_iconContainer__ztHYB {\n width: 2rem;\n min-width: 2rem;\n height: 2rem;\n min-height: 2rem;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_block__xQPlr .SideBar-module_item__qV5cH:first-of-type > .SideBar-module_link__F8ft9 {\n padding-top: 0;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_block__xQPlr .SideBar-module_item__qV5cH:last-of-type > .SideBar-module_link__F8ft9 {\n padding-bottom: 0;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_text__-8Xdj {\n line-height: 1.5em;\n}\n.SideBar-module_sideBar__JrC80 .SideBar-module_children__IgrMq {\n margin: 1rem 0;\n max-width: 100%;\n}\n.SideBar-module_sideBar__JrC80.SideBar-module_close__nIzio {\n width: 5.125rem;\n padding: 2rem 0.5rem;\n}\n.SideBar-module_sideBar__JrC80.SideBar-module_close__nIzio .SideBar-module_separator__xI0ch {\n display: none;\n}\n.SideBar-module_sideBar__JrC80.SideBar-module_close__nIzio .SideBar-module_block__xQPlr {\n width: 4.125rem;\n animation: SideBar-module_animationOnClose__uyekj forwards 0.3s ease-in-out;\n}\n.SideBar-module_sideBar__JrC80.SideBar-module_close__nIzio .SideBar-module_block__xQPlr .SideBar-module_link__F8ft9 {\n animation: SideBar-module_animationOnCloseOnLink__70yjf forwards 0.3s ease-in-out;\n}\n.SideBar-module_sideBar__JrC80:not(.SideBar-module_close__nIzio) .SideBar-module_link__F8ft9:hover .SideBar-module_text__-8Xdj {\n transform: translateX(0.5rem);\n}\n\n@keyframes SideBar-module_animationOnClose__uyekj {\n 0% {\n opacity: 100%;\n transform: translateX(0);\n }\n 50% {\n opacity: 0;\n transform: translateX(100%);\n }\n 50.01% {\n transform: translateX(-100%);\n }\n 100% {\n transform: translateX(0%);\n }\n}\n@keyframes SideBar-module_animationOnCloseOnLink__70yjf {\n 0% {\n flex-direction: row;\n }\n 25% {\n flex-direction: row;\n }\n 100% {\n gap: 0.25rem;\n font-size: 0.75rem;\n flex-direction: column;\n }\n}";
var styles$5 = {"sideBar":"SideBar-module_sideBar__JrC80","separator":"SideBar-module_separator__xI0ch","block":"SideBar-module_block__xQPlr","body":"SideBar-module_body__KjE0e","foot":"SideBar-module_foot__ni7dc","item":"SideBar-module_item__qV5cH","link":"SideBar-module_link__F8ft9","iconContainer":"SideBar-module_iconContainer__ztHYB","hasIcon":"SideBar-module_hasIcon__57pAL","toggleSideBarButton":"SideBar-module_toggleSideBarButton__7Os5m","text":"SideBar-module_text__-8Xdj","children":"SideBar-module_children__IgrMq","close":"SideBar-module_close__nIzio","animationOnClose":"SideBar-module_animationOnClose__uyekj","animationOnCloseOnLink":"SideBar-module_animationOnCloseOnLink__70yjf"};
styleInject(css_248z$5);
var SideBar = function (_a) {
var items = _a.items, children = _a.children;
var _b = useState(true), isClose = _b[0], setIsClose = _b[1];
var renderItem = function (item) { return (React__default.createElement("li", { key: item.label, className: styles$5.item },
React__default.createElement(Link, { href: item.href, legacyBehavior: true },
React__default.createElement("a", { className: styles$5.link },
React__default.createElement("div", { className: "".concat(styles$5.iconContainer, " ").concat(item.icon ? styles$5.hasIcon : '') }, item.icon),
React__default.createElement("span", { className: styles$5.text }, item.label))))); };
return (React__default.createElement("ul", { className: "".concat(styles$5.sideBar, " ").concat(isClose ? styles$5.close : '') },
React__default.createElement("div", { className: styles$5.head },
React__default.createElement("div", { className: styles$5.block },
React__default.createElement("li", { className: styles$5.item },
React__default.createElement("button", { onClick: function () { return setIsClose(function (prev) { return !prev; }); }, className: "".concat(styles$5.link, " ").concat(styles$5.toggleSideBarButton) },
React__default.createElement("div", { className: styles$5.iconContainer }, isClose ? (React__default.createElement("svg", { width: "28", height: "22", viewBox: "0 0 28 22", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
React__default.createElement("path", { d: "M1 2H27C27.5 2 28 1.5625 28 1.0625C28 0.5625 27.5 0 27 0H1C0.4375 0 0 0.5 0 1C0 1.5 0.4375 2 1 2ZM27 10H1C0.4375 10 0 10.5 0 11C0 11.5625 0.4375 12 1 12H27C27.5 12 28 11.5625 28 11C28 10.5 27.5 10 27 10ZM27 20H1C0.4375 20 0 20.5 0 21C0 21.5 0.4375 22 1 22H27C27.5 22 28 21.5625 28 21.0625C28 20.5625 27.5 20 27 20Z", fill: "#666666" }))) : (React__default.createElement("svg", { width: "21", height: "19", viewBox: "0 0 21 19", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
React__default.createElement("path", { d: "M20.9531 10C20.9531 10.4219 20.625 10.75 20.25 10.75H3.1875L9.51562 17.7812C9.79688 18.0625 9.79688 18.5312 9.46875 18.8125C9.32812 18.9531 9.14062 19 9 19C8.76562 19 8.57812 18.9531 8.4375 18.7656L0.9375 10.5156C0.65625 10.2344 0.65625 9.8125 0.9375 9.53125L8.4375 1.28125C8.71875 0.953125 9.1875 0.953125 9.46875 1.23438C9.79688 1.51562 9.79688 1.98438 9.51562 2.26562L3.1875 9.25H20.25C20.625 9.25 20.9531 9.625 20.9531 10Z", fill: "#666666" }))))))),
items.head ? (React__default.createElement(React__default.Fragment, null,
React__default.createElement("div", { className: styles$5.block }, items.head.map(function (item) { return renderItem(item); })),
React__default.createElement("div", { className: styles$5.separator }))) : null,
children && !isClose ? (React__default.createElement(React__default.Fragment, null,
React__default.createElement("div", { className: styles$5.children }, children),
React__default.createElement("div", { className: styles$5.separator }))) : null,
React__default.createElement("div", { className: "".concat(styles$5.block, " ").concat(styles$5.body) }, items.body.map(function (item) { return renderItem(item); }))),
items.foot ? (React__default.createElement("div", { className: "".concat(styles$5.block, " ").concat(styles$5.foot) }, items.foot.map(function (item) { return renderItem(item); }))) : null));
};
var css_248z$4 = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.TabBar-module_tabBar__V0sMq {\n width: 100%;\n max-width: 100%;\n overflow: auto;\n display: flex;\n align-items: flex-end;\n flex-wrap: nowrap;\n gap: 2rem;\n position: relative;\n}\n.TabBar-module_tabBar__V0sMq .TabBar-module_tab__Ltbpt {\n background: none;\n border: none;\n cursor: pointer;\n padding: 0.75rem 1rem;\n font-weight: 700;\n text-align: center;\n letter-spacing: 0.04em;\n text-transform: uppercase;\n color: #666666;\n max-width: 12rem;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n transition: color 0.3s ease-in-out;\n position: relative;\n}\n.TabBar-module_tabBar__V0sMq .TabBar-module_tab__Ltbpt::after {\n content: \"\";\n position: absolute;\n z-index: 2;\n bottom: 0;\n left: 0;\n right: 0;\n height: 2px;\n background-color: #002559;\n transform-origin: 100% 0;\n transform: scaleX(0);\n transition: transform 0.3s ease-in-out;\n}\n.TabBar-module_tabBar__V0sMq .TabBar-module_tab__Ltbpt.TabBar-module_active__Hg5fw {\n color: #002559;\n}\n.TabBar-module_tabBar__V0sMq .TabBar-module_tab__Ltbpt.TabBar-module_active__Hg5fw::after {\n transform-origin: 0 0;\n transform: scaleX(1);\n}\n.TabBar-module_tabBar__V0sMq .TabBar-module_tab__Ltbpt:hover {\n color: #002559;\n}\n.TabBar-module_tabBar__V0sMq::after {\n content: \"\";\n position: absolute;\n z-index: 1;\n bottom: 0;\n height: 1px;\n left: 0;\n right: 0;\n background-color: #DDE3EB;\n}";
var styles$4 = {"tabBar":"TabBar-module_tabBar__V0sMq","tab":"TabBar-module_tab__Ltbpt","active":"TabBar-module_active__Hg5fw"};
styleInject(css_248z$4);
var TabBar = function (_a) {
var tabs = _a.tabs, currentTab = _a.currentTab, setCurrentTab = _a.setCurrentTab;
return (React__default.createElement("div", { className: styles$4.tabBar }, tabs.map(function (tab) { return (React__default.createElement("button", { key: tab, className: "text-small ".concat(styles$4.tab, " ").concat(tab === currentTab ? styles$4.active : ''), onClick: function () { return setCurrentTab(tab); } }, tab)); })));
};
var css_248z$3 = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.Breadcrumb-module_breadcrumb__xjrnf {\n max-width: 100%;\n background-color: #FFFFFF;\n padding: 1rem 0;\n}\n.Breadcrumb-module_breadcrumb__xjrnf .Breadcrumb-module_list__Z9z1- {\n max-width: 100%;\n list-style: none;\n margin: 0;\n padding: 0;\n color: #666666;\n line-height: 120%;\n display: flex;\n align-items: center;\n flex-wrap: wrap;\n gap: 0.5rem;\n}\n.Breadcrumb-module_breadcrumb__xjrnf .Breadcrumb-module_list__Z9z1- .Breadcrumb-module_item__79sly {\n display: flex;\n align-items: center;\n}\n.Breadcrumb-module_breadcrumb__xjrnf .Breadcrumb-module_list__Z9z1- .Breadcrumb-module_item__79sly .Breadcrumb-module_link__dRjYE {\n display: flex;\n align-items: center;\n gap: 0.375rem;\n transition: color 0.3s;\n}\n.Breadcrumb-module_breadcrumb__xjrnf .Breadcrumb-module_list__Z9z1- .Breadcrumb-module_item__79sly .Breadcrumb-module_link__dRjYE:hover {\n color: #002559;\n}\n.Breadcrumb-module_breadcrumb__xjrnf .Breadcrumb-module_list__Z9z1- .Breadcrumb-module_item__79sly .Breadcrumb-module_link__dRjYE.Breadcrumb-module_currentLink__1e0Xw {\n pointer-events: none;\n}\n.Breadcrumb-module_breadcrumb__xjrnf .Breadcrumb-module_list__Z9z1- .Breadcrumb-module_item__79sly .Breadcrumb-module_chevronIcon__0pv5q {\n margin-right: 0.5rem;\n}\n.Breadcrumb-module_breadcrumb__xjrnf .Breadcrumb-module_list__Z9z1- .Breadcrumb-module_item__79sly .Breadcrumb-module_chevronIcon__0pv5q path {\n fill: #666666;\n}";
var styles$3 = {"breadcrumb":"Breadcrumb-module_breadcrumb__xjrnf","list":"Breadcrumb-module_list__Z9z1-","item":"Breadcrumb-module_item__79sly","link":"Breadcrumb-module_link__dRjYE","currentLink":"Breadcrumb-module_currentLink__1e0Xw","chevronIcon":"Breadcrumb-module_chevronIcon__0pv5q"};
styleInject(css_248z$3);
var pages = [
{
route: 'projects',
label: 'Projets',
},
{
route: 'affairs',
label: 'Affaires',
},
{
route: 'billing',
label: 'Facturation',
},
{
route: 'team',
label: 'Équipe',
},
{
route: 'files',
label: 'Fichiers',
},
{
route: 'advancement',
label: 'Avancement',
},
];
var Breadcrumb = function (_a) {
var dynamicRoutesLabel = _a.dynamicRoutesLabel;
var _b = useRouter(), route = _b.route, asPath = _b.asPath;
var paths = asPath.split('/').slice(1);
var routes = route.split('/').slice(1);
var capitalize = function (str) { return str.charAt(0).toUpperCase() + str.slice(1); };
var isDynamicRoute = function (route) { return /^\[[a-z0-9]+\]$/i.test(route); };
var isLastItemInArray = function (item, array) { return array.indexOf(item) === array.length - 1; };
var renderChevronIcon = function () { return (React__default.createElement("svg", { className: styles$3.chevronIcon, width: "4", height: "7", viewBox: "0 0 4 7", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
React__default.createElement("path", { d: "M3.69824 3.41797L1.34668 6.2002L0.546875 5.71484L2.50879 3.31543L0.546875 0.922852L1.34668 0.451172L3.69824 3.2334V3.41797Z", fill: "#666666" }))); };
var renderBreadcrumbItem = function (route) {
var link = '/' + paths.slice(0, routes.indexOf(route) + 1).join('/');
return (React__default.createElement(Link, { href: link, className: "".concat(styles$3.link, " ").concat(isLastItemInArray(route, routes) ? styles$3.currentLink : '') },
React__default.createElement(React__default.Fragment, null,
getBreadcrumbItemIconByRoute(route),
getBreadcrumbItemLabelByRoute(route))));
};
var getBreadcrumbItemIconByRoute = function (route) {
var _a;
var iconFoundInPages = (_a = pages.find(function (page) { return page.route === route; })) === null || _a === void 0 ? void 0 : _a.icon;
return iconFoundInPages;
};
var getBreadcrumbItemLabelByRoute = function (route) {
var _a;
if (isDynamicRoute(route))
return getLabelForDynamicRouteItem(paths[routes.indexOf(route)]);
var labelFoundInPages = (_a = pages.find(function (page) { return page.route === route; })) === null || _a === void 0 ? void 0 : _a.label;
return labelFoundInPages || capitalize(paths[routes.indexOf(route)]);
};
var dynamicRouteItemsCount = 0;
var getLabelForDynamicRouteItem = function (path) {
var label = path;
if (dynamicRoutesLabel === null || dynamicRoutesLabel === void 0 ? void 0 : dynamicRoutesLabel.length) {
label = dynamicRoutesLabel[dynamicRouteItemsCount];
dynamicRouteItemsCount++;
}
return label;
};
return (React__default.createElement("nav", { className: styles$3.breadcrumb },
React__default.createElement("ul", { className: "text-small ".concat(styles$3.list) },
React__default.createElement("li", { className: styles$3.item },
React__default.createElement(Link, { className: styles$3.link, href: "/" },
React__default.createElement(React__default.Fragment, null,
React__default.createElement(HomeOutlined$1, null),
"Accueil"))),
route !== '/' &&
routes.map(function (route, index) {
return (React__default.createElement("li", { key: index, className: styles$3.item },
renderChevronIcon(),
renderBreadcrumbItem(route)));
}))));
};
var css_248z$2 = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.Filters-module_filters__3V7Ue {\n height: 23rem;\n max-height: 23rem;\n width: 58rem;\n max-width: 100%;\n}\n.Filters-module_filters__3V7Ue .Filters-module_filtersContainer__0Z9Gc {\n background-color: #FFFFFF;\n height: 100%;\n width: 100%;\n display: grid;\n grid-template-columns: 1fr 3fr 2fr;\n}\n.Filters-module_filters__3V7Ue .Filters-module_filtersContainer__0Z9Gc .Filters-module_categoriesContainer__5rEaH {\n display: flex;\n flex-direction: column;\n padding: 1rem 0;\n overflow: auto;\n}\n.Filters-module_filters__3V7Ue .Filters-module_filtersContainer__0Z9Gc .Filters-module_categoriesContainer__5rEaH .Filters-module_categoryButton__-jTaH {\n background: none;\n border: none;\n cursor: pointer;\n display: flex;\n align-items: center;\n gap: 1rem;\n padding: 0.75rem;\n font-weight: 500;\n letter-spacing: 0.04em;\n color: #666666;\n width: 100%;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n transition: 0.3s ease-in-out;\n}\n.Filters-module_filters__3V7Ue .Filters-module_filtersContainer__0Z9Gc .Filters-module_categoriesContainer__5rEaH .Filters-module_categoryButton__-jTaH .Filters-module_categoryName__fVe9V {\n width: 100%;\n text-align: left;\n}\n.Filters-module_filters__3V7Ue .Filters-module_filtersContainer__0Z9Gc .Filters-module_categoriesContainer__5rEaH .Filters-module_categoryButton__-jTaH .Filters-module_chevron__GclxI {\n height: 0.75rem;\n min-height: 0.75rem;\n text-align: right;\n}\n.Filters-module_filters__3V7Ue .Filters-module_filtersContainer__0Z9Gc .Filters-module_categoriesContainer__5rEaH .Filters-module_categoryButton__-jTaH.Filters-module_active__yQqPV {\n color: #002559;\n background-color: #D5E5EF;\n font-weight: 700;\n}\n.Filters-module_filters__3V7Ue .Filters-module_filtersContainer__0Z9Gc .Filters-module_categoriesContainer__5rEaH .Filters-module_categoryButton__-jTaH:hover {\n color: #002559;\n}\n.Filters-module_filters__3V7Ue .Filters-module_filtersContainer__0Z9Gc .Filters-module_searchDataContainer__zV-Y1 {\n padding: 1rem;\n border-right: 1px solid #dde3eb;\n border-left: 1px solid #dde3eb;\n display: flex;\n flex-direction: column;\n gap: 0.75rem;\n overflow: hidden;\n}\n.Filters-module_filters__3V7Ue .Filters-module_filtersContainer__0Z9Gc .Filters-module_searchDataContainer__zV-Y1 .Filters-module_dataItemContainer__zSQXc {\n overflow: auto;\n display: flex;\n flex-direction: column;\n gap: 0.75rem;\n}\n.Filters-module_filters__3V7Ue .Filters-module_filtersContainer__0Z9Gc .Filters-module_selectionContainer__HfPcE {\n display: flex;\n flex-direction: column;\n gap: 1rem;\n padding: 1rem;\n max-height: 100%;\n overflow: hidden;\n}\n.Filters-module_filters__3V7Ue .Filters-module_filtersContainer__0Z9Gc .Filters-module_selectionContainer__HfPcE .Filters-module_title__4TqCq {\n font-weight: 700;\n font-size: 0.875rem;\n letter-spacing: 0.04em;\n text-transform: uppercase;\n color: #002559;\n}\n.Filters-module_filters__3V7Ue .Filters-module_filtersContainer__0Z9Gc .Filters-module_selectionContainer__HfPcE .Filters-module_body__Pjist {\n flex-grow: 1;\n display: flex;\n flex-direction: column;\n overflow: scroll;\n gap: 1rem;\n}\n.Filters-module_filters__3V7Ue .Filters-module_filtersContainer__0Z9Gc .Filters-module_selectionContainer__HfPcE .Filters-module_body__Pjist .Filters-module_section__BTnwQ .Filters-module_categoryTitle__BGawj {\n margin-bottom: 0.5rem;\n}\n.Filters-module_filters__3V7Ue .Filters-module_dataItemContainer__zSQXc {\n display: flex;\n flex-direction: column;\n gap: 0.75rem;\n}\n.Filters-module_filters__3V7Ue .Filters-module_dataItemContainer__zSQXc .Filters-module_dataItem__DUpop {\n background: none;\n border: none;\n cursor: pointer;\n padding: 0;\n display: flex;\n align-items: center;\n gap: 0.25rem;\n width: 100%;\n}\n.Filters-module_filters__3V7Ue .Filters-module_dataItemContainer__zSQXc .Filters-module_dataItem__DUpop .Filters-module_selectedButton__ffK-m {\n width: 1rem;\n}\n.Filters-module_filters__3V7Ue .Filters-module_dataItemContainer__zSQXc .Filters-module_dataItem__DUpop .Filters-module_deSelectedButton__E4JPB {\n width: 1rem;\n filter: opacity(40%);\n}\n.Filters-module_filters__3V7Ue .Filters-module_dataItemContainer__zSQXc .Filters-module_dataItem__DUpop .Filters-module_dataItemSelected__fP6iD {\n font-weight: 700;\n width: 100%;\n text-align: left;\n}";
var styles$2 = {"filters":"Filters-module_filters__3V7Ue","filtersContainer":"Filters-module_filtersContainer__0Z9Gc","categoriesContainer":"Filters-module_categoriesContainer__5rEaH","categoryButton":"Filters-module_categoryButton__-jTaH","categoryName":"Filters-module_categoryName__fVe9V","chevron":"Filters-module_chevron__GclxI","active":"Filters-module_active__yQqPV","searchDataContainer":"Filters-module_searchDataContainer__zV-Y1","dataItemContainer":"Filters-module_dataItemContainer__zSQXc","selectionContainer":"Filters-module_selectionContainer__HfPcE","title":"Filters-module_title__4TqCq","body":"Filters-module_body__Pjist","section":"Filters-module_section__BTnwQ","categoryTitle":"Filters-module_categoryTitle__BGawj","dataItem":"Filters-module_dataItem__DUpop","selectedButton":"Filters-module_selectedButton__ffK-m","deSelectedButton":"Filters-module_deSelectedButton__E4JPB","dataItemSelected":"Filters-module_dataItemSelected__fP6iD"};
styleInject(css_248z$2);
var circlePlus = (React__default.createElement("svg", { width: "14", height: "15", viewBox: "0 0 14 15", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
React__default.createElement("path", { d: "M7 0.25C3.11719 0.25 0 3.39453 0 7.25C0 11.1328 3.11719 14.25 7 14.25C10.8555 14.25 14 11.1328 14 7.25C14 3.39453 10.8555 0.25 7 0.25ZM7 13.375C3.60938 13.375 0.875 10.6406 0.875 7.25C0.875 3.88672 3.60938 1.125 7 1.125C10.3633 1.125 13.125 3.88672 13.125 7.25C13.125 10.6406 10.3633 13.375 7 13.375ZM9.625 6.8125H7.4375V4.625C7.4375 4.40625 7.21875 4.1875 7 4.1875C6.75391 4.1875 6.5625 4.40625 6.5625 4.625V6.8125H4.375C4.12891 6.8125 3.9375 7.03125 3.9375 7.25C3.9375 7.49609 4.12891 7.6875 4.375 7.6875H6.5625V9.875C6.5625 10.1211 6.75391 10.3125 7 10.3125C7.21875 10.3125 7.4375 10.1211 7.4375 9.875V7.6875H9.625C9.84375 7.6875 10.0625 7.49609 10.0625 7.25C10.0625 7.03125 9.84375 6.8125 9.625 6.8125Z", fill: "#333333" })));
var circleMinus = (React__default.createElement("svg", { width: "14", height: "15", viewBox: "0 0 14 15", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
React__default.createElement("path", { opacity: "0.4", d: "M9.625 6.8125H4.375C4.12891 6.8125 3.9375 7.03125 3.9375 7.25C3.9375 7.49609 4.12891 7.6875 4.375 7.6875H9.625C9.84375 7.6875 10.0625 7.49609 10.0625 7.25C10.0625 7.03125 9.84375 6.8125 9.625 6.8125ZM7 0.25C3.11719 0.25 0 3.39453 0 7.25C0 11.1328 3.11719 14.25 7 14.25C10.8555 14.25 14 11.1328 14 7.25C14 3.39453 10.8555 0.25 7 0.25ZM7 13.375C3.60938 13.375 0.875 10.6406 0.875 7.25C0.875 3.88672 3.60938 1.125 7 1.125C10.3633 1.125 13.125 3.88672 13.125 7.25C13.125 10.6406 10.3633 13.375 7 13.375Z", fill: "#333333" })));
var chevron = (React__default.createElement("svg", { className: styles$2.chevron, width: "7", height: "12", viewBox: "0 0 7 12", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
React__default.createElement("path", { d: "M0.992188 11.1562C0.898438 11.0859 0.851562 10.9922 0.851562 10.8984C0.851562 10.8047 0.898438 10.7109 0.96875 10.6406L5.21094 6.02344L0.96875 1.38281C0.828125 1.24219 0.828125 1.00781 0.992188 0.867188C1.13281 0.726562 1.36719 0.726562 1.50781 0.890625L6.00781 5.76562C6.14844 5.90625 6.14844 6.11719 6.00781 6.25781L1.50781 11.1328C1.36719 11.2969 1.13281 11.2969 0.992188 11.1562Z", fill: "#333333" })));
var Filters = function (_a) {
var _b;
var onSubmit = _a.onSubmit, filtersSelection = _a.filtersSelection, data = _a.data;
var saveSelection = function (selectedValues) {
onSubmit(selectedValues);
};
var _c = React__default.useState(''), searchData = _c[0], setSearchData = _c[1];
var _d = React__default.useState(0), currentTab = _d[0], setCurrentTab = _d[1];
var _e = useState(filtersSelection), selectedValues = _e[0], setSelectedValues = _e[1];
var sortArray = function (array, sortArray) {
return array
.slice()
.sort(function (a, b) { return sortArray.indexOf(a.categoryName) - sortArray.indexOf(b.categoryName); });
};
var categories = data.map(function (el) { return el.categoryName; });
var onSelect = function (key, category) {
var _a;
var filteredSV = selectedValues.filter(function (selectedValue) { return selectedValue.categoryName !== category; });
var oldCategoryValues = (_a = selectedValues.find(function (sv) { return sv.categoryName === category; })) === null || _a === void 0 ? void 0 : _a.key;
var newCategoryValues = {
categoryName: category,
key: oldCategoryValues && oldCategoryValues.length > 0 ? __spreadArray([], new Set(__spreadArray([key], oldCategoryValues, true)), true) : [key],
};
var selection = __spreadArray(__spreadArray([], filteredSV, true), [newCategoryValues], false);
var selectedValuesSorted = sortArray(selection, categories);
setSelectedValues(__spreadArray([], selectedValuesSorted, true));
};
var onDeselect = function (key, category) {
var _a;
var filteredSV = selectedValues.filter(function (selectedValue) { return selectedValue.categoryName !== category; });
var oldCategoryValues = (_a = selectedValues.find(function (sv) { return sv.categoryName === category; })) === null || _a === void 0 ? void 0 : _a.key;
var newCategoryValues = {
categoryName: category,
key: oldCategoryValues && oldCategoryValues.length > 0 ? oldCategoryValues.filter(function (value) { return value !== key; }) : [],
};
setSelectedValues(__spreadArray(__spreadArray([], filteredSV, true), [newCategoryValues], false).filter(function (category) { return category.key.length > 0; }));
};
var isSelected = function (key, category) {
return !selectedValues.some(function (e) { return e.categoryName === category && e.key.includes(key); });
};
return (React__default.createElement("div", { className: styles$2.filters },
React__default.createElement(ShadowCard, null,
React__default.createElement("div", { className: styles$2.filtersContainer },
React__default.createElement("div", { className: styles$2.categoriesContainer }, data.map(function (tab, index) { return (React__default.createElement("button", { key: tab.categoryName, className: "text-small ".concat(styles$2.categoryButton, " ").concat(index === currentTab ? styles$2.active : ''), onClick: function () {
setCurrentTab(index);
} },
React__default.createElement("div", { className: styles$2.categoryName }, tab.categoryName),
chevron)); })),
React__default.createElement("div", { className: styles$2.searchDataContainer },
React__default.createElement(Input, { type: "search", value: searchData, placeholder: 'Rechercher', setValue: function (e) {
setSearchData(e);
} }),
React__default.createElement("div", { className: styles$2.dataItemContainer }, data.length > 0 &&
((_b = data[currentTab]) === null || _b === void 0 ? void 0 : _b.options.filter(function (item) { return item.name.includes(searchData); }).map(function (item) { return (React__default.createElement("button", { key: item.key, className: styles$2.dataItem, onClick: function () {
isSelected(item.key, data[currentTab].categoryName)
? onSelect(item.key, data[currentTab].categoryName)
: onDeselect(item.key, data[currentTab].categoryName);
} },
isSelected(item.key, data[currentTab].categoryName) ? circlePlus : circleMinus,
React__default.createElement("span", { className: "".concat(isSelected(item.key, data[currentTab].categoryName) ? '' : styles$2.dataItemSelected) }, item.name))); })))),
React__default.createElement("div", { className: styles$2.selectionContainer },
React__default.createElement("h3", { className: styles$2.title }, "S\u00E9lection"),
React__default.createElement("div", { className: styles$2.body }, selectedValues.length > 0
? sortArray(selectedValues, categories).map(function (item, index) { return (React__default.createElement("section", { key: index, className: styles$2.section },
React__default.createElement("div", { className: styles$2.categoryTitle },
item.key.length + ' ',
item.key.length > 1
? item.categoryName
: item.categoryName.slice(0, item.categoryName.length - 1)),
React__default.createElement("div", { className: styles$2.dataItemContainer }, item.key.map(function (key) { return (React__default.createElement("button", { className: styles$2.dataItem, onClick: function () {
return isSelected(key, item.categoryName)
? onSelect(key, item.categoryName)
: onDeselect(key, item.categoryName);
} },
circleMinus,
data.map(function (el) {
return el.options.map(function (option) { return (option.key === key ? React__default.createElement("span", null, option.name) : ''); });
}))); })))); })
: 'Aucun filtre sélectionné'),
React__default.createElement("div", { className: styles$2.submitButtonContainer },
React__default.createElement(Button$2, { small: true, onClick: function () { return saveSelection(selectedValues); } }, "Confirmer")))))));
};
var css_248z$1 = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.FilterBar-module_filterBar__zBM-C {\n max-width: 100%;\n padding: 1rem 2rem;\n background-color: #FAFAFA;\n display: flex;\n justify-content: space-between;\n}";
var styles$1 = {"filterBar":"FilterBar-module_filterBar__zBM-C"};
styleInject(css_248z$1);
var FilterBar = function (_a) {
var children = _a.children;
return React__default.createElement("div", { className: styles$1.filterBar }, children);
};
var css_248z = "/**************************************************************\n********************* GENERAL *********************\n***************************************************************/\n/**************************************************************\n********************* COLORS *********************\n***************************************************************/\n.Section-module_section__afMtN {\n display: flex;\n flex-direction: column;\n gap: 1rem;\n}\n.Section-module_section__afMtN .Section-module_head__27WOW {\n display: flex;\n align-items: center;\n justify-content: space-between;\n}\n.Section-module_section__afMtN .Section-module_head__27WOW .Section-module_link__yQhtq, .Section-module_section__afMtN .Section-module_head__27WOW .Section-module_button__SardW {\n background: none;\n border: none;\n padding: 0;\n cursor: pointer;\n color: #002559;\n}\n.Section-module_section__afMtN .Section-module_content__b-X1- {\n flex-grow: 1;\n}";
var styles = {"section":"Section-module_section__afMtN","head":"Section-module_head__27WOW","link":"Section-module_link__yQhtq","button":"Section-module_button__SardW","content":"Section-module_content__b-X1-"};
styleInject(css_248z);
var Section = function (_a) {
var title = _a.title, link = _a.link, button = _a.button, children = _a.children;
return (React__default.createElement("section", { className: styles.section },
React__default.createElement("div", { className: styles.head },
React__default.createElement("h2", null, title),
link ? (React__default.createElement(Link, { className: "text-small ".concat(styles.link), href: link.href }, link.label)) : button ? (React__default.createElement("button", { className: "text-small ".concat(styles.button), onClick: button.onClick }, button.label)) : null),
React__default.createElement("div", { className: styles.content }, children)));
};
export { Breadcrumb, Button$2 as Button, DropdownFilter, FilterBar, Filters, FormItem, Grid, InformationsTable, Input, ManageItemButton, NewItemCard as ManageItemCard, Modal, ProgressBar, ProgressBarRounded, QuickActionCard, RecentActivities, RecentActivitiesCard, Section, Select, ShadowCard, SideBar, TabBar, Textarea, TopBar, UserProfileWidget };