linearGradient.js.flow 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // @flow
  2. import constructGradientValue from '../internalHelpers/_constructGradientValue'
  3. import PolishedError from '../internalHelpers/_errors'
  4. import type { LinearGradientConfiguration } from '../types/linearGradientConfiguration'
  5. import type { Styles } from '../types/style'
  6. /**
  7. * CSS for declaring a linear gradient, including a fallback background-color. The fallback is either the first color-stop or an explicitly passed fallback color.
  8. *
  9. * @example
  10. * // Styles as object usage
  11. * const styles = {
  12. * ...linearGradient({
  13. colorStops: ['#00FFFF 0%', 'rgba(0, 0, 255, 0) 50%', '#0000FF 95%'],
  14. toDirection: 'to top right',
  15. fallback: '#FFF',
  16. })
  17. * }
  18. *
  19. * // styled-components usage
  20. * const div = styled.div`
  21. * ${linearGradient({
  22. colorStops: ['#00FFFF 0%', 'rgba(0, 0, 255, 0) 50%', '#0000FF 95%'],
  23. toDirection: 'to top right',
  24. fallback: '#FFF',
  25. })}
  26. *`
  27. *
  28. * // CSS as JS Output
  29. *
  30. * div: {
  31. * 'backgroundColor': '#FFF',
  32. * 'backgroundImage': 'linear-gradient(to top right, #00FFFF 0%, rgba(0, 0, 255, 0) 50%, #0000FF 95%)',
  33. * }
  34. */
  35. export default function linearGradient({
  36. colorStops,
  37. fallback,
  38. toDirection = '',
  39. }: LinearGradientConfiguration): Styles {
  40. if (!colorStops || colorStops.length < 2) {
  41. throw new PolishedError(56)
  42. }
  43. return {
  44. backgroundColor:
  45. fallback
  46. || colorStops[0]
  47. .replace(/,\s+/g, ',')
  48. .split(' ')[0]
  49. .replace(/,(?=\S)/g, ', '),
  50. backgroundImage: constructGradientValue`linear-gradient(${toDirection}${colorStops
  51. .join(', ')
  52. .replace(/,(?=\S)/g, ', ')})`,
  53. }
  54. }