contrastReverse.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ContrastReverse = void 0;
  4. const d3_array_1 = require("d3-array");
  5. const color_1 = require("../utils/color");
  6. function getsRGB(s) {
  7. let c = s / 255;
  8. c = c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
  9. return c;
  10. }
  11. function getL(r, g, b) {
  12. return 0.2126 * getsRGB(r) + 0.7152 * getsRGB(g) + 0.0722 * getsRGB(b);
  13. }
  14. /**
  15. * Calculate the contrast. see https://webaim.org/resources/contrastchecker/
  16. * @param foreground
  17. * @param background
  18. */
  19. function contrast(foreground, background) {
  20. const { r, g, b } = foreground;
  21. const { r: rb, g: gb, b: bb } = background;
  22. const L1 = getL(r, g, b);
  23. const L2 = getL(rb, gb, bb);
  24. return (Math.max(L1, L2) + 0.05) / (Math.min(L1, L2) + 0.05);
  25. }
  26. /**
  27. * Reverse color for max contrast.
  28. */
  29. function mostContrast(color, palette) {
  30. const i = (0, d3_array_1.maxIndex)(palette, (c) => contrast(color, (0, color_1.parseToRGB)(c)));
  31. return palette[i];
  32. }
  33. /**
  34. * Reverse the label color when the contrast is lower then `threshold`.
  35. * The default value of `threshold` is 4.5.
  36. * More about contract, see https://webaim.org/resources/contrastchecker/
  37. */
  38. const ContrastReverse = (options) => {
  39. const { threshold = 4.5, palette = ['#000', '#fff'] } = options;
  40. return (labels, coordinate) => {
  41. labels.forEach((l) => {
  42. const background = l.attr('dependentElement').parsedStyle.fill;
  43. const foreground = l.parsedStyle.fill;
  44. const c = contrast(foreground, background);
  45. if (c < threshold)
  46. l.attr('fill', mostContrast(background, palette));
  47. });
  48. return labels;
  49. };
  50. };
  51. exports.ContrastReverse = ContrastReverse;
  52. //# sourceMappingURL=contrastReverse.js.map