@shopify/polaris
Version:
Shopify’s product component library
84 lines (69 loc) • 2.14 kB
JavaScript
import { PureComponent } from 'react';
import { ThemeContext } from '../../utilities/theme/context.js';
import { globalIdGeneratorFactory } from '../../utilities/unique-id/unique-id-factory.js';
import { portal } from '../shared.js';
import { createPortal } from 'react-dom';
var getUniqueID = globalIdGeneratorFactory('portal-');
class Portal extends PureComponent {
constructor(...args) {
super(...args);
this.context = void 0;
this.state = {
isMounted: false
};
this.portalNode = null;
this.portalId = this.props.idPrefix !== '' ? "".concat(this.props.idPrefix, "-").concat(getUniqueID()) : getUniqueID();
}
componentDidMount() {
this.portalNode = document.createElement('div');
this.portalNode.setAttribute(portal.props[0], this.portalId);
if (this.context != null) {
var {
cssCustomProperties
} = this.context;
if (cssCustomProperties != null) {
this.portalNode.setAttribute('style', cssCustomProperties);
} else {
this.portalNode.removeAttribute('style');
}
}
document.body.appendChild(this.portalNode);
this.setState({
isMounted: true
});
}
componentDidUpdate(_, prevState) {
var {
onPortalCreated = noop
} = this.props;
if (this.portalNode && this.context != null) {
var {
cssCustomProperties,
textColor
} = this.context;
if (cssCustomProperties != null) {
var style = "".concat(cssCustomProperties, ";color:").concat(textColor, ";");
this.portalNode.setAttribute('style', style);
} else {
this.portalNode.removeAttribute('style');
}
}
if (!prevState.isMounted && this.state.isMounted) {
onPortalCreated();
}
}
componentWillUnmount() {
if (this.portalNode) {
document.body.removeChild(this.portalNode);
}
}
render() {
return this.portalNode && this.state.isMounted ? /*#__PURE__*/createPortal(this.props.children, this.portalNode) : null;
}
}
Portal.defaultProps = {
idPrefix: ''
};
Portal.contextType = ThemeContext;
function noop() {}
export { Portal };