stylis-plugin-css-variables
Version:
Stylis plugin that transforms CSS variable into static values for non-supported browsers.
64 lines (53 loc) • 2.2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getRootPropertyValue = getRootPropertyValue;
exports.hasVariable = hasVariable;
var htmlRootNode;
/* istanbul ignore next */
if (typeof window !== 'undefined') {
var _window, _window$document;
htmlRootNode = (_window = window) == null ? void 0 : (_window$document = _window.document) == null ? void 0 : _window$document.documentElement;
}
/*
* Caching the computedStyle instance for document.documentElement.
* We do this so to prevent additional getComputedStyle calls, which greatly
* improves performance. We use the .getPropertyValue() method from this
* reference to retrieve CSS variable values.
*
* Although the instance is cached, the values retrieved by .getPropertyValue()
* are up to date. This is important in cases where global :root variables
* are updated.
*/
var rootComputedStyles = htmlRootNode && window.getComputedStyle(htmlRootNode);
/**
* Retrieves the custom CSS variable from the :root selector.
*
* @param {string} key The CSS variable property to retrieve.
* @return {?string} The value of the CSS variable.
*/
function getRootPropertyValue(key) {
var _rootStyles, _rootStyles$getProper;
// We'll attempt to get the CSS variable from :root.
var rootStyles = rootComputedStyles;
/* istanbul ignore next */
if (process.env.NODE_ENV === 'test') {
/*
* The cached rootComputedStyles does not retrieve the latest values
* in our environment (JSDOM). In that case, we'll create a fresh
* instance computedStyles on the root HTML element.
*/
rootStyles = typeof window !== 'undefined' && window.getComputedStyle(document.documentElement);
}
return (_rootStyles = rootStyles) == null ? void 0 : _rootStyles.getPropertyValue == null ? void 0 : (_rootStyles$getProper = _rootStyles.getPropertyValue(key)) == null ? void 0 : _rootStyles$getProper.trim();
}
/**
* Checks to see if a CSS declaration rule uses var().
*
* @param {string} declaration A CSS declaration rule.
* @return {boolean} Result of whether declaration contains a CSS variable.
*/
function hasVariable(declaration) {
return declaration.includes('var(');
}