UNPKG

tdesign-react

Version:
1,156 lines (1,119 loc) 44.9 kB
/** * tdesign v1.15.1 * (c) 2025 tdesign * @license MIT */ import { _ as _objectWithoutProperties } from '../../_chunks/dep-6b660ef0.js'; import { _ as _createClass, a as _classCallCheck } from '../../_chunks/dep-46885238.js'; import { _ as _typeof } from '../../_chunks/dep-eca3a3de.js'; import { _ as _defineProperty } from '../../_chunks/dep-cb0a3966.js'; import React from 'react'; import { omit } from 'lodash-es'; import require$$0 from 'react-is'; function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } var propTypes = {exports: {}}; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret$3 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1 = ReactPropTypesSecret$3; var has$2 = Function.call.bind(Object.prototype.hasOwnProperty); var printWarning$1 = function printWarning() {}; if (process.env.NODE_ENV !== 'production') { var ReactPropTypesSecret$2 = ReactPropTypesSecret_1; var loggedTypeFailures = {}; var has$1 = has$2; printWarning$1 = function printWarning(text) { var message = 'Warning: ' + text; if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {/**/} }; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes$1(typeSpecs, values, location, componentName, getStack) { if (process.env.NODE_ENV !== 'production') { for (var typeSpecName in typeSpecs) { if (has$1(typeSpecs, typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + _typeof(typeSpecs[typeSpecName]) + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); err.name = 'Invariant Violation'; throw err; } error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$2); } catch (ex) { error = ex; } if (error && !(error instanceof Error)) { printWarning$1((componentName || 'React class') + ': type specification of ' + location + ' `' + typeSpecName + '` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a ' + _typeof(error) + '. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).'); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; printWarning$1('Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')); } } } } } /** * Resets warning cache when testing. * * @private */ checkPropTypes$1.resetWarningCache = function () { if (process.env.NODE_ENV !== 'production') { loggedTypeFailures = {}; } }; var checkPropTypes_1 = checkPropTypes$1; var ReactIs$1 = require$$0; var assign = objectAssign; var ReactPropTypesSecret$1 = ReactPropTypesSecret_1; var has = has$2; var checkPropTypes = checkPropTypes_1; var printWarning = function printWarning() {}; if (process.env.NODE_ENV !== 'production') { printWarning = function printWarning(text) { var message = 'Warning: ' + text; if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; } function emptyFunctionThatReturnsNull() { return null; } var factoryWithTypeCheckers = function factoryWithTypeCheckers(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bigint: createPrimitiveTypeChecker('bigint'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), elementType: createElementTypeTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker, exact: createStrictShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message, data) { this.message = message; this.data = data && _typeof(data) === 'object' ? data : {}; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (process.env.NODE_ENV !== 'production') { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret$1) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package var err = new Error('Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types'); err.name = 'Invariant Violation'; throw err; } else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if (!manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3) { printWarning('You are manually calling a React.PropTypes validation ' + 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.'); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'), { expectedType: expectedType }); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunctionThatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret$1); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createElementTypeTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!ReactIs$1.isValidElementType(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { if (process.env.NODE_ENV !== 'production') { if (arguments.length > 1) { printWarning('Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' + 'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).'); } else { printWarning('Invalid argument supplied to oneOf, expected an array.'); } } return emptyFunctionThatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues, function replacer(key, value) { var type = getPreciseType(value); if (type === 'symbol') { return String(value); } return value; }); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (has(propValue, key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret$1); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { process.env.NODE_ENV !== 'production' ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunctionThatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== 'function') { printWarning('Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.'); return emptyFunctionThatReturnsNull; } } function validate(props, propName, componentName, location, propFullName) { var expectedTypes = []; for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; var checkerResult = checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret$1); if (checkerResult == null) { return null; } if (checkerResult.data && has(checkerResult.data, 'expectedType')) { expectedTypes.push(checkerResult.data.expectedType); } } var expectedTypesMessage = expectedTypes.length > 0 ? ', expected one of type [' + expectedTypes.join(', ') + ']' : ''; return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`' + expectedTypesMessage + '.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function invalidValidatorError(componentName, location, propFullName, key, type) { return new PropTypeError((componentName || 'React class') + ': ' + location + ' type `' + propFullName + '.' + key + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + type + '`.'); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (typeof checker !== 'function') { return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker)); } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret$1); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createStrictShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } // We need to check all keys in case some are required but missing from props. var allKeys = assign({}, props[propName], shapeTypes); for (var key in allKeys) { var checker = shapeTypes[key]; if (has(shapeTypes, key) && typeof checker !== 'function') { return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker)); } if (!checker) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + '\nBad object: ' + JSON.stringify(props[propName], null, ' ') + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')); } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret$1); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (_typeof(propValue)) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // falsy value can't be a Symbol if (!propValue) { return false; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = _typeof(propValue); if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === 'undefined' || propValue === null) { return '' + propValue; } var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { var type = getPreciseType(value); switch (type) { case 'array': case 'object': return 'an ' + type; case 'boolean': case 'date': case 'regexp': return 'a ' + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret = ReactPropTypesSecret_1; function emptyFunction() {} function emptyFunctionWithReset() {} emptyFunctionWithReset.resetWarningCache = emptyFunction; var factoryWithThrowingShims = function factoryWithThrowingShims() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret) { // It is still safe when called from React. return; } var err = new Error('Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types'); err.name = 'Invariant Violation'; throw err; } shim.isRequired = shim; function getShim() { return shim; } // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bigint: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, elementType: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim, checkPropTypes: emptyFunctionWithReset, resetWarningCache: emptyFunction }; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (process.env.NODE_ENV !== 'production') { var ReactIs = require$$0; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; propTypes.exports = factoryWithTypeCheckers(ReactIs.isElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod propTypes.exports = factoryWithThrowingShims(); } var PropTypes = propTypes.exports; var _excluded = ["children", "ellipsis", "lines"]; function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } var Truncate = /*#__PURE__*/function (_React$Component) { function Truncate(props) { var _this; _classCallCheck(this, Truncate); _this = _callSuper(this, Truncate, [props]); _defineProperty(_this, "state", {}); _defineProperty(_this, "extractReplaceLinksKeys", function (content) { var i = 0; _this.replacedLinks = []; content.replace(/(<a[\s]+([^>]+)>((?:.(?!<\/a>))*.)<\/a>)/g, function () { for (var _len = arguments.length, rest = new Array(_len), _key = 0; _key < _len; _key++) { rest[_key] = arguments[_key]; } var item = Array.prototype.slice.call(rest, 1, 4); item.key = "[".concat("@".repeat(item[2].length - 1), "=").concat(i + 1, "]"); _this.replacedLinks.push(item); content = content.replace(item[0], item.key); }); return content; }); _defineProperty(_this, "restoreReplacedLinks", function (content) { _this.replacedLinks.forEach(function (item) { content = content.replace(item.key, item[0]); }); return _this.createMarkup(content); }); _defineProperty(_this, "innerText", function (node) { var div = document.createElement("div"); var contentKey = "innerText" in window.HTMLElement.prototype ? "innerText" : "textContent"; var content = node.innerHTML.replace(/\r\n|\r|\n/g, " "); div.innerHTML = _this.extractReplaceLinksKeys(content); var text = div[contentKey]; var test = document.createElement("div"); test.innerHTML = "foo<br/>bar"; if (test[contentKey].replace(/\r\n|\r/g, "\n") !== "foo\nbar") { div.innerHTML = div.innerHTML.replace(/<br.*?[/]?>/gi, "\n"); text = div[contentKey]; } return text; }); _defineProperty(_this, "onResize", function () { _this.calcTargetWidth(); }); _defineProperty(_this, "onTruncate", function (didTruncate) { var onTruncate = _this.props.onTruncate; if (typeof onTruncate === "function") { _this.timeout = window.requestAnimationFrame(function () { onTruncate(didTruncate); }); } }); _defineProperty(_this, "calcTargetWidth", function (callback) { var _this2 = _this, target = _this2.elements.target, calcTargetWidth = _this2.calcTargetWidth, canvasContext = _this2.canvasContext, width = _this2.props.width; if (!target) { return; } var targetWidth = width || Math.floor(target.parentElement.getBoundingClientRect().width); if (!targetWidth) { return window.requestAnimationFrame(function () { return calcTargetWidth(callback); }); } var style = window.getComputedStyle(target); var font = [style["font-weight"], style["font-style"], style["font-size"], style["font-family"]].join(" "); canvasContext.font = font; _this.setState({ targetWidth: targetWidth }, callback); }); _defineProperty(_this, "measureWidth", function (text) { return _this.canvasContext.measureText(text).width; }); _defineProperty(_this, "ellipsisWidth", function (node) { _this.calculatedEllipsisWidth = true; return node.offsetWidth; }); _defineProperty(_this, "trimRight", function (text) { return text.replace(/\s+$/, ""); }); _defineProperty(_this, "createMarkup", function (str) { return /* @__PURE__ */React.createElement("span", { className: _this.props.lineClassName, dangerouslySetInnerHTML: { __html: str } }); }); _defineProperty(_this, "getLines", function () { var _this3 = _this, elements = _this3.elements, _this3$props = _this3.props, numLines = _this3$props.lines, ellipsis = _this3$props.ellipsis, trimWhitespace = _this3$props.trimWhitespace, lineClassName = _this3$props.lineClassName, targetWidth = _this3.state.targetWidth, innerText = _this3.innerText, measureWidth = _this3.measureWidth, onTruncate = _this3.onTruncate, trimRight = _this3.trimRight, renderLine = _this3.renderLine, restoreReplacedLinks = _this3.restoreReplacedLinks; var lines = []; var text = innerText(elements.text); var textLines = text.split("\n").map(function (line) { return line.split(""); }); var didTruncate = true; var ellipsisWidth = _this.ellipsisWidth(_this.elements.ellipsis); for (var line = 1; line <= numLines; line++) { var textWords = textLines[0]; if (textWords.length === 0) { lines.push(); textLines.shift(); line -= 1; continue; } var resultLine = textWords.join(""); if (measureWidth(resultLine) <= targetWidth) { if (textLines.length === 1) { didTruncate = false; resultLine = restoreReplacedLinks(resultLine); lines.push(resultLine); break; } } if (line === numLines) { var textRest = textWords.join(""); var lower = 0; var upper = textRest.length - 1; while (lower <= upper) { var middle = Math.floor((lower + upper) / 2); var testLine = textRest.slice(0, middle + 1); if (measureWidth(testLine) + ellipsisWidth <= targetWidth) { lower = middle + 1; } else { upper = middle - 1; } } var lastLineText = textRest.slice(0, lower); if (trimWhitespace) { lastLineText = trimRight(lastLineText); while (!lastLineText.length && lines.length) { var prevLine = lines.pop(); lastLineText = trimRight(prevLine); } } if (lastLineText.substr(lastLineText.length - 2) === "][") { lastLineText = lastLineText.substring(0, lastLineText.length - 1); } lastLineText = lastLineText.replace(/\[@+$/, ""); lastLineText = restoreReplacedLinks(lastLineText); resultLine = /* @__PURE__ */React.createElement("span", { className: "".concat(lineClassName, "-with-symbol") }, lastLineText, ellipsis); } else { var _lower = 0; var _upper = textWords.length - 1; while (_lower <= _upper) { var _middle = Math.floor((_lower + _upper) / 2); var _testLine = textWords.slice(0, _middle + 1).join(""); if (measureWidth(_testLine) <= targetWidth) { _lower = _middle + 1; } else { _upper = _middle - 1; } } if (_lower === 0) { line = numLines - 1; continue; } resultLine = textWords.slice(0, _lower).join(""); resultLine = restoreReplacedLinks(resultLine); textLines[0].splice(0, _lower); } lines.push(resultLine); } onTruncate(didTruncate); return lines.map(renderLine); }); _defineProperty(_this, "renderLine", function (line, i, arr) { var lineClassName = _this.props.lineClassName; if (i === arr.length - 1) { return /* @__PURE__ */React.createElement("span", { className: "".concat(lineClassName, "-wrapper"), key: i }, line); } var br = /* @__PURE__ */React.createElement("br", { key: "".concat(i, "br") }); if (line) { return [/* @__PURE__ */React.createElement("span", { className: "".concat(lineClassName, "-wrapper"), key: i }, line), br]; } return br; }); _this.elements = {}; _this.replacedLinks = []; _this.calculatedEllipsisWidth = false; _this.canvasContext; return _this; } _inherits(Truncate, _React$Component); return _createClass(Truncate, [{ key: "componentDidMount", value: function componentDidMount() { var text = this.elements.text, calcTargetWidth = this.calcTargetWidth, onResize = this.onResize; var canvas = document.createElement("canvas"); this.canvasContext = canvas.getContext("2d"); calcTargetWidth(function () { if (text && text.parentNode) { text.parentNode.removeChild(text); } }); window.addEventListener("resize", onResize); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (this.props.children !== prevProps.children) { this.forceUpdate(); } if (this.props.width !== prevProps.width) { this.calcTargetWidth(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { var ellipsis = this.elements.ellipsis, onResize = this.onResize, timeout = this.timeout; if (ellipsis.parentNode && this.calculatedEllipsisWidth) { ellipsis.parentNode.removeChild(ellipsis); } window.removeEventListener("resize", onResize); window.cancelAnimationFrame(timeout); } }, { key: "render", value: function render() { var _this4 = this; var target = this.elements.target, _this$props = this.props, children = _this$props.children, ellipsis = _this$props.ellipsis, lines = _this$props.lines, spanProps = _objectWithoutProperties(_this$props, _excluded), targetWidth = this.state.targetWidth, getLines = this.getLines, onTruncate = this.onTruncate; var text; var mounted = !!(target && targetWidth); if (typeof window !== "undefined" && mounted) { if (lines > 0) { text = getLines(); } else { text = children; onTruncate(false); } } return /* @__PURE__ */React.createElement("span", _objectSpread(_objectSpread({}, omit(spanProps, ["onTruncate", "trimWhitespace", "lineClassName"])), {}, { ref: function ref(targetEl) { _this4.elements.target = targetEl; } }), /* @__PURE__ */React.createElement("span", { style: { display: "block", maxWidth: spanProps.width > 0 ? "".concat(spanProps.width, "px") : "unset" } }, text), /* @__PURE__ */React.createElement("span", { ref: function ref(textEl) { _this4.elements.text = textEl; } }, children), /* @__PURE__ */React.createElement("span", { ref: function ref(ellipsisEl) { _this4.elements.ellipsis = ellipsisEl; }, style: { position: "fixed", visibility: "hidden", top: 0, left: 0 } }, ellipsis)); } }]); }(React.Component); _defineProperty(Truncate, "propTypes", { children: PropTypes.node, ellipsis: PropTypes.node, lines: PropTypes.oneOfType([PropTypes.oneOf([false]), PropTypes.number]), trimWhitespace: PropTypes.bool, width: PropTypes.number, onTruncate: PropTypes.func, className: PropTypes.string, lineClassName: PropTypes.string }); _defineProperty(Truncate, "defaultProps", { children: "", ellipsis: "...", lines: 1, trimWhitespace: false, width: 0, lineClassName: "truncate-line" }); export { Truncate as default }; //# sourceMappingURL=Truncate.js.map