helpers.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* jshint esnext:true */
  2. var toggle = ( el, visibility ) => {
  3. 'use strict';
  4. if ( +visibility ) {
  5. el.show();
  6. } else {
  7. el.hide();
  8. }
  9. };
  10. function isNumeric(n) {
  11. return !isNaN(parseFloat(n)) && isFinite(n);
  12. }
  13. /**
  14. * Converts an RGB color value to HSL. Conversion formula
  15. * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
  16. * Assumes r, g, and b are contained in the set [0, 255] and
  17. * returns h, s, and l for use with the hsl() notation in CSS
  18. *
  19. * @param Number r The red color value
  20. * @param Number g The green color value
  21. * @param Number b The blue color value
  22. * @return Array The HSL representation
  23. */
  24. function rgbToHsl(r, g, b) {
  25. r /= 255, g /= 255, b /= 255;
  26. let max = Math.max(r, g, b), min = Math.min(r, g, b);
  27. let h, s, l = (max + min) / 2;
  28. if (max == min) {
  29. h = s = 0; // achromatic
  30. } else {
  31. let d = max - min;
  32. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  33. switch (max) {
  34. case r: h = (g - b) / d + (g < b ? 6 : 0); break;
  35. case g: h = (b - r) / d + 2; break;
  36. case b: h = (r - g) / d + 4; break;
  37. }
  38. h /= 6;
  39. }
  40. return [ h * 360, s*100, l*100 ];
  41. }
  42. function hexToRgb( hex ) {
  43. // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  44. let shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  45. hex = hex.replace(shorthandRegex, function(m, r, g, b) {
  46. return r + r + g + g + b + b;
  47. });
  48. let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  49. return result ? [
  50. parseInt(result[1], 16),
  51. parseInt(result[2], 16),
  52. parseInt(result[3], 16)
  53. ] : null;
  54. }
  55. function hexToHsl( hex ) {
  56. return rgbToHsl( ...hexToRgb( hex ) );
  57. }
  58. export { toggle, isNumeric, rgbToHsl, hexToRgb, hexToHsl };