parent
76f1765be7
commit
3997e94a68
@ -0,0 +1,87 @@ |
||||
const objToDom=obj => { |
||||
if(obj[Popup.EM]) { |
||||
let em=document.createElement('em'); |
||||
em.appendChild(document.createTextNode(obj[Popup.EM])); |
||||
return em; |
||||
} else if(obj[Popup.STRONG]) { |
||||
let em=document.createElement('strong'); |
||||
em.appendChild(document.createTextNode(obj[Popup.STRONG])); |
||||
return em; |
||||
} else if(typeof obj=='string' || typeof obj=='number') { |
||||
return document.createTextNode(obj+''); |
||||
} else if(Array.isArray(obj)) { |
||||
let ul=document.createElement('ul'); |
||||
obj.forEach(elem => ul.appendChild(objToDom(elem))); |
||||
return ul; |
||||
} else { |
||||
let table=document.createElement('table'); |
||||
Object |
||||
.keys(obj) |
||||
.forEach(key => { |
||||
let tr=table.appendChild(document.createElement('tr')); |
||||
tr.appendChild(document.createElement('th')).appendChild(document.createTextNode(key)); |
||||
tr.appendChild(document.createElement('td')).appendChild(objToDom(obj[key])); |
||||
}); |
||||
return table; |
||||
} |
||||
} |
||||
|
||||
class Popup { |
||||
constructor(title, content=[], buttons={}) { |
||||
this.title=title; |
||||
this.content=content.map(objToDom); |
||||
this.buttons={...buttons}; |
||||
} |
||||
|
||||
addContent(cnt) { |
||||
this.content.push(objToDom(cnt)); |
||||
} |
||||
addText(cnt) { |
||||
this.content.push(document.createTextNode(cnt)); |
||||
} |
||||
addEm(cnt) { |
||||
this.content.push(objToDom({[Popup.EM]: cnt})); |
||||
} |
||||
addStrong(cnt) { |
||||
this.content.push(objToDom({[Popup.STRONG]: cnt})); |
||||
} |
||||
|
||||
async display() { |
||||
let outer=document.createElement('div'); |
||||
outer.classList.add('popup'); |
||||
let popup=outer.appendChild(document.createElement('div')); |
||||
popup.classList.add('content'); |
||||
|
||||
let title=popup.appendChild(document.createElement('h1')); |
||||
title.innerText=this.title; |
||||
|
||||
let contentSection=popup.appendChild(document.createElement('section')); |
||||
this.content.forEach(elem => contentSection.appendChild(elem)); |
||||
|
||||
let buttonSection=popup.appendChild(document.createElement('section')); |
||||
let buttons=Object.keys(this.buttons).map(btn => { |
||||
let button=document.createElement('button'); |
||||
button.innerText=this.buttons[btn]; |
||||
button.dataset.code=btn; |
||||
return button; |
||||
}); |
||||
buttons.forEach(btn => buttonSection.appendChild(btn)); |
||||
|
||||
document.body.appendChild(outer); |
||||
|
||||
const code=await Promise.race(buttons.map(btn => new Promise(ok => { |
||||
btn.addEventListener('click', e => { |
||||
e.preventDefault(); |
||||
return ok(btn.dataset.code); |
||||
}); |
||||
}))); |
||||
|
||||
document.body.removeChild(outer); |
||||
return code; |
||||
} |
||||
} |
||||
|
||||
Popup.EM=Symbol('EM'); |
||||
Popup.STRONG=Symbol('STRONG'); |
||||
|
||||
return module.exports=Popup; |
Loading…
Reference in new issue