rc-util
Version:
Common Utils For React Component
52 lines (41 loc) • 1.42 kB
JavaScript
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import canUseDom from './canUseDom';
var MARK_KEY = "rc-util-key";
function getContainer(option) {
if (option.attachTo) {
return option.attachTo;
}
var head = document.querySelector('head');
return head || document.body;
}
export function injectCSS(css) {
var _option$csp;
var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!canUseDom()) {
return null;
}
var styleNode = document.createElement('style');
styleNode.nonce = (_option$csp = option.csp) === null || _option$csp === void 0 ? void 0 : _option$csp.nonce;
styleNode.innerHTML = css;
var container = getContainer(option);
var firstChild = container.firstChild;
if (option.prepend && firstChild) {
container.insertBefore(styleNode, firstChild);
} else {
container.appendChild(styleNode);
}
return styleNode;
}
export function updateCSS(css, key) {
var option = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var container = getContainer(option);
var existNode = _toConsumableArray(container.children).find(function (node) {
return node.tagName === 'STYLE' && node[MARK_KEY] === key;
});
if (existNode) {
existNode.parentElement.removeChild(existNode);
}
var newNode = injectCSS(css, option);
newNode[MARK_KEY] = key;
return newNode;
}