gallery/script/single.ts

109 lines
3.1 KiB
TypeScript

let mainfig: HTMLElement;
let mainimg: HTMLImageElement;
let mainlink: HTMLAnchorElement;
let altButtons: HTMLInputElement[];
let skipAll: HTMLInputElement;
const opened: Set<string> = new Set;
function openCW(id: string | null, caption: HTMLElement, focusLink = false): void {
if (id !== null) opened.add(id);
if (caption.parentElement) {
mainfig.removeChild(caption);
}
mainlink.tabIndex = 0;
if (focusLink) mainlink.focus();
}
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, 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;
const newCaption = template.content.firstElementChild!.cloneNode(true) as HTMLElement;
newCaption.querySelector('#cw-text')!.innerHTML = cw;
if (caption) openCW(null, caption);
mainfig.insertBefore(newCaption, mainlink);
mainlink.tabIndex = -1;
addCWListeners(id, newCaption);
} else {
if (caption) openCW(null, caption);
}
mainimg.src = src;
mainlink.href = href;
}
function activateButton(button: HTMLInputElement, doPush = true): void {
setImage(button.id, button.value,
button.dataset.link!,
button.dataset.warning!);
if (doPush) history.pushState(null, '', '#' + button.id);
}
function useFragment(firstLoad = false): void {
let button = altButtons[0];
const frag = decodeURIComponent(location.hash).replace(/^#/, '');
if (frag) {
const selected = document.getElementById(frag) as HTMLInputElement;
if (selected) button = selected;
}
let id: string | null = null;
if (button) {
id = button.id;
button.checked = true;
activateButton(button, false);
}
if (firstLoad) {
const cw = document.getElementById('cw');
if (cw) addCWListeners(id, cw);
}
}
function setup() {
mainfig = document.getElementById('mainfig')!;
mainimg = document.getElementById('mainimg') as HTMLImageElement;
mainlink = document.getElementById('mainlink') as HTMLAnchorElement;
skipAll = document.getElementById('skipAll') as HTMLInputElement;
const alts = document.getElementById('alts');
if (alts) {
const inputs = Array.from(alts.getElementsByTagName('input'));
altButtons = inputs.filter(e => e.name == 'variant');
} else {
altButtons = [];
}
for (const button of altButtons) {
button.onchange = _e => { if (button.checked) activateButton(button); };
}
if (skipAll) {
skipAll.onchange = _e => { if (skipAll.checked) {
const caption = document.getElementById('cw');
if (caption) { openCW(null, caption, false); }
} };
}
window.addEventListener('popstate', _e => useFragment());
useFragment(true);
}
window.addEventListener('DOMContentLoaded', setup);
export {};