From da74e3da320a333edadb3c8f1ee3550c687926a2 Mon Sep 17 00:00:00 2001 From: PKulkoRaccoonGang Date: Thu, 9 Nov 2023 15:19:49 +0200 Subject: [PATCH] refactor: added array support for requiredWhen --- src/Chip/README.md | 2 +- src/utils/propTypes/utils.js | 19 +++++++++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/Chip/README.md b/src/Chip/README.md index 1e63b541dd6..39155133272 100644 --- a/src/Chip/README.md +++ b/src/Chip/README.md @@ -42,7 +42,7 @@ Use `onClick` prop to make the whole `Chip` clickable, this will also add approp ## With Icon Before and After ### Basic Usage -Use `iconBefore` and `iconAfter` props to provide icons for the `Chip`, note that you also have to provide +Use `iconBefore` and `iconAfter` props to provide icons for the `Chip`, note that you also can provide accessible names for these icons for screen reader support via `iconBeforeAlt` and `iconAfterAlt` respectively. ```jsx live diff --git a/src/utils/propTypes/utils.js b/src/utils/propTypes/utils.js index 33106532362..3624b25ec5b 100644 --- a/src/utils/propTypes/utils.js +++ b/src/utils/propTypes/utils.js @@ -22,6 +22,16 @@ export const customPropTypeRequirement = (targetType, conditionFn, filterString) } ); +/** + * Checks if all specified properties are defined in the `props` object. + * + * @param {Object} props - The object in which the properties are checked. + * @param {string[]} otherPropNames - An array of strings representing the property names to be checked. + * @returns {boolean} `true` if all properties are defined and not equal to `undefined`, `false` otherwise. + */ +export const isEveryPropDefined = (props, otherPropNames) => otherPropNames + .every(propName => props[propName] !== undefined); + /** * Returns a PropType entry with the given propType that is required if otherPropName * is truthy. @@ -34,8 +44,13 @@ export const customPropTypeRequirement = (targetType, conditionFn, filterString) export const requiredWhen = (propType, otherPropName) => ( customPropTypeRequirement( propType, - (props) => props[otherPropName] === true, - `${otherPropName} is truthy`, + (props) => { + if (Array.isArray(otherPropName)) { + return isEveryPropDefined(props, otherPropName); + } + return props[otherPropName] === true; + }, + Array.isArray(otherPropName) ? `${otherPropName} are defined` : `${otherPropName} is truthy`, ) );