UNPKG

@bigfishtv/cockpit

Version:

71 lines (60 loc) 1.62 kB
import React, { Component } from 'react' import classnames from 'classnames' import newId from '../../utils/newId' export const modalHandler = {} export default class ModalHost extends Component { constructor(props) { super(props) this.state = { modals: [] } modalHandler.add = this.addModal modalHandler.remove = this.removeModal modalHandler.removeTop = this.removeTopModal } componentDidMount() { document.addEventListener('keydown', this.handleKeyDown) } componentWillUnmount() { document.removeEventListener('keydown', this.handleKeyDown) } handleKeyDown = event => { if (event.key === 'Escape') { this.removeTopModal() } } addModal = modal => { modal.id = newId() if (modal.closable === undefined) { modal.closable = true } this.setState({ modals: this.state.modals.concat([modal]), }) return modal } removeModal = modal => { this.setState({ modals: this.state.modals.filter(m => m !== modal), }) } removeTopModal = () => { if (this.state.modals.length) { const modal = this.state.modals[this.state.modals.length - 1] if (modal.closable) { this.removeModal(this.state.modals[this.state.modals.length - 1]) } } } render() { const { modals } = this.state const active = modals.length > 0 return ( <div className={classnames('modal', { hide: !active })}> <div className="modal-background" onClick={this.removeTopModal} /> {modals.map(modal => { const { Component, props, id } = modal return <Component key={id} {...props} closeModal={this.removeModal.bind(this, modal)} /> })} </div> ) } }