singletonStyleDomAPI.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. "use strict";
  2. /* istanbul ignore next */
  3. var replaceText = function replaceText() {
  4. var textStore = [];
  5. return function replace(index, replacement) {
  6. textStore[index] = replacement;
  7. return textStore.filter(Boolean).join("\n");
  8. };
  9. }();
  10. /* istanbul ignore next */
  11. function apply(styleElement, index, remove, obj) {
  12. var css;
  13. if (remove) {
  14. css = "";
  15. } else {
  16. css = "";
  17. if (obj.supports) {
  18. css += "@supports (".concat(obj.supports, ") {");
  19. }
  20. if (obj.media) {
  21. css += "@media ".concat(obj.media, " {");
  22. }
  23. var needLayer = typeof obj.layer !== "undefined";
  24. if (needLayer) {
  25. css += "@layer".concat(obj.layer.length > 0 ? " ".concat(obj.layer) : "", " {");
  26. }
  27. css += obj.css;
  28. if (needLayer) {
  29. css += "}";
  30. }
  31. if (obj.media) {
  32. css += "}";
  33. }
  34. if (obj.supports) {
  35. css += "}";
  36. }
  37. }
  38. // For old IE
  39. /* istanbul ignore if */
  40. if (styleElement.styleSheet) {
  41. styleElement.styleSheet.cssText = replaceText(index, css);
  42. } else {
  43. var cssNode = document.createTextNode(css);
  44. var childNodes = styleElement.childNodes;
  45. if (childNodes[index]) {
  46. styleElement.removeChild(childNodes[index]);
  47. }
  48. if (childNodes.length) {
  49. styleElement.insertBefore(cssNode, childNodes[index]);
  50. } else {
  51. styleElement.appendChild(cssNode);
  52. }
  53. }
  54. }
  55. var singletonData = {
  56. singleton: null,
  57. singletonCounter: 0
  58. };
  59. /* istanbul ignore next */
  60. function domAPI(options) {
  61. if (typeof document === "undefined") return {
  62. update: function update() {},
  63. remove: function remove() {}
  64. };
  65. // eslint-disable-next-line no-undef,no-use-before-define
  66. var styleIndex = singletonData.singletonCounter++;
  67. var styleElement =
  68. // eslint-disable-next-line no-undef,no-use-before-define
  69. singletonData.singleton || (
  70. // eslint-disable-next-line no-undef,no-use-before-define
  71. singletonData.singleton = options.insertStyleElement(options));
  72. return {
  73. update: function update(obj) {
  74. apply(styleElement, styleIndex, false, obj);
  75. },
  76. remove: function remove(obj) {
  77. apply(styleElement, styleIndex, true, obj);
  78. }
  79. };
  80. }
  81. module.exports = domAPI;