polished
Version:
A lightweight toolset for writing styles in Javascript.
63 lines (61 loc) • 2.27 kB
JavaScript
exports.__esModule = true;
exports["default"] = readableColor;
var _getContrast = _interopRequireDefault(require("./getContrast"));
var _getLuminance = _interopRequireDefault(require("./getLuminance"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var defaultReturnIfLightColor = '#000';
var defaultReturnIfDarkColor = '#fff';
/**
* Returns black or white (or optional passed 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, returnIfLightColor, returnIfDarkColor, strict) {
if (returnIfLightColor === void 0) {
returnIfLightColor = defaultReturnIfLightColor;
}
if (returnIfDarkColor === void 0) {
returnIfDarkColor = defaultReturnIfDarkColor;
}
if (strict === void 0) {
strict = true;
}
var isColorLight = (0, _getLuminance["default"])(color) > 0.179;
var preferredReturnColor = isColorLight ? returnIfLightColor : returnIfDarkColor;
if (!strict || (0, _getContrast["default"])(color, preferredReturnColor) >= 4.5) {
return preferredReturnColor;
}
return isColorLight ? defaultReturnIfLightColor : defaultReturnIfDarkColor;
}
module.exports = exports.default;
;