Last active
November 21, 2024 23:16
-
-
Save e1himself/d2b8acb398a5310cf6b8e27d92429ab7 to your computer and use it in GitHub Desktop.
The initial implementation of @prezly/react-promise-modal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ReactDOM from 'react-dom'; | |
import { noop } from 'lodash'; | |
const DEFAULT_OPTIONS = { | |
destructionDelay: 300, | |
}; | |
const reactConfirmation = async (renderModal, options = {}) => { | |
const { destructionDelay } = { ...DEFAULT_OPTIONS, ...options }; | |
const container = document.createElement('div'); | |
document.body.appendChild(container); | |
const displayModal = (props) => { | |
ReactDOM.render(renderModal({ ...props, show: true }), container); | |
}; | |
const hideModal = (props, callback) => { | |
ReactDOM.render(renderModal({ ...props, show: false }), container, callback); | |
}; | |
const destroyModal = () => { | |
ReactDOM.unmountComponentAtNode(container); | |
document.body.removeChild(container); | |
}; | |
const confirmation = new Promise((resolve) => { | |
const onConfirm = () => resolve(true); | |
const onCancel = () => resolve(false); | |
displayModal({ onConfirm, onCancel }); | |
}); | |
try { | |
return await confirmation; | |
} finally { | |
const onConfirm = noop; | |
const onCancel = noop; | |
hideModal({ onConfirm, onCancel }, () => { | |
setTimeout(destroyModal, destructionDelay); | |
}); | |
} | |
}; | |
export default reactConfirmation; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment