UNPKG

2.27 kBJavaScriptView Raw
1"use strict";
2
3exports.__esModule = true;
4exports["default"] = readableColor;
5var _getContrast = _interopRequireDefault(require("./getContrast"));
6var _getLuminance = _interopRequireDefault(require("./getLuminance"));
7function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
8var defaultReturnIfLightColor = '#000';
9var defaultReturnIfDarkColor = '#fff';
10
11/**
12 * Returns black or white (or optional passed colors) for best
13 * contrast depending on the luminosity of the given color.
14 * When passing custom return colors, strict mode ensures that the
15 * return color always meets or exceeds WCAG level AA or greater. If this test
16 * fails, the default return color (black or white) is returned in place of the
17 * custom return color. You can optionally turn off strict mode.
18 *
19 * Follows [W3C specs for readability](https://www.w3.org/TR/WCAG20-TECHS/G18.html).
20 *
21 * @example
22 * // Styles as object usage
23 * const styles = {
24 * color: readableColor('#000'),
25 * color: readableColor('black', '#001', '#ff8'),
26 * color: readableColor('white', '#001', '#ff8'),
27 * color: readableColor('red', '#333', '#ddd', true)
28 * }
29 *
30 * // styled-components usage
31 * const div = styled.div`
32 * color: ${readableColor('#000')};
33 * color: ${readableColor('black', '#001', '#ff8')};
34 * color: ${readableColor('white', '#001', '#ff8')};
35 * color: ${readableColor('red', '#333', '#ddd', true)};
36 * `
37 *
38 * // CSS in JS Output
39 * element {
40 * color: "#fff";
41 * color: "#ff8";
42 * color: "#001";
43 * color: "#000";
44 * }
45 */
46function readableColor(color, returnIfLightColor, returnIfDarkColor, strict) {
47 if (returnIfLightColor === void 0) {
48 returnIfLightColor = defaultReturnIfLightColor;
49 }
50 if (returnIfDarkColor === void 0) {
51 returnIfDarkColor = defaultReturnIfDarkColor;
52 }
53 if (strict === void 0) {
54 strict = true;
55 }
56 var isColorLight = (0, _getLuminance["default"])(color) > 0.179;
57 var preferredReturnColor = isColorLight ? returnIfLightColor : returnIfDarkColor;
58 if (!strict || (0, _getContrast["default"])(color, preferredReturnColor) >= 4.5) {
59 return preferredReturnColor;
60 }
61 return isColorLight ? defaultReturnIfLightColor : defaultReturnIfDarkColor;
62}
63module.exports = exports.default;
\No newline at end of file