@grafana/ui
Version:
Grafana Components Library
1 lines • 3.4 kB
Source Map (JSON)
{"version":3,"file":"ClickOutsideWrapper.mjs","sources":["../../../../src/components/ClickOutsideWrapper/ClickOutsideWrapper.tsx"],"sourcesContent":["import { PureComponent, createRef } from 'react';\nimport * as React from 'react';\n\nexport interface Props {\n /**\n * Callback to trigger when clicking outside of current element occurs.\n */\n onClick: () => void;\n /**\n * Runs the 'onClick' function when pressing a key outside of the current element. Defaults to true.\n */\n includeButtonPress: boolean;\n /** Object to attach the click event listener to. */\n parent: Window | Document;\n /**\n * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener. Defaults to false.\n */\n useCapture?: boolean;\n}\n\ninterface State {\n hasEventListener: boolean;\n}\n\nexport class ClickOutsideWrapper extends PureComponent<React.PropsWithChildren<Props>, State> {\n static defaultProps = {\n includeButtonPress: true,\n parent: typeof window !== 'undefined' ? window : undefined,\n useCapture: false,\n };\n myRef = createRef<HTMLDivElement>();\n state = {\n hasEventListener: false,\n };\n\n componentDidMount() {\n this.props.parent.addEventListener('click', this.onOutsideClick, this.props.useCapture);\n if (this.props.includeButtonPress) {\n // Use keyup since keydown already has an event listener on window\n this.props.parent.addEventListener('keyup', this.onOutsideClick, this.props.useCapture);\n }\n }\n\n componentWillUnmount() {\n this.props.parent.removeEventListener('click', this.onOutsideClick, this.props.useCapture);\n if (this.props.includeButtonPress) {\n this.props.parent.removeEventListener('keyup', this.onOutsideClick, this.props.useCapture);\n }\n }\n\n onOutsideClick: EventListener = (event) => {\n const domNode = this.myRef.current;\n\n if (!domNode || (event.target instanceof Node && !domNode.contains(event.target))) {\n this.props.onClick();\n }\n };\n\n render() {\n return <div ref={this.myRef}>{this.props.children}</div>;\n }\n}\n"],"names":[],"mappings":";;;AAwBO,MAAM,4BAA4B,aAAqD,CAAA;AAAA,EAAvF,WAAA,GAAA;AAAA,IAAA,KAAA,CAAA,GAAA,SAAA,CAAA;AAML,IAAA,IAAA,CAAA,KAAA,GAAQ,SAA0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