github.com/kyleu/dbaudit@v0.0.2-0.20240321155047-ff2f2c940496/client/src/modal.ts (about) 1 // Content managed by Project Forge, see [projectforge.md] for details. 2 export function modalInit() { 3 document.addEventListener("keydown", (event) => { 4 if (event.key === "Escape") { 5 if (document.location.hash.startsWith("#modal-")) { 6 document.location.hash = ""; 7 } 8 } 9 }); 10 } 11 12 export function modalNew(key: string, title: string) { 13 const el = document.createElement("div"); 14 el.classList.add("modal"); 15 el.id = "modal-" + key; 16 el.style.display = "none"; 17 18 const backdrop = document.createElement("a"); 19 backdrop.classList.add("backdrop"); 20 backdrop.href = "#"; 21 el.appendChild(backdrop); 22 23 const content = document.createElement("div"); 24 content.classList.add("modal-content"); 25 el.appendChild(content); 26 27 const hd = document.createElement("div"); 28 hd.classList.add("modal-header"); 29 content.appendChild(hd); 30 31 const hdClose = document.createElement("a"); 32 hdClose.classList.add("modal-close"); 33 hdClose.href = "#"; 34 hdClose.innerText = "×"; 35 hd.appendChild(hdClose); 36 37 const hdTitle = document.createElement("h2"); 38 hdTitle.innerText = title; 39 hd.appendChild(hdTitle); 40 41 const bd = document.createElement("div"); 42 bd.classList.add("modal-body"); 43 content.appendChild(bd); 44 45 document.body.appendChild(el); 46 return el; 47 } 48 49 export function modalGetOrCreate(key: string, title: string): HTMLElement { 50 const el = document.getElementById("modal-" + key); 51 if (el) { 52 const bodies = el.getElementsByClassName("modal-body"); 53 if (bodies.length !== 1) { 54 throw new Error("unable to find modal body"); 55 } 56 return el; 57 } 58 return modalNew(key, title); 59 } 60 61 export function modalGetBody(m: HTMLElement) { 62 const bodies = m.getElementsByClassName("modal-body"); 63 if (bodies.length !== 1) { 64 throw new Error("unable to find modal body"); 65 } 66 return bodies[0]; 67 } 68 69 export function modalGetHeader(m: HTMLElement) { 70 const bodies = m.getElementsByClassName("modal-header"); 71 if (bodies.length !== 1) { 72 throw new Error("unable to find modal header"); 73 } 74 return bodies[0]; 75 } 76 77 export function modalSetTitle(m: HTMLElement, title: string) { 78 const hd = modalGetHeader(m); 79 const t = hd.getElementsByTagName("h2"); 80 if (t.length !== 1) { 81 throw new Error("unable to find modal title"); 82 } 83 t[0].innerText = title; 84 }