component.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. var utils = require('../utils')
  2. , nodes = require('../nodes');
  3. /**
  4. * Color component name map.
  5. */
  6. var componentMap = {
  7. red: 'r'
  8. , green: 'g'
  9. , blue: 'b'
  10. , alpha: 'a'
  11. , hue: 'h'
  12. , saturation: 's'
  13. , lightness: 'l'
  14. };
  15. /**
  16. * Color component unit type map.
  17. */
  18. var unitMap = {
  19. hue: 'deg'
  20. , saturation: '%'
  21. , lightness: '%'
  22. };
  23. /**
  24. * Color type map.
  25. */
  26. var typeMap = {
  27. red: 'rgba'
  28. , blue: 'rgba'
  29. , green: 'rgba'
  30. , alpha: 'rgba'
  31. , hue: 'hsla'
  32. , saturation: 'hsla'
  33. , lightness: 'hsla'
  34. };
  35. /**
  36. * Return component `name` for the given `color`.
  37. *
  38. * @param {RGBA|HSLA} color
  39. * @param {String} name
  40. * @return {Unit}
  41. * @api public
  42. */
  43. function component(color, name) {
  44. utils.assertColor(color, 'color');
  45. utils.assertString(name, 'name');
  46. var name = name.string
  47. , unit = unitMap[name]
  48. , type = typeMap[name]
  49. , name = componentMap[name];
  50. if (!name) throw new Error('invalid color component "' + name + '"');
  51. return new nodes.Unit(color[type][name], unit);
  52. };
  53. component.params = ['color', 'name'];
  54. module.exports = component;