css.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.css = void 0;
  4. var utils_1 = require("../utils");
  5. function css(prop, val) {
  6. if ((prop != null && val != null) ||
  7. // When `prop` is a "plain" object
  8. (typeof prop === 'object' && !Array.isArray(prop))) {
  9. return utils_1.domEach(this, function (el, i) {
  10. if (utils_1.isTag(el)) {
  11. // `prop` can't be an array here anymore.
  12. setCss(el, prop, val, i);
  13. }
  14. });
  15. }
  16. return getCss(this[0], prop);
  17. }
  18. exports.css = css;
  19. /**
  20. * Set styles of all elements.
  21. *
  22. * @private
  23. * @param el - Element to set style of.
  24. * @param prop - Name of property.
  25. * @param value - Value to set property to.
  26. * @param idx - Optional index within the selection.
  27. */
  28. function setCss(el, prop, value, idx) {
  29. if (typeof prop === 'string') {
  30. var styles = getCss(el);
  31. var val = typeof value === 'function' ? value.call(el, idx, styles[prop]) : value;
  32. if (val === '') {
  33. delete styles[prop];
  34. }
  35. else if (val != null) {
  36. styles[prop] = val;
  37. }
  38. el.attribs.style = stringify(styles);
  39. }
  40. else if (typeof prop === 'object') {
  41. Object.keys(prop).forEach(function (k, i) {
  42. setCss(el, k, prop[k], i);
  43. });
  44. }
  45. }
  46. function getCss(el, prop) {
  47. if (!el || !utils_1.isTag(el))
  48. return;
  49. var styles = parse(el.attribs.style);
  50. if (typeof prop === 'string') {
  51. return styles[prop];
  52. }
  53. if (Array.isArray(prop)) {
  54. var newStyles_1 = {};
  55. prop.forEach(function (item) {
  56. if (styles[item] != null) {
  57. newStyles_1[item] = styles[item];
  58. }
  59. });
  60. return newStyles_1;
  61. }
  62. return styles;
  63. }
  64. /**
  65. * Stringify `obj` to styles.
  66. *
  67. * @private
  68. * @category CSS
  69. * @param obj - Object to stringify.
  70. * @returns The serialized styles.
  71. */
  72. function stringify(obj) {
  73. return Object.keys(obj).reduce(function (str, prop) { return "" + str + (str ? ' ' : '') + prop + ": " + obj[prop] + ";"; }, '');
  74. }
  75. /**
  76. * Parse `styles`.
  77. *
  78. * @private
  79. * @category CSS
  80. * @param styles - Styles to be parsed.
  81. * @returns The parsed styles.
  82. */
  83. function parse(styles) {
  84. styles = (styles || '').trim();
  85. if (!styles)
  86. return {};
  87. return styles.split(';').reduce(function (obj, str) {
  88. var n = str.indexOf(':');
  89. // Skip if there is no :, or if it is the first/last character
  90. if (n < 1 || n === str.length - 1)
  91. return obj;
  92. obj[str.slice(0, n).trim()] = str.slice(n + 1).trim();
  93. return obj;
  94. }, {});
  95. }