Last active
June 16, 2024 08:51
-
-
Save UniBreakfast/7aae27d23522ab3c961c4a466cfe0318 to your computer and use it in GitHub Desktop.
Promisified function `showModal()` with two modal dialogs back and forth traversal.
This file contains 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
await showModal() | |
function showModal() { | |
const values = ['a', 'b'] | |
return new Promise(async resolve => { | |
do { | |
const dialog = makeDialog() | |
const addBtn = makeBtn('add') | |
const buttons = values.map(makeBtn) | |
dialog.append(addBtn, ...buttons) | |
const decision = await new Promise(resolve => { | |
dialog.onclick = async e => { | |
if (e.target == addBtn) { | |
values.push(await getInput()) | |
resolve() | |
} else if (buttons.includes(e.target)) { | |
if (e.altKey) { | |
const i = values.indexOf(e.target.value) | |
values.splice(i, 1) | |
resolve() | |
} else resolve(e.target.value) | |
} else return | |
dialog.remove() | |
} | |
}) | |
if (decision) return resolve(decision) | |
} while (true) | |
}) | |
} | |
function getInput() { | |
const dialog = makeDialog() | |
const input = makeInput() | |
const addBtn = makeBtn('add') | |
dialog.append(input, addBtn) | |
return new Promise(resolve => { | |
addBtn.onclick = () => { | |
resolve(input.value) | |
dialog.remove() | |
} | |
}) | |
} | |
function makeDialog() { | |
const dialog = document.createElement('dialog') | |
dialog.show() | |
document.body.replaceChildren(dialog) | |
return dialog | |
} | |
function makeBtn(value) { | |
const btn = document.createElement('button') | |
btn.append(value) | |
btn.setAttribute('value', value) | |
return btn | |
} | |
function makeInput() { | |
const input = document.createElement('input') | |
return input | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment