UNPKG

vite-pages-theme-doc

Version:
1,626 lines (1,512 loc) 63.8 kB
import * as React from 'react'; import { useContext } from 'react'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 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 _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(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(key) === "symbol" ? key : String(key); } 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 _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); } /* 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(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, valid, message); } function noteOnce(valid, message) { call(note, valid, message); } warningOnce.preMessage = preMessage; warningOnce.resetWarned = resetWarned; warningOnce.noteOnce = noteOnce; /* eslint-enable */ function _defineProperty(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 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 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 _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 _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 _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 _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); } 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; } /** * 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(a) === 'object' && _typeof(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 Entity = /*#__PURE__*/function () { function Entity(instanceId) { _classCallCheck(this, Entity); _defineProperty(this, "instanceId", void 0); _defineProperty(this, "cache", new Map()); this.instanceId = instanceId; } /** @private Internal cache map. Do not access this directly */ _createClass(Entity, [{ key: "get", value: function get(keys) { return this.cache.get(keys.join('%')) || null; } }, { key: "update", value: function update(keys, valueFn) { var path = keys.join('%'); 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 _excluded = ["children"]; var ATTR_TOKEN = 'data-token-hash'; var ATTR_MARK = 'data-css-hash'; var ATTR_DEV_CACHE_PATH = 'data-dev-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); 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 ? 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 StyleProvider = function StyleProvider(props) { var children = props.children, restProps = _objectWithoutProperties(props, _excluded); var parentContext = React.useContext(StyleContext); var context = useMemo(function () { var mergedContext = _objectSpread2({}, parentContext); Object.keys(restProps).forEach(function (key) { var value = restProps[key]; if (restProps[key] !== undefined) { mergedContext[key] = value; } }); var cache = restProps.cache; mergedContext.cache = mergedContext.cache || createCache(); mergedContext.defaultCache = !cache && parentContext.defaultCache; return mergedContext; }, [parentContext, restProps], function (prev, next) { return !isEqual(prev[0], next[0], true) || !isEqual(prev[1], next[1], true); }); return /*#__PURE__*/React.createElement(StyleContext.Provider, { value: context }, children); }; 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 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; var styleNode = document.createElement('style'); styleNode.setAttribute(APPEND_ORDER, getOrder(prepend)); 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 (prepend === 'queue') { var existStyle = findStyles(container).filter(function (node) { return ['prepend', 'prependQueue'].includes(node.getAttribute(APPEND_ORDER)); }); 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 flattenToken(token) { var str = ''; Object.keys(token).forEach(function (key) { var value = token[key]; str += key; if (value && _typeof(value) === 'object') { str += flattenToken(value); } else { str += value; } }); return str; } /** * Convert derivative token to key string */ function token2key(token, salt) { return murmur2("".concat(salt, "_").concat(flattenToken(token))); } var layerKey = "layer-".concat(Date.now(), "-").concat(Math.random()).replace(/\./g, ''); var layerWidth = '903px'; function supportSelector(styleStr, handleElement) { if (canUseDom()) { var _ele$parentNode; updateCSS(styleStr, layerKey); var _ele = document.createElement('div'); _ele.style.position = 'fixed'; _ele.style.left = '0'; _ele.style.top = '0'; handleElement === null || handleElement === void 0 ? void 0 : handleElement(_ele); document.body.appendChild(_ele); if (process.env.NODE_ENV !== 'production') { _ele.innerHTML = 'Test'; _ele.style.zIndex = '9999999'; } var support = getComputedStyle(_ele).width === layerWidth; (_ele$parentNode = _ele.parentNode) === null || _ele$parentNode === void 0 ? void 0 : _ele$parentNode.removeChild(_ele); removeCSS(layerKey); return support; } return false; } var canLayer = undefined; function supportLayer() { if (canLayer === undefined) { canLayer = supportSelector("@layer ".concat(layerKey, " { .").concat(layerKey, " { width: ").concat(layerWidth, "!important; } }"), function (ele) { ele.className = layerKey; }); } return canLayer; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } function _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 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) { 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 useClientCache(prefix, keyPath, cacheFn, onCacheRemove) { var _React$useContext = React.useContext(StyleContext), globalCache = _React$useContext.cache; var fullPath = [prefix].concat(_toConsumableArray(keyPath)); var HMRUpdate = useHMR(); // Create cache React.useMemo(function () { globalCache.update(fullPath, function (prevCache) { var _ref = prevCache || [], _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 ? void 0 : onCacheRemove(tmpCache, HMRUpdate); tmpCache = null; } var mergedCache = tmpCache || cacheFn(); return [times + 1, mergedCache]; }); }, /* eslint-disable react-hooks/exhaustive-deps */ [fullPath.join('_')] /* eslint-enable */); // Remove if no need anymore React.useEffect(function () { return function () { globalCache.update(fullPath, function (prevCache) { var _ref3 = prevCache || [], _ref4 = _slicedToArray(_ref3, 2), _ref4$ = _ref4[0], times = _ref4$ === void 0 ? 0 : _ref4$, cache = _ref4[1]; var nextCount = times - 1; if (nextCount === 0) { onCacheRemove === null || onCacheRemove === void 0 ? void 0 : onCacheRemove(cache, false); return null; } return [times - 1, cache]; }); }; }, fullPath); return globalCache.get(fullPath)[1]; } 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 ? void 0 : _style$parentNode.removeChild(style); } }); } } // 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; }); if (cleanableKeyList.length < tokenKeyList.length) { 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(_objectSpread2({}, derivativeToken), overrideToken); // Format if needed if (format) { mergedDerivativeToken = format(mergedDerivativeToken); } return mergedDerivativeToken; }; /** * 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), instanceId = _useContext.cache.instanceId; 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; // Basic - We do basic cache here var mergedToken = React.useMemo(function () { return Object.assign.apply(Object, [{}].concat(_toConsumableArray(tokens))); }, [tokens]); var tokenStr = React.useMemo(function () { return flattenToken(mergedToken); }, [mergedToken]); var overrideTokenStr = React.useMemo(function () { return flattenToken(override); }, [override]); var cachedToken = useClientCache('token', [salt, theme.id, tokenStr, overrideTokenStr], function () { var mergedDerivativeToken = getComputedToken(mergedToken, override, theme, formatToken); // Optimize for `useStyleRegister` performance var tokenKey = token2key(mergedDerivativeToken, salt); mergedDerivativeToken._tokenKey = tokenKey; recordCleanToken(tokenKey); var hashId = "".concat(hashPrefix, "-").concat(murmur2(tokenKey)); mergedDerivativeToken._hashId = hashId; // Not used return [mergedDerivativeToken, hashId]; }, function (cache) { // Remove token will remove all related style cleanTokenStyle(cache[0]._tokenKey, instanceId); }); return cachedToken; } 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 * @return {number} */ function indexof(value, search) { return value.indexOf(search); } /** * @param {string} value * @param {number} index * @return {number} */ function charat(value, index) { return value.charCodeAt(index) | 0; } /** * @param {string} value * @param {number} begin * @param {number} end * @return {string} */ function substr(value, begin, end) { return value.slice(begin, end); } /** * @param {string} value * @return {number} */ function strlen(value) { return value.length; } /** * @param {any[]} value * @return {number} */ function sizeof(value) { return value.length; } /** * @param {any} value * @param {any[]} array * @return {any} */ function append(value, array) { return array.push(value), value; } var line = 1; var column = 1; var length = 0; var position = 0; var character = 0; var characters = ''; /** * @param {string} value * @param {object | null} root * @param {object | null} parent * @param {string} type * @param {string[] | string} props * @param {object[] | string} children * @param {number} length */ function node(value, root, parent, type, props, children, length) { return { value: value, root: root, parent: parent, type: type, props: props, children: children, line: line, column: column, length: length, return: '' }; } /** * @return {number} */ function char() { return character; } /** * @return {number} */ function prev() { character = position > 0 ? charat(characters, --position) : 0; if (column--, character === 10) column = 1, line--; return character; } /** * @return {number} */ function next() { character = position < length ? charat(characters, position++) : 0; if (column++, character === 10) column = 1, line++; return character; } /** * @return {number} */ function peek() { return charat(characters, position); } /** * @return {number} */ function caret() { return position; } /** * @param {number} begin * @param {number} end * @return {string} */ function slice(begin, end) { return substr(characters, begin, end); } /** * @param {number} type * @return {number} */ function token(type) { switch (type) { // \0 \t \n \r \s whitespace token case 0: case 9: case 10: case 13: case 32: return 5; // ! + , / > @ ~ isolate token case 33: case 43: case 44: case 47: case 62: case 64: case 126: // ; { } breakpoint token case 59: case 123: case 125: return 4; // : accompanied token case 58: return 3; // " ' ( [ opening delimit token case 34: case 39: case 40: case 91: return 2; // ) ] closing delimit token case 41: case 93: return 1; } return 0; } /** * @param {string} value * @return {any[]} */ function alloc(value) { return line = column = 1, length = strlen(characters = value), position = 0, []; } /** * @param {any} value * @return {any} */ function dealloc(value) { return characters = '', value; } /** * @param {number} type * @return {string} */ function delimit(type) { return trim(slice(position - 1, delimiter(type === 91 ? type + 2 : type === 40 ? type + 1 : type))); } /** * @param {number} type * @return {string} */ function whitespace(type) { while (character = peek()) if (character < 33) next();else break; return token(type) > 2 || token(character) > 3 ? '' : ' '; } /** * @param {number} index * @param {number} count * @return {string} */ function escaping(index, count) { while (--count && next()) // not 0-9 A-F a-f if (character < 48 || character > 102 || character > 57 && character < 65 || character > 70 && character < 97) break; return slice(index, caret() + (count < 6 && peek() == 32 && next() == 32)); } /** * @param {number} type * @return {number} */ function delimiter(type) { while (next()) switch (character) { // ] ) " ' case type: return position; // " ' case 34: case 39: if (type !== 34 && type !== 39) delimiter(character); break; // ( case 40: if (type === 41) delimiter(type); break; // \ case 92: next(); break; } return position; } /** * @param {number} type * @param {number} index * @return {number} */ function commenter(type, index) { while (next()) // // if (type + character === 47 + 10) break; // /* else if (type + character === 42 + 42 && peek() === 47) break; return '/*' + slice(index, position - 1) + '*' + from(type === 47 ? type : next()); } /** * @param {number} index * @return {string} */ function identifier(index) { while (!token(peek())) next(); return slice(index, position); } /** * @param {string} value * @return {object[]} */ function compile(value) { return dealloc(parse('', null, null, null, [''], value = alloc(value), 0, [0], value)); } /** * @param {string} value * @param {object} root * @param {object?} parent * @param {string[]} rule * @param {string[]} rules * @param {string[]} rulesets * @param {number[]} pseudo * @param {number[]} points * @param {string[]} declarations * @return {object} */ function parse(value, root, parent, rule, rules, rulesets, pseudo, points, declarations) { var index = 0; var offset = 0; var length = pseudo; var atrule = 0; var property = 0; var previous = 0; var variable = 1; var scanning = 1; var ampersand = 1; var character = 0; var type = ''; var props = rules; var children = rulesets; var reference = rule; var characters = type; while (scanning) switch (previous = character, character = next()) { // ( case 40: if (previous != 108 && charat(characters, length - 1) == 58) { if (indexof(characters += replace(delimit(character), '&', '&\f'), '&\f') != -1) ampersand = -1; break; } // " ' [ case 34: case 39: case 91: characters += delimit(character); break; // \t \n \r \s case 9: case 10: case 13: case 32: characters += whitespace(previous); break; // \ case 92: characters += escaping(caret() - 1, 7); continue; // / case 47: switch (peek()) { case 42: case 47: append(comment(commenter(next(), caret()), root, parent), declarations); break; default: characters += '/'; } break; // { case 123 * variable: points[index++] = strlen(characters) * ampersand; // } ; \0 case 125 * variable: case 59: case 0: switch (character) { // \0 } case 0: case 125: scanning = 0; // ; case 59 + offset: if (ampersand == -1) characters = replace(characters, /\f/g, ''); if (property > 0 && strlen(characters) - length) append(property > 32 ? declaration(characters + ';', rule, parent, length - 1) : declaration(replace(characters, ' ', '') + ';', rule, parent, length - 2), declarations); break; // @ ; case 59: characters += ';'; // { rule/at-rule default: append(reference = ruleset(characters, root, parent, index, offset, rules, points, type, props = [], children = [], length), rulesets); if (character === 123) if (offset === 0) parse(characters, root, reference, reference, props, rulesets, length, points, children);else switch (atrule === 99 && charat(characters, 3) === 110 ? 100 : atrule) { // d l m s case 100: case 108: case 109: case 115: parse(value, reference, reference, rule && append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length), children), rules, children, length, points, rule ? props : children); break; default: parse(characters, reference, reference, reference, [''], children, 0, points, children); } } index = offset = property = 0, variable = ampersand = 1, type = characters = '', length = pseudo; break; // : case 58: length = 1 + strlen(characters), property = previous; default: if (variable < 1) if (character == 123) --variable;else if (character == 125 && variable++ == 0 && prev() == 125) continue; switch (characters += from(character), character * variable) { // & case 38: ampersand = offset > 0 ? 1 : (characters += '\f', -1); break; // , case 44: points[index++] = (strlen(characters) - 1) * ampersand, ampersand = 1; break; // @ case 64: // - if (peek() === 45) characters += delimit(next()); atrule = peek(), offset = length = strlen(type = characters += identifier(caret())), character++; break; // - case 45: if (previous === 45 && strlen(characters) == 2) variable = 0; } } return rulesets; } /** * @param {string} value * @param {object} root * @param {object?} parent * @param {number} index * @param {number} offset * @param {string[]} rules * @param {number[]} points * @param {string} type * @param {string[]} props * @param {string[]} children * @param {number} length * @return {object} */ function ruleset(value, root, parent, index, offset, rules, points, type, props, children, length) { var post = offset - 1; var rule = offset === 0 ? rules : ['']; var size = sizeof(rule); for (var i = 0, j = 0, k = 0; i < index; ++i) for (var x = 0, y = substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x) if (z = trim(j > 0 ? rule[x] + ' ' + y : replace(y, /&\f/g, rule[x]))) props[k++] = z; return node(value, root, parent, offset === 0 ? RULESET : type, props, children, length); } /** * @param {number} value * @param {object} root * @param {object?} parent * @return {object} */ function comment(value, root, parent) { return node(value, root, parent, COMMENT, from(char()), substr(value, 2, -2), 0); } /** * @param {string} value * @param {object} root * @param {object?} parent * @param {number} length * @return {object} */ function declaration(value, root, parent, length) { return node(value, root, parent, DECLARATION, substr(value, 0, length), substr(value, length + 1, -1), length); } /** * @param {object[]} children * @param {function} callback * @return {string} */ function serialize(children, callback) { var output = ''; var length = sizeof(children); for (var i = 0; i < length; i++) output += callback(children[i], i, children, callback) || ''; return output; } /** * @param {object} element * @param {number} index * @param {object[]} children * @param {function} callback * @return {string} */ function stringify(element, index, children, callback) { switch (element.type) { case LAYER: if (element.children.length) break; case IMPORT: case DECLARATION: return element.return = element.return || element.value; case COMMENT: return ''; case KEYFRAMES: return element.return = element.value + '{' + serialize(element.children, callback) + '}'; case RULESET: element.value = element.props.join(','); } return strlen(children = serialize(element.children, callback)) ? element.return = element.value + '{' + children + '}' : ''; } 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 isClientSide = canUseDom(); 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); return serialized.replace(/\{%%%\:[^;];}/g, ';'); } function isCompoundCSSProperty(value) { return _typeof(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 ? 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(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(_objectSpread2({}, effectStyle), childEffectStyle); styleStr += "".concat(mergedKey).concat(_parsedStr2); } else { var _value; function appendStyle(cssKey, cssValue) { if (process.env.NODE_ENV !== 'production' && (_typeof(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(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; } /** * Register a style to the global style sheet. */ function useStyleRegister(info,