# All files / mixins retinaImage.js

100% Statements 5/5
100% Branches 6/6
100% Functions 1/1
100% Lines 5/5

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51

    7x
    1x

    6x
    6x

    6x

     // @flow

    import hiDPI from './hiDPI'

    /**
     * The retina-image mixin is a helper to generate a retina background image and non-retina
     * background image. The retina background image will output to a HiDPI media query. The mixin uses
     * a _2x.png filename suffix by default.
     *
     * @example
     * // Styles as object usage
     * const styles = {
     *  ...retinaImage('my-img')
     * }
     *
     * // styled-components usage
     * const div = styled.div`
     *   ${retinaImage('my-img')}
     * `
     *
     * // CSS as JS Output
     * div {
     *   backgroundImage: 'url(my-img.png)',
     *   '@media only screen and (-webkit-min-device-pixel-ratio: 1.3),
     *    only screen and (min--moz-device-pixel-ratio: 1.3),
     *    only screen and (-o-min-device-pixel-ratio: 1.3/1),
     *    only screen and (min-resolution: 144dpi),
     *    only screen and (min-resolution: 1.5dppx)': {
     *     backgroundImage: 'url(my-img_2x.png)',
     *   }
     * }
     */
    function retinaImage(filename: string, backgroundSize?: string, extension?: string = 'png', retinaFilename?: string, retinaSuffix?: string = '_2x') {
      if (!filename) {
        throw new Error('Please supply a filename to retinaImage() as the first argument.')
      }
      // Replace the dot at the beginning of the passed extension if one exists
      const ext = extension.replace(/^\./, '')
      const rFilename = retinaFilename ? `${retinaFilename}.${ext}` : `${filename}${retinaSuffix}.${ext}`

      return {
        backgroundImage: `url(${filename}.${ext})`,
        [hiDPI()]: {
          backgroundImage: `url(${rFilename})`,
          backgroundSize,
        },
      }
    }

    export default retinaImage