From 38120bc60f3f987809b94495bd2c92d6a7780e05 Mon Sep 17 00:00:00 2001 From: rhiannon morris Date: Sun, 7 Jul 2024 21:42:17 +0200 Subject: [PATCH] improve some null handling --- script/single.ts | 42 ++++++++++++++++++++---------------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/script/single.ts b/script/single.ts index 2954f7d..e5f1c08 100644 --- a/script/single.ts +++ b/script/single.ts @@ -6,43 +6,38 @@ let skipAll: HTMLInputElement; const opened: Set = new Set; -function openCW(id: string | null, caption: HTMLElement | null, - focusLink = false) { +function openCW(id: string | null, caption: HTMLElement, focusLink = false): void { if (id !== null) opened.add(id); - if (caption !== null) mainfig.removeChild(caption); + if (caption.parentElement) { + mainfig.removeChild(caption); + } mainlink.tabIndex = 0; if (focusLink) mainlink.focus(); } -function addCWListeners(id: string | null, - caption: HTMLElement | null) { - if (caption) { - caption.addEventListener('click', _e => openCW(id, caption)); - caption.addEventListener('keyup', - e => { if (e.key == 'Enter') openCW(id, caption, true) }); - } +function addCWListeners(id: string | null, caption: HTMLElement): void { + caption.addEventListener('click', _e => openCW(id, caption)); + caption.addEventListener('keyup', + e => { if (e.key == 'Enter') openCW(id, caption, true) }); } -function setImage(id: string | null, - src: string, - href: string, - cw: string) { +function setImage(id: string, src: string, href: string, cw: string): void { const caption = document.getElementById('cw'); const checked = skipAll ? skipAll.checked : false; if (!checked && !opened.has(id) && cw) { const template = document.getElementById('cw-template') as HTMLTemplateElement; - newCaption = template.content.firstElementChild!.cloneNode(true) as HTMLElement; + const newCaption = template.content.firstElementChild!.cloneNode(true) as HTMLElement; newCaption.querySelector('#cw-text')!.innerHTML = cw; - addCWListeners(id, newCaption); - } - if (caption) { - openCW(null, caption); - } - if (newCaption !== null) { + if (caption) openCW(null, caption); + mainfig.insertBefore(newCaption, mainlink); mainlink.tabIndex = -1; + + addCWListeners(id, newCaption); + } else { + if (caption) openCW(null, caption); } mainimg.src = src; @@ -74,7 +69,10 @@ function useFragment(firstLoad = false): void { activateButton(button, false); } - if (firstLoad) addCWListeners(id, document.getElementById('cw')); + if (firstLoad) { + const cw = document.getElementById('cw'); + if (cw) addCWListeners(id, cw); + } } function setup() {