UNPKG

polished

Version:

A lightweight toolset for writing styles in Javascript.

73 lines (61 loc) 2.32 kB
"use strict"; exports.__esModule = true; exports["default"] = readableColor; var _getContrast = /*#__PURE__*/_interopRequireDefault( /*#__PURE__*/require("./getContrast")); var _getLuminance = /*#__PURE__*/_interopRequireDefault( /*#__PURE__*/require("./getLuminance")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var defaultLightReturnColor = '#000'; var defaultDarkReturnColor = '#fff'; /** * Returns black or white (or optional light and dark return colors) for best * contrast depending on the luminosity of the given color. * When passing custom return colors, strict mode ensures that the * return color always meets or exceeds WCAG level AA or greater. If this test * fails, the default return color (black or white) is returned in place of the * custom return color. You can optionally turn off strict mode. * * Follows [W3C specs for readability](https://www.w3.org/TR/WCAG20-TECHS/G18.html). * * @example * // Styles as object usage * const styles = { * color: readableColor('#000'), * color: readableColor('black', '#001', '#ff8'), * color: readableColor('white', '#001', '#ff8'), * color: readableColor('red', '#333', '#ddd', true) * } * * // styled-components usage * const div = styled.div` * color: ${readableColor('#000')}; * color: ${readableColor('black', '#001', '#ff8')}; * color: ${readableColor('white', '#001', '#ff8')}; * color: ${readableColor('red', '#333', '#ddd', true)}; * ` * * // CSS in JS Output * element { * color: "#fff"; * color: "#ff8"; * color: "#001"; * color: "#000"; * } */ function readableColor(color, lightReturnColor, darkReturnColor, strict) { if (lightReturnColor === void 0) { lightReturnColor = defaultLightReturnColor; } if (darkReturnColor === void 0) { darkReturnColor = defaultDarkReturnColor; } if (strict === void 0) { strict = true; } var isLightColor = (0, _getLuminance["default"])(color) > 0.179; var preferredReturnColor = isLightColor ? lightReturnColor : darkReturnColor; if (!strict || (0, _getContrast["default"])(color, preferredReturnColor) >= 4.5) { return preferredReturnColor; } return isLightColor ? defaultLightReturnColor : defaultDarkReturnColor; } module.exports = exports.default;