improve some null handling

This commit is contained in:
rhiannon morris 2024-07-07 21:42:17 +02:00
parent e89970d339
commit 38120bc60f

View file

@ -6,43 +6,38 @@ let skipAll: HTMLInputElement;
const opened: Set<string> = new Set; const opened: Set<string> = new Set;
function openCW(id: string | null, caption: HTMLElement | null, function openCW(id: string | null, caption: HTMLElement, focusLink = false): void {
focusLink = false) {
if (id !== null) opened.add(id); if (id !== null) opened.add(id);
if (caption !== null) mainfig.removeChild(caption); if (caption.parentElement) {
mainfig.removeChild(caption);
}
mainlink.tabIndex = 0; mainlink.tabIndex = 0;
if (focusLink) mainlink.focus(); if (focusLink) mainlink.focus();
} }
function addCWListeners(id: string | null, function addCWListeners(id: string | null, caption: HTMLElement): void {
caption: HTMLElement | null) {
if (caption) {
caption.addEventListener('click', _e => openCW(id, caption)); caption.addEventListener('click', _e => openCW(id, caption));
caption.addEventListener('keyup', caption.addEventListener('keyup',
e => { if (e.key == 'Enter') openCW(id, caption, true) }); e => { if (e.key == 'Enter') openCW(id, caption, true) });
} }
}
function setImage(id: string | null, function setImage(id: string, src: string, href: string, cw: string): void {
src: string,
href: string,
cw: string) {
const caption = document.getElementById('cw'); const caption = document.getElementById('cw');
const checked = skipAll ? skipAll.checked : false; const checked = skipAll ? skipAll.checked : false;
if (!checked && !opened.has(id) && cw) { if (!checked && !opened.has(id) && cw) {
const template = document.getElementById('cw-template') as HTMLTemplateElement; 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; newCaption.querySelector('#cw-text')!.innerHTML = cw;
addCWListeners(id, newCaption);
}
if (caption) { if (caption) openCW(null, caption);
openCW(null, caption);
}
if (newCaption !== null) {
mainfig.insertBefore(newCaption, mainlink); mainfig.insertBefore(newCaption, mainlink);
mainlink.tabIndex = -1; mainlink.tabIndex = -1;
addCWListeners(id, newCaption);
} else {
if (caption) openCW(null, caption);
} }
mainimg.src = src; mainimg.src = src;
@ -74,7 +69,10 @@ function useFragment(firstLoad = false): void {
activateButton(button, false); activateButton(button, false);
} }
if (firstLoad) addCWListeners(id, document.getElementById('cw')); if (firstLoad) {
const cw = document.getElementById('cw');
if (cw) addCWListeners(id, cw);
}
} }
function setup() { function setup() {