diff --git a/rollup.config.js b/rollup.config.js index e15dd96f3..782ba5bd3 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -43,7 +43,7 @@ export default { plugins: [simplevars(), nested()], modules: true }), - sass({ insert: true }), + sass({ insert: false }), url(), svgr(), babel({ diff --git a/src/index.js b/src/index.js index f8d10128f..fb5b3f04b 100755 --- a/src/index.js +++ b/src/index.js @@ -19,7 +19,7 @@ import nodeListToArray from './utils/nodeListToArray'; import { generateUUID } from './utils/uuid'; /* CSS */ -import './index.scss'; +import baseCss from './index.scss'; import { generateTooltipStyle } from './decorators/styler'; @staticMethods @@ -146,6 +146,7 @@ class ReactTooltip extends React.Component { this.bindListener(); // Bind listener for tooltip this.bindWindowEvents(resizeHide); // Bind global event for static method + this.injectStyles(); // Inject styles for each DOM root having tooltip. } static getDerivedStateFromProps(nextProps, prevState) { @@ -173,6 +174,34 @@ class ReactTooltip extends React.Component { this.unbindWindowEvents(); } + /* Look for the closest DOM root having tooltip and inject styles. */ + injectStyles() { + const { id } = this.props; + const targetArray = this.getTargetArray(id); + const domRoots = []; + targetArray.forEach(target => { + let parentNode = target.parentNode; + while (parentNode.parentNode && !parentNode.host) { + parentNode = parentNode.parentNode; + } + const head = parentNode.querySelector('head'); + domRoots.push(head || parentNode); + }); + if (domRoots.length) { + const style = document.createElement('style'); + style.textContent = baseCss; + style.setAttribute('data-react-tooltip', 'true'); + domRoots + .filter((item, idx, src) => src.indexOf(item) === idx) + .forEach(domRoot => { + // Prevent styles duplication. + if (!domRoot.querySelector('style[data-react-tooltip]')) { + domRoot.appendChild(style); + } + }); + } + } + /** * Return if the mouse is on the tooltip. * @returns {boolean} true - mouse is on the tooltip