UNPKG

polished

Version:

A lightweight toolset for writing styles in Javascript.

45 lines (44 loc) 1.7 kB
"use strict"; exports.__esModule = true; exports["default"] = getLuminance; var _parseToRgb = _interopRequireDefault(require("./parseToRgb")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /** * Returns a number (float) representing the luminance of a color. * * @example * // Styles as object usage * const styles = { * background: getLuminance('#CCCD64') >= getLuminance('#0000ff') ? '#CCCD64' : '#0000ff', * background: getLuminance('rgba(58, 133, 255, 1)') >= getLuminance('rgba(255, 57, 149, 1)') ? * 'rgba(58, 133, 255, 1)' : * 'rgba(255, 57, 149, 1)', * } * * // styled-components usage * const div = styled.div` * background: ${getLuminance('#CCCD64') >= getLuminance('#0000ff') ? '#CCCD64' : '#0000ff'}; * background: ${getLuminance('rgba(58, 133, 255, 1)') >= getLuminance('rgba(255, 57, 149, 1)') ? * 'rgba(58, 133, 255, 1)' : * 'rgba(255, 57, 149, 1)'}; * * // CSS in JS Output * * div { * background: "#CCCD64"; * background: "rgba(58, 133, 255, 1)"; * } */ function getLuminance(color) { if (color === 'transparent') return 0; var rgbColor = (0, _parseToRgb["default"])(color); var _Object$keys$map = Object.keys(rgbColor).map(function (key) { var channel = rgbColor[key] / 255; return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4); }), r = _Object$keys$map[0], g = _Object$keys$map[1], b = _Object$keys$map[2]; return parseFloat((0.2126 * r + 0.7152 * g + 0.0722 * b).toFixed(3)); } module.exports = exports.default;