color-parser.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict';
  2. // eslint-disable-next-line no-var
  3. var colorParser = (() => {
  4. const el = document.createElement('div');
  5. // https://bugs.webkit.org/show_bug.cgi?id=14563
  6. document.head.appendChild(el);
  7. function parseRGB(color) {
  8. const [r, g, b, a = 1] = color.match(/[.\d]+/g).map(Number);
  9. return {r, g, b, a};
  10. }
  11. function parse(color) {
  12. el.style.color = color;
  13. if (el.style.color === '') {
  14. throw new Error(chrome.i18n.getMessage('styleMetaErrorColor', color));
  15. }
  16. color = getComputedStyle(el).color;
  17. el.style.color = '';
  18. return parseRGB(color);
  19. }
  20. function format({r, g, b, a = 1}) {
  21. if (a === 1) {
  22. return `rgb(${r}, ${g}, ${b})`;
  23. }
  24. return `rgba(${r}, ${g}, ${b}, ${a})`;
  25. }
  26. function formatHex({r, g, b, a = null}) {
  27. let hex = '#' + (0x1000000 + (r << 16) + (g << 8) + (b | 0)).toString(16).substr(1);
  28. if (a !== null) {
  29. hex += (0x100 + Math.floor(a * 255)).toString(16).substr(1);
  30. }
  31. return hex;
  32. }
  33. return {parse, format, formatHex};
  34. })();