retinaImage.js.flow 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // @flow
  2. import hiDPI from './hiDPI'
  3. import PolishedError from '../internalHelpers/_errors'
  4. import type { Styles } from '../types/style'
  5. /**
  6. * A helper to generate a retina background image and non-retina
  7. * background image. The retina background image will output to a HiDPI media query. The mixin uses
  8. * a _2x.png filename suffix by default.
  9. *
  10. * @example
  11. * // Styles as object usage
  12. * const styles = {
  13. * ...retinaImage('my-img')
  14. * }
  15. *
  16. * // styled-components usage
  17. * const div = styled.div`
  18. * ${retinaImage('my-img')}
  19. * `
  20. *
  21. * // CSS as JS Output
  22. * div {
  23. * backgroundImage: 'url(my-img.png)',
  24. * '@media only screen and (-webkit-min-device-pixel-ratio: 1.3),
  25. * only screen and (min--moz-device-pixel-ratio: 1.3),
  26. * only screen and (-o-min-device-pixel-ratio: 1.3/1),
  27. * only screen and (min-resolution: 144dpi),
  28. * only screen and (min-resolution: 1.5dppx)': {
  29. * backgroundImage: 'url(my-img_2x.png)',
  30. * }
  31. * }
  32. */
  33. export default function retinaImage(
  34. filename: string,
  35. backgroundSize?: string,
  36. extension?: string = 'png',
  37. retinaFilename?: string,
  38. retinaSuffix?: string = '_2x',
  39. ): Styles {
  40. if (!filename) {
  41. throw new PolishedError(58)
  42. }
  43. // Replace the dot at the beginning of the passed extension if one exists
  44. const ext = extension.replace(/^\./, '')
  45. const rFilename = retinaFilename
  46. ? `${retinaFilename}.${ext}`
  47. : `${filename}${retinaSuffix}.${ext}`
  48. return {
  49. backgroundImage: `url(${filename}.${ext})`,
  50. [hiDPI()]: {
  51. backgroundImage: `url(${rFilename})`,
  52. ...(backgroundSize ? { backgroundSize } : {}),
  53. },
  54. }
  55. }