fuzzyworld

dao-game / peerjs-browser-bug / files / src / modal.ts

Branch peerjs-browser-bug · default branch · all branches

modal.ts

2.1 KB · history · blame

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