colours.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _color = require('color');
  6. var _color2 = _interopRequireDefault(_color);
  7. var _keywords = require('./keywords.json');
  8. var _keywords2 = _interopRequireDefault(_keywords);
  9. var _toShorthand = require('./lib/toShorthand');
  10. var _toShorthand2 = _interopRequireDefault(_toShorthand);
  11. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12. const shorter = (a, b) => (a && a.length < b.length ? a : b).toLowerCase();
  13. exports.default = (colour, isLegacy = false, cache = false) => {
  14. const key = colour + "|" + isLegacy;
  15. if (cache && cache[key]) {
  16. return cache[key];
  17. }
  18. try {
  19. const parsed = (0, _color2.default)(colour.toLowerCase());
  20. const alpha = parsed.alpha();
  21. if (alpha === 1) {
  22. const toHex = (0, _toShorthand2.default)(parsed.hex().toLowerCase());
  23. const result = shorter(_keywords2.default[toHex], toHex);
  24. if (cache) {
  25. cache[key] = result;
  26. }
  27. return result;
  28. } else {
  29. const rgb = parsed.rgb();
  30. if (!isLegacy && !rgb.color[0] && !rgb.color[1] && !rgb.color[2] && !alpha) {
  31. const result = 'transparent';
  32. if (cache) {
  33. cache[key] = result;
  34. }
  35. return result;
  36. }
  37. let hsla = parsed.hsl().string();
  38. let rgba = rgb.string();
  39. let result = hsla.length < rgba.length ? hsla : rgba;
  40. if (cache) {
  41. cache[key] = result;
  42. }
  43. return result;
  44. }
  45. } catch (e) {
  46. // Possibly malformed, so pass through
  47. const result = colour;
  48. if (cache) {
  49. cache[key] = result;
  50. }
  51. return result;
  52. }
  53. };