UNPKG

polished

Version:

A lightweight toolset for writing styles in Javascript.

69 lines (66 loc) 2.95 kB
"use strict"; exports.__esModule = true; exports["default"] = void 0; var _curry = _interopRequireDefault(require("../internalHelpers/_curry")); var _rgba = _interopRequireDefault(require("./rgba")); var _parseToRgb = _interopRequireDefault(require("./parseToRgb")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } /** * Mixes the two provided colors together by calculating the average of each of the RGB components weighted to the first color by the provided weight. * * @example * // Styles as object usage * const styles = { * background: mix(0.5, '#f00', '#00f') * background: mix(0.25, '#f00', '#00f') * background: mix('0.5', 'rgba(255, 0, 0, 0.5)', '#00f') * } * * // styled-components usage * const div = styled.div` * background: ${mix(0.5, '#f00', '#00f')}; * background: ${mix(0.25, '#f00', '#00f')}; * background: ${mix('0.5', 'rgba(255, 0, 0, 0.5)', '#00f')}; * ` * * // CSS in JS Output * * element { * background: "#7f007f"; * background: "#3f00bf"; * background: "rgba(63, 0, 191, 0.75)"; * } */ function mix(weight, color, otherColor) { if (color === 'transparent') return otherColor; if (otherColor === 'transparent') return color; if (weight === 0) return otherColor; var parsedColor1 = (0, _parseToRgb["default"])(color); var color1 = _extends({}, parsedColor1, { alpha: typeof parsedColor1.alpha === 'number' ? parsedColor1.alpha : 1 }); var parsedColor2 = (0, _parseToRgb["default"])(otherColor); var color2 = _extends({}, parsedColor2, { alpha: typeof parsedColor2.alpha === 'number' ? parsedColor2.alpha : 1 }); // The formula is copied from the original Sass implementation: // http://sass-lang.com/documentation/Sass/Script/Functions.html#mix-instance_method var alphaDelta = color1.alpha - color2.alpha; var x = parseFloat(weight) * 2 - 1; var y = x * alphaDelta === -1 ? x : x + alphaDelta; var z = 1 + x * alphaDelta; var weight1 = (y / z + 1) / 2.0; var weight2 = 1 - weight1; var mixedColor = { red: Math.floor(color1.red * weight1 + color2.red * weight2), green: Math.floor(color1.green * weight1 + color2.green * weight2), blue: Math.floor(color1.blue * weight1 + color2.blue * weight2), alpha: color1.alpha * parseFloat(weight) + color2.alpha * (1 - parseFloat(weight)) }; return (0, _rgba["default"])(mixedColor); } // prettier-ignore var curriedMix = (0, _curry["default"] /* ::<number | string, string, string, string> */)(mix); var _default = exports["default"] = curriedMix; module.exports = exports.default;