svgCssUtil.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * Module containing CSS helper functions to work with svg.
  3. *
  4. * Note: dojo/dom-class does not work with svg elements, because in SVG,
  5. * className is defined as type SVGAnimatedString -> use getAttribute instead of className
  6. * @see https://bugs.dojotoolkit.org/ticket/16309
  7. * @module dgraph/svgCssUtil
  8. */
  9. export let svgCssUtil = {
  10. /**
  11. * Add a class name to the class attribute.
  12. * @param {HTMLElement|SVGElement} element
  13. * @param {String} className
  14. * @param {Boolean} [overwrite] adds by default
  15. */
  16. add: function(element, className, overwrite) {
  17. let cls = element.getAttribute('class');
  18. if (!overwrite) {
  19. className = (cls ? cls + ' ': '') + className;
  20. }
  21. element.setAttribute('class', className);
  22. },
  23. /**
  24. * Returns the class attribute
  25. * @param {HTMLElement|SVGElement} element
  26. * @return {string}
  27. */
  28. getClass: function(element) {
  29. return element.getAttribute('class');
  30. },
  31. /**
  32. * Remove a class name from class attribute
  33. * @param {HTMLElement|SVGElement} element
  34. * @param className
  35. */
  36. remove: function(element, className) {
  37. let arrClasses = element.hasAttribute('class') ? this.getClass(element).split(' '): [],
  38. newClasses = [],
  39. i, len;
  40. len = arrClasses.length;
  41. for (i = 0; i < len; i++) {
  42. if (className !== arrClasses[i]) {
  43. newClasses.push(arrClasses[i]);
  44. }
  45. }
  46. this.add(element, newClasses.join(' '), true);
  47. },
  48. /**
  49. * Checks element for given class.
  50. * ClassName can be an array to check for multiple classes.
  51. * @param {HTMLElement|SVGElement} element
  52. * @param {Array|String} className
  53. */
  54. has: function(element, className) {
  55. let elClasses = element.hasAttribute('class') ? this.getClass(element).split(' '): [],
  56. arrClasses = className,
  57. chkInd = 0,
  58. i, len, z, lenZ;
  59. if (typeof className === 'string') {
  60. arrClasses = className.split(' ');
  61. }
  62. len = arrClasses.length;
  63. for (i = 0; i < len; i++) {
  64. lenZ = elClasses.length;
  65. for (z = 0; z < lenZ; z++) {
  66. if (arrClasses[i] === elClasses[z]) {
  67. chkInd++;
  68. break;
  69. }
  70. }
  71. }
  72. return chkInd === arrClasses.length;
  73. },
  74. /**
  75. * Adds a class to node if not present, or removes if present.
  76. * @param {HTMLElement|SVGElement} element
  77. * @param className
  78. */
  79. toggle: function(element, className) {
  80. let fnc = this.has(element, className) ? 'remove': 'add';
  81. this[fnc](element, className);
  82. }
  83. };