From 8fa7b1a9a0ccb8d35ad9e76fcb0512a99e4aeac1 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 1e63b541dd..3915513327 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 3310653236..f6a9f262ad 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; + }, + `${otherPropName} ${Array.isArray(otherPropName) ? 'are defined' : 'is truthy'}`, ) );