important.js.flow 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // @flow
  2. import type { Styles } from '../types/style'
  3. import PolishedError from '../internalHelpers/_errors'
  4. /**
  5. * Helper for targeting rules in a style block generated by polished modules that need !important-level specificity. Can optionally specify a rule (or rules) to target specific rules.
  6. *
  7. * @example
  8. * // Styles as object usage
  9. * const styles = {
  10. * ...important(cover())
  11. * }
  12. *
  13. * // styled-components usage
  14. * const div = styled.div`
  15. * ${important(cover())}
  16. * `
  17. *
  18. * // CSS as JS Output
  19. *
  20. * div: {
  21. * 'position': 'absolute !important',
  22. * 'top': '0 !important',
  23. * 'right: '0 !important',
  24. * 'bottom': '0 !important',
  25. * 'left: '0 !important'
  26. * }
  27. */
  28. export default function important(styleBlock: Styles, rules?: Array<string> | string): Styles {
  29. if (typeof styleBlock !== 'object' || styleBlock === null) {
  30. throw new PolishedError(75, typeof styleBlock)
  31. }
  32. const newStyleBlock = {}
  33. Object.keys(styleBlock).forEach(key => {
  34. if (typeof styleBlock[key] === 'object' && styleBlock[key] !== null) {
  35. newStyleBlock[key] = important(styleBlock[key], rules)
  36. } else if (!rules || (rules && (rules === key || rules.indexOf(key) >= 0))) {
  37. newStyleBlock[key] = `${styleBlock[key]} !important`
  38. } else {
  39. newStyleBlock[key] = styleBlock[key]
  40. }
  41. })
  42. return newStyleBlock
  43. }