colorDiff.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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.7;
  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. if (color !== null) {
  40. deduplicatedColors[color] = color;
  41. }
  42. });
  43. return Object.keys(deduplicatedColors).map(this.parseColor);
  44. };
  45. this.parseOffender = function(offender) {
  46. var regexResult = /^(.*) \(\d+ times\)$/.exec(offender.value.message);
  47. return regexResult ? regexResult[1] : null;
  48. };
  49. this.parseColor = function(color) {
  50. var colorArray = parse(color).rgba;
  51. var obj = {
  52. R: colorArray[0],
  53. G: colorArray[1],
  54. B: colorArray[2],
  55. A: colorArray[3]
  56. };
  57. obj.Lab = diff.rgb_to_lab(obj);
  58. obj.original = color;
  59. return obj;
  60. };
  61. this.compareTwoColors = function(color1, color2) {
  62. if (color1.A !== color2.A) {
  63. debug('Comparison not possible, because the alpha channel is different');
  64. return false;
  65. }
  66. var delta = diff.diff(color1.Lab, color2.Lab);
  67. debug('Delta is %d', delta);
  68. return delta <= COLOR_DIFF_THRESHOLD;
  69. };
  70. };
  71. module.exports = new colorDiff();