hasProp.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import propName from './propName';
  2. const DEFAULT_OPTIONS = {
  3. spreadStrict: true,
  4. ignoreCase: true,
  5. };
  6. /**
  7. * Returns boolean indicating whether an prop exists on the props
  8. * property of a JSX element node.
  9. */
  10. export default function hasProp(props = [], prop = '', options = DEFAULT_OPTIONS) {
  11. const propToCheck = options.ignoreCase ? prop.toUpperCase() : prop;
  12. return props.some((attribute) => {
  13. // If the props contain a spread prop, then refer to strict param.
  14. if (attribute.type === 'JSXSpreadAttribute') {
  15. return !options.spreadStrict;
  16. }
  17. const currentProp = options.ignoreCase
  18. ? propName(attribute).toUpperCase()
  19. : propName(attribute);
  20. return propToCheck === currentProp;
  21. });
  22. }
  23. /**
  24. * Given the props on a node and a list of props to check, this returns a boolean
  25. * indicating if any of them exist on the node.
  26. */
  27. export function hasAnyProp(nodeProps = [], props = [], options = DEFAULT_OPTIONS) {
  28. const propsToCheck = typeof props === 'string' ? props.split(' ') : props;
  29. return propsToCheck.some((prop) => hasProp(nodeProps, prop, options));
  30. }
  31. /**
  32. * Given the props on a node and a list of props to check, this returns a boolean
  33. * indicating if all of them exist on the node
  34. */
  35. export function hasEveryProp(nodeProps = [], props = [], options = DEFAULT_OPTIONS) {
  36. const propsToCheck = typeof props === 'string' ? props.split(' ') : props;
  37. return propsToCheck.every((prop) => hasProp(nodeProps, prop, options));
  38. }