UNPKG

@cap3/capitano-components

Version:
95 lines 3.6 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const React = require("react"); const react_dom_1 = require("react-dom"); const react_popper_1 = require("react-popper"); class Popup extends React.Component { constructor() { super(...arguments); this.state = { visible: false }; this.popupRef = null; this.targetRef = null; this.renderPopper = () => { const { popup, placement = "bottom-start", modifiers, portalNode, } = this.props; const { visible } = this.state; return (React.createElement(react_popper_1.Popper, Object.assign({ modifiers: { preventOverflow: { enabled: true }, flip: { enabled: true }, } }, { placement, modifiers }), ({ ref, style, placement }) => { const refSetter = (elem) => { if (elem && elem !== this.popupRef) { this.popupRef = elem; ref(elem); } }; const content = popup({ "data-placement": placement, ref: refSetter, style: Object.assign({}, style, { zIndex: 10 }), visible, toggle: this.toggle, }); if (portalNode) { return react_dom_1.createPortal(content, portalNode); } else { return content; } })); }; this.toggle = () => { if (!this.props.disabled) { this.state.visible ? this.hide() : this.show(); } }; this.show = () => { this.setState({ visible: true }, () => { document.addEventListener("click", this.outsideClickListener); }); }; this.hide = () => { this.setState({ visible: false }); this.removeOutsideClickListener(); }; this.removeOutsideClickListener = () => { document.removeEventListener("click", this.outsideClickListener); }; this.outsideClickListener = (event) => { const { visible } = this.state; if (this.props.hideOnInsideClick) { this.hide(); } else if (visible && this.popupRef) { const rect = this.popupRef.getBoundingClientRect(); const x = event.clientX; const y = event.clientY; if (isPointOutsideRect({ x, y }, rect)) { this.hide(); } } }; } componentWillUnmount() { this.removeOutsideClickListener(); } render() { const { target } = this.props; const { visible } = this.state; return (React.createElement(react_popper_1.Manager, null, React.createElement(react_popper_1.Reference, null, ({ ref }) => { const refSetter = (elem) => { if (elem && elem !== this.targetRef) { this.targetRef = elem; ref(elem); } }; return target({ ref: refSetter, toggle: this.toggle, visible }); }), visible && this.renderPopper())); } } exports.Popup = Popup; const isPointOutsideRect = ({ x, y }, { left, right, bottom, top }) => { return x < left || x > right || y < top || y > bottom; }; //# sourceMappingURL=Popup.js.map