colorDiff.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. var debug = require('debug')('ylt:colorDiff');
  2. var diff = require('color-diff');
  3. var parse = require('parse-color');
  4. var colorDiff = function() {
  5. var COLOR_DIFF_THRESHOLD = 0.9;
  6. this.compareAllColors = function(data) {
  7. debug('Starting to compare all colors...');
  8. var offenders = data.toolsResults.phantomas.offenders.cssColors;
  9. var colors = (offenders) ? this.parseAllColors(offenders) : [];
  10. var result = [];
  11. // Compare colors to each other
  12. for (var i = 0; i < colors.length - 1 ; i++) {
  13. for (var j = i + 1; j < colors.length; j++) {
  14. debug('Comparing color %s with color %s', colors[i].original, colors[j].original);
  15. if (this.compareTwoColors(colors[i], colors[j])) {
  16. debug('Colors are similar!');
  17. result.push({
  18. color1: colors[i].original,
  19. color2: colors[j].original,
  20. isDark: (colors[i].Lab.L < 60)
  21. });
  22. }
  23. }
  24. }
  25. data.toolsResults.colorDiff = {
  26. metrics: {
  27. similarColors: result.length
  28. },
  29. offenders: {
  30. similarColors: result
  31. }
  32. };
  33. return data;
  34. };
  35. this.parseAllColors = function(offenders) {
  36. var parsedOffenders = offenders.map(this.parseOffender);
  37. var deduplicatedColors = {};
  38. parsedOffenders.forEach(function(color) {
  39. deduplicatedColors[color] = color;
  40. });
  41. return Object.keys(deduplicatedColors).map(this.parseColor);
  42. };
  43. this.parseOffender = function(offender) {
  44. var regexResult = /^(.*) \(\d+ times\)$/.exec(offender);
  45. return regexResult[1];
  46. };
  47. this.parseColor = function(color) {
  48. var colorArray = parse(color).rgba;
  49. var obj = {
  50. R: colorArray[0],
  51. G: colorArray[1],
  52. B: colorArray[2],
  53. A: colorArray[3]
  54. };
  55. obj.Lab = diff.rgb_to_lab(obj);
  56. obj.original = color;
  57. return obj;
  58. };
  59. this.compareTwoColors = function(color1, color2) {
  60. if (color1.A !== color2.A) {
  61. debug('Comparison not possible, because the alpha channel is different');
  62. return false;
  63. }
  64. var delta = diff.diff(color1.Lab, color2.Lab);
  65. debug('Delta is %d', delta);
  66. return delta <= COLOR_DIFF_THRESHOLD;
  67. };
  68. };
  69. module.exports = new colorDiff();