index.js
65 lines
| 1 | import { Button, Popover } from '@wordpress/components'; |
| 2 | import { createRef, Component } from '@wordpress/element'; |
| 3 | |
| 4 | export default class AdvancedPopOverControl extends Component { |
| 5 | constructor(props) { |
| 6 | super(props); |
| 7 | this.state = { open: false }; |
| 8 | this.buttonRef = createRef(); |
| 9 | } |
| 10 | |
| 11 | render() { |
| 12 | const popverBtnClass = |
| 13 | 'apc-icon-btn components-button is-secondary is-small'; |
| 14 | |
| 15 | const handleOpen = () => { |
| 16 | this.setState({ open: !this.state.open }); |
| 17 | }; |
| 18 | |
| 19 | const handleClose = () => { |
| 20 | this.setState({ open: false }); |
| 21 | }; |
| 22 | |
| 23 | const handleOnClickOutside = (event) => { |
| 24 | if ( |
| 25 | event.relatedTarget && |
| 26 | !event.relatedTarget.closest(`.${popverBtnClass}`) && |
| 27 | event.relatedTarget !== this.buttonRef.current |
| 28 | ) { |
| 29 | handleClose(); |
| 30 | } |
| 31 | }; |
| 32 | |
| 33 | return ( |
| 34 | <> |
| 35 | <div className="components-base-control"> |
| 36 | <div |
| 37 | className={ |
| 38 | 'vk-blocks-button-icon-control__wrapper components-base-control__field' |
| 39 | } |
| 40 | ref={this.buttonRef} |
| 41 | > |
| 42 | <Button |
| 43 | isTertiary |
| 44 | className={`${popverBtnClass} mb-1`} |
| 45 | onClick={handleOpen} |
| 46 | ref={this.buttonRef} |
| 47 | > |
| 48 | {this.props.label} |
| 49 | </Button> |
| 50 | {this.state.open && this.buttonRef.current && ( |
| 51 | <Popover |
| 52 | anchor={this.buttonRef.current} |
| 53 | children={this.props.renderComp} |
| 54 | onFocusOutside={handleOnClickOutside} |
| 55 | focusOnMount={'container'} |
| 56 | className={'vk-blocks-advanced-popover-control'} |
| 57 | ></Popover> |
| 58 | )} |
| 59 | </div> |
| 60 | </div> |
| 61 | </> |
| 62 | ); |
| 63 | } |
| 64 | } |
| 65 |