# All files / color opacify.js

100% Statements 4/4
100% Branches 2/2
100% Functions 1/1
100% Lines 4/4

    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

    8x
    7x
    7x

    7x

     // @flow
    import rgba from './rgba'
    import parseToRgb from './parseToRgb'
    import guard from '../internalHelpers/_guard'
    import curry from '../internalHelpers/_curry'

    /**
     * Increases the opacity of a color. Its range for the amount is between 0 to 1.
     *
     *
     * @example
     * // Styles as object usage
     * const styles = {
     *   background: opacify(0.1, 'rgba(255, 255, 255, 0.9)');
     *   background: opacify(0.2, 'hsla(0, 0%, 100%, 0.5)'),
     *   background: opacify(0.5, 'rgba(255, 0, 0, 0.2)'),
     * }
     *
     * // styled-components usage
     * const div = styled.div`
     *   background: ${opacify(0.1, 'rgba(255, 255, 255, 0.9)')};
     *   background: ${opacify(0.2, 'hsla(0, 0%, 100%, 0.5)')},
     *   background: ${opacify(0.5, 'rgba(255, 0, 0, 0.2)')},
     * `
     *
     * // CSS in JS Output
     *
     * element {
     *   background: "#fff";
     *   background: "rgba(255,255,255,0.7)";
     *   background: "rgba(255,0,0,0.7)";
     * }
     */
    function opacify(amount: number, color: string) {
      const parsedColor = parseToRgb(color)
      const alpha: number = typeof parsedColor.alpha === 'number' ? parsedColor.alpha : 1
      const colorWithAlpha = {
        ...parsedColor,
        alpha: guard(0, 1, (alpha + amount)),
      }
      return rgba(colorWithAlpha)
    }

    export default curry(opacify)