dao-game / files / src / utils / modal.ts
modal.ts
| 1 | export interface Options { |
| 2 | text: string; |
| 3 | title?: string; |
| 4 | willBackgroundCancel?: boolean; |
| 5 | } |
| 6 | |
| 7 | let previousPromise: Promise<void> = undefined; |
| 8 | /* |
| 9 | <div class="modal"> |
| 10 | <div class="modal-content"> |
| 11 | <span class="close">Close</span> |
| 12 | <p></p> |
| 13 | </div> |
| 14 | </div> |
| 15 | */ |
| 16 | export const showModal = (options: Options): Promise<void> => { |
| 17 | const { text, title, willBackgroundCancel } = options; |
| 18 | const modal = document.createElement('div'); |
| 19 | modal.classList.add('modal'); |
| 20 | |
| 21 | const modalContentDiv = document.createElement('div'); |
| 22 | modalContentDiv.classList.add('modal-content'); |
| 23 | modalContentDiv.classList.add('info'); |
| 24 | modal.appendChild(modalContentDiv); |
| 25 | |
| 26 | if (title) { |
| 27 | const modelContentTitle = document.createElement('div'); |
| 28 | modelContentTitle.classList.add('info'); |
| 29 | modelContentTitle.innerText = title; |
| 30 | modalContentDiv.appendChild(modelContentTitle); |
| 31 | } |
| 32 | |
| 33 | const closeSpan = document.createElement('span'); |
| 34 | closeSpan.classList.add('close'); |
| 35 | closeSpan.innerText = 'x'; |
| 36 | modalContentDiv.appendChild(closeSpan); |
| 37 | |
| 38 | const modalContentPara = document.createElement('p'); |
| 39 | modalContentPara.id = 'modal-content'; |
| 40 | modalContentPara.innerText = text; |
| 41 | modalContentDiv.appendChild(modalContentPara); |
| 42 | |
| 43 | document.body.appendChild(modal); |
| 44 | |
| 45 | const promise = new Promise<void>((resolve, reject) => { |
| 46 | let isModalOpen = true; |
| 47 | const closeModal = () => { |
| 48 | modal.style.display = "none"; |
| 49 | isModalOpen = false; |
| 50 | modal.parentNode.removeChild(modal); |
| 51 | resolve(); |
| 52 | } |
| 53 | |
| 54 | // When the user clicks on <span> (x), close the modal |
| 55 | closeSpan.onclick = () => closeModal(); |
| 56 | |
| 57 | if (willBackgroundCancel === undefined || willBackgroundCancel === true) { |
| 58 | // When the user clicks anywhere outside of the modal, close it |
| 59 | window.onclick = (event: MouseEvent) => { |
| 60 | if (event.target == modal) { |
| 61 | closeModal(); |
| 62 | } |
| 63 | }; |
| 64 | } |
| 65 | }); |
| 66 | |
| 67 | // show modal |
| 68 | modal.style.display = "block"; |
| 69 | |
| 70 | return promise; |
| 71 | } |