singleton.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.stylesheetSingleton = void 0;
  4. var get_nonce_1 = require("get-nonce");
  5. function makeStyleTag() {
  6. if (!document)
  7. return null;
  8. var tag = document.createElement('style');
  9. tag.type = 'text/css';
  10. var nonce = (0, get_nonce_1.getNonce)();
  11. if (nonce) {
  12. tag.setAttribute('nonce', nonce);
  13. }
  14. return tag;
  15. }
  16. function injectStyles(tag, css) {
  17. // @ts-ignore
  18. if (tag.styleSheet) {
  19. // @ts-ignore
  20. tag.styleSheet.cssText = css;
  21. }
  22. else {
  23. tag.appendChild(document.createTextNode(css));
  24. }
  25. }
  26. function insertStyleTag(tag) {
  27. var head = document.head || document.getElementsByTagName('head')[0];
  28. head.appendChild(tag);
  29. }
  30. var stylesheetSingleton = function () {
  31. var counter = 0;
  32. var stylesheet = null;
  33. return {
  34. add: function (style) {
  35. if (counter == 0) {
  36. if ((stylesheet = makeStyleTag())) {
  37. injectStyles(stylesheet, style);
  38. insertStyleTag(stylesheet);
  39. }
  40. }
  41. counter++;
  42. },
  43. remove: function () {
  44. counter--;
  45. if (!counter && stylesheet) {
  46. stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet);
  47. stylesheet = null;
  48. }
  49. },
  50. };
  51. };
  52. exports.stylesheetSingleton = stylesheetSingleton;