|
| 1 | +type Props = { |
| 2 | + qa?: string; |
| 3 | + qaVal?: string; |
| 4 | + 'data-qa'?: string; |
| 5 | + 'data-qa-val'?: string; |
| 6 | +}; |
| 7 | + |
| 8 | +/** |
| 9 | + * Processes QA props. |
| 10 | + * If `qa` or `qaVal` props are present, they are not modified and have higher priority. |
| 11 | + * Otherwise, maps `data-qa` to `qa` and `data-qa-val` to `qaVal`. |
| 12 | + * Data attributes are always removed. |
| 13 | + * Modifies the original props object without copying it. |
| 14 | + * Accepts only non-falsy values, otherwise deletes both props. |
| 15 | + * |
| 16 | + * @param props - The object to process |
| 17 | + * @returns The modified object |
| 18 | + */ |
| 19 | +export function useQaProps<T extends Props>(props: T): T { |
| 20 | + // Helper function to process qa attributes |
| 21 | + const processQaAttribute = (propName: string, dataAttrName: string) => { |
| 22 | + if (props[propName] !== undefined || props[dataAttrName] !== undefined) { |
| 23 | + const propValue = props[propName]; |
| 24 | + const dataAttrValue = props[dataAttrName]; |
| 25 | + |
| 26 | + if (!propValue) { |
| 27 | + if (dataAttrValue) { |
| 28 | + // If prop is empty but data-attr is truthy, map data-attr to prop |
| 29 | + props[propName] = dataAttrValue; |
| 30 | + } else { |
| 31 | + // Both values are falsy, delete both |
| 32 | + delete props[propName]; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + delete props[dataAttrName]; |
| 37 | + } |
| 38 | + }; |
| 39 | + |
| 40 | + // Process qa attributes |
| 41 | + processQaAttribute('qa', 'data-qa'); |
| 42 | + processQaAttribute('qaVal', 'data-qa-val'); |
| 43 | + |
| 44 | + return props; |
| 45 | +} |
0 commit comments