Files
fewo-stommer/resources/themes/ostsee-licht/theme.js
T
LarsandClaude Opus 5.5 a1fc4f7fef
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m38s
Galerie: kein Springen beim Blaettern, Vergleich ohne Pfeile an den Beschriftungen
- Lightbox: feste Bildgroesse aus dem Seitenverhaeltnis, beim Blaettern wird das grosse Foto erst geladen und dann eingeblendet
- Seebad-Vergleich: Pfeile neben Sommer/Winter entfernt (passten nicht zur Ziehrichtung)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 07:07:26 +01:00

385 lines
17 KiB
JavaScript

/**
* Theme "Ostsee-Licht": small progressive enhancements. Everything works without JavaScript.
*/
// Lightbox for galleries: links with data-lightbox open the large image in the layout's dialog#lightbox. The photo
// grows out of its thumbnail and shrinks back on closing; the links of one section form a series to browse with the
// arrow buttons, the arrow keys or a swipe. Without JavaScript the link simply opens the large image.
const lightbox = document.getElementById('lightbox');
if (lightbox && typeof lightbox.showModal === 'function') {
const image = lightbox.querySelector('img');
const caption = lightbox.querySelector('[data-caption]');
const counter = lightbox.querySelector('[data-counter]');
const browseButtons = lightbox.querySelectorAll('[data-prev], [data-next]');
const ease = 'cubic-bezier(0.2, 0.8, 0.2, 1)';
let series = [];
let index = 0;
const thumbnailOf = (link) => link.querySelector('img');
// Transform that lays the opened image over the thumbnail: same centre, scaled to cover it, cropped like object-cover.
const fromThumbnail = (thumbnail) => {
const from = thumbnail.getBoundingClientRect();
const to = image.getBoundingClientRect();
if (!from.width || !to.width) {
return null;
}
const scale = Math.max(from.width / to.width, from.height / to.height);
const insetX = (to.width * scale - from.width) / (2 * scale);
const insetY = (to.height * scale - from.height) / (2 * scale);
const x = from.left + from.width / 2 - (to.left + to.width / 2);
const y = from.top + from.height / 2 - (to.top + to.height / 2);
return { transform: `translate(${x}px, ${y}px) scale(${scale})`, clipPath: `inset(${insetY}px ${insetX}px round 4px)` };
};
const visible = (element) => {
const rect = element.getBoundingClientRect();
return rect.bottom > 0 && rect.top < window.innerHeight && rect.width > 0;
};
// The image gets its final size from the photo's aspect ratio, so swapping the thumbnail for the large file
// (or browsing to the next photo) never makes it jump between sizes.
const fit = () => {
const thumbnail = thumbnailOf(series[index]);
const ratio = thumbnail?.naturalWidth ? thumbnail.naturalWidth / thumbnail.naturalHeight : 3 / 2;
const width = Math.min(window.innerWidth * 0.94, window.innerHeight * 0.84 * ratio);
image.style.width = `${width}px`;
image.style.height = `${width / ratio}px`;
};
const show = (position) => {
index = (position + series.length) % series.length;
const link = series[index];
const thumbnail = thumbnailOf(link);
fit();
image.src = thumbnail?.currentSrc || link.href;
image.alt = link.dataset.alt ?? '';
caption.textContent = link.dataset.caption || link.dataset.alt || '';
if (counter) {
counter.textContent = series.length > 1 ? `${index + 1} von ${series.length}` : '';
}
if (image.src !== link.href) {
const large = new Image();
large.onload = () => { if (series[index] === link) image.src = link.href; };
large.src = link.href;
}
};
// Browsing waits (briefly) for the large file of the next photo, then fades it in; no thumbnail flashes in between.
let browsing = 0;
const browse = (step) => {
if (series.length < 2) {
return;
}
const target = (index + step + series.length) % series.length;
const ticket = ++browsing;
const large = new Image();
large.src = series[target].href;
const ready = Promise.race([large.decode().catch(() => {}), new Promise((resolve) => setTimeout(resolve, 600))]);
ready.then(() => {
if (ticket !== browsing) {
return;
}
show(target);
if (!reducedMotion()) {
image.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 260, easing: 'ease-out' });
}
});
};
window.addEventListener('resize', () => { if (lightbox.open) fit(); });
const close = () => {
const thumbnail = thumbnailOf(series[index] ?? lightbox);
const start = !reducedMotion() && thumbnail && visible(thumbnail) ? fromThumbnail(thumbnail) : null;
if (!start) {
lightbox.close();
return;
}
lightbox.querySelectorAll('[data-chrome]').forEach((element) => element.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 150, fill: 'forwards' }));
image.animate([{ transform: 'none', clipPath: 'inset(0 0 round 4px)' }, start], { duration: 380, easing: ease, fill: 'forwards' })
.finished.then(() => {
lightbox.close();
lightbox.getAnimations({ subtree: true }).forEach((animation) => animation.cancel());
});
};
document.addEventListener('click', (event) => {
const link = event.target.closest('a[data-lightbox]');
if (!link) {
return;
}
event.preventDefault();
series = [...(link.closest('section') ?? document).querySelectorAll('a[data-lightbox]')];
browseButtons.forEach((button) => { button.hidden = series.length < 2; });
show(series.indexOf(link));
lightbox.showModal();
const thumbnail = thumbnailOf(link);
const start = !reducedMotion() && thumbnail ? fromThumbnail(thumbnail) : null;
if (start) {
image.animate([start, { transform: 'none', clipPath: 'inset(0 0 round 4px)' }], { duration: 480, easing: ease });
lightbox.querySelectorAll('[data-chrome]').forEach((element) => element.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 250, delay: 300, fill: 'backwards' }));
}
});
lightbox.addEventListener('click', (event) => {
if (event.target.closest('[data-prev]')) {
browse(-1);
} else if (event.target.closest('[data-next]')) {
browse(1);
} else if (event.target === lightbox || event.target.closest('[data-close]')) {
close();
}
});
lightbox.addEventListener('cancel', (event) => {
event.preventDefault();
close();
});
lightbox.addEventListener('keydown', (event) => {
if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
event.preventDefault();
browse(event.key === 'ArrowLeft' ? -1 : 1);
}
});
let swipeStart = null;
lightbox.addEventListener('pointerdown', (event) => { swipeStart = { x: event.clientX, y: event.clientY }; });
lightbox.addEventListener('pointerup', (event) => {
const dx = swipeStart ? event.clientX - swipeStart.x : 0;
const dy = swipeStart ? event.clientY - swipeStart.y : 0;
swipeStart = null;
if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(dy) * 1.5) {
browse(dx < 0 ? 1 : -1);
}
});
}
// Availability search in the hero: forwards the dates to the booking page.
document.addEventListener('submit', (event) => {
const form = event.target.closest('form[data-availability-search]');
if (!form) {
return;
}
const arrival = form.querySelector('[name=anreise]').value;
const departure = form.querySelector('[name=abreise]').value;
if (!arrival || !departure) {
event.preventDefault();
form.querySelector('[name=anreise]').focus();
}
});
// Rotating offers: one slide at a time, advancing every 7 s; pauses on hover/focus and
// does not advance by itself when the visitor prefers reduced motion.
document.querySelectorAll('[data-rotator]').forEach((rotator) => {
const slides = [...rotator.querySelectorAll('[data-rotator-slide]')];
const dots = [...rotator.querySelectorAll('[data-rotator-dot]')];
let current = 0;
let paused = false;
const show = (index) => {
current = (index + slides.length) % slides.length;
slides.forEach((slide, i) => { slide.hidden = i !== current; });
dots.forEach((dot, i) => dot.setAttribute('aria-selected', i === current ? 'true' : 'false'));
};
rotator.querySelector('[data-rotator-prev]')?.addEventListener('click', () => show(current - 1));
rotator.querySelector('[data-rotator-next]')?.addEventListener('click', () => show(current + 1));
dots.forEach((dot, i) => dot.addEventListener('click', () => show(i)));
['mouseenter', 'focusin'].forEach((type) => rotator.addEventListener(type, () => { paused = true; }));
['mouseleave', 'focusout'].forEach((type) => rotator.addEventListener(type, () => { paused = false; }));
if (!window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
setInterval(() => { if (!paused && !document.hidden) show(current + 1); }, 7000);
}
});
const reducedMotion = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// Playback speed set per video in the admin (data-playback-rate); also after the browser resets it on load.
document.querySelectorAll('video[data-playback-rate]').forEach((video) => {
const rate = Number(video.dataset.playbackRate) || 1;
const apply = () => { video.defaultPlaybackRate = rate; video.playbackRate = rate; };
apply();
video.addEventListener('loadedmetadata', apply);
});
// Silent video loops (partials/video-loop): loaded only with motion allowed and without Save-Data, playing while
// visible; the button pauses and resumes. Otherwise the poster stays and nothing is downloaded.
document.querySelectorAll('[data-video-loop]').forEach((box) => {
const video = box.querySelector('video');
const toggle = box.querySelector('[data-video-toggle]');
if (!video?.dataset.src || reducedMotion() || navigator.connection?.saveData) {
return;
}
let stopped = false;
const play = () => video.play().catch(() => {});
video.src = video.dataset.src;
video.preload = 'auto';
toggle.hidden = false;
toggle.addEventListener('click', () => {
stopped = !stopped;
stopped ? video.pause() : play();
const label = stopped ? 'Video abspielen' : 'Video anhalten';
toggle.setAttribute('aria-pressed', String(stopped));
toggle.setAttribute('aria-label', label);
toggle.title = label;
toggle.querySelector('[data-icon-pause]').classList.toggle('hidden', stopped);
toggle.querySelector('[data-icon-play]').classList.toggle('hidden', !stopped);
});
new IntersectionObserver(([entry]) => {
entry.isIntersecting && !stopped ? play() : video.pause();
}).observe(video);
});
// Video tour (sections/tour): start overlay, chapter buttons, highlighting the current chapter; floor plan rooms
// with [data-tour-link] jump into the tour on the same page. Without JavaScript the native controls remain.
const tour = document.querySelector('[data-tour]');
if (tour) {
const video = tour.querySelector('video');
const start = tour.querySelector('[data-tour-start]');
const seeks = [...tour.querySelectorAll('[data-tour-seek]')];
const playFrom = (seconds) => {
start.hidden = true;
const go = () => {
if (seconds !== null) {
video.currentTime = seconds;
}
video.play().catch(() => {});
};
video.readyState >= 1 ? go() : video.addEventListener('loadedmetadata', go, { once: true });
if (video.readyState < 1) {
video.load();
}
};
start.hidden = false;
start.addEventListener('click', () => playFrom(null));
video.addEventListener('play', () => { start.hidden = true; });
tour.querySelector('[data-tour-chapters]')?.removeAttribute('hidden');
seeks.forEach((button) => button.addEventListener('click', () => playFrom(Number(button.dataset.tourSeek))));
video.addEventListener('timeupdate', () => {
const current = seeks.filter((button) => Number(button.dataset.tourSeek) <= video.currentTime + 0.25).pop();
seeks.forEach((button) => (button === current ? button.setAttribute('aria-current', 'true') : button.removeAttribute('aria-current')));
});
document.querySelectorAll('[data-tour-link]').forEach((link) => {
link.hidden = false;
link.addEventListener('click', (event) => {
event.preventDefault();
tour.scrollIntoView({ behavior: reducedMotion() ? 'auto' : 'smooth', block: 'center' });
playFrom(Number(link.dataset.tourLink));
});
});
}
// One-time reveal of a graphic when it scrolls into view (e.g. the sunrise of theme Seebad): the theme's CSS
// styles [data-reveal="ready"] (start) and the transition to [data-reveal="shown"]. Without JavaScript or with
// reduced motion the graphic is simply shown.
if (!reducedMotion() && 'IntersectionObserver' in window) {
const reveal = new IntersectionObserver((entries) => {
entries.filter((entry) => entry.isIntersecting).forEach((entry) => {
entry.target.dataset.reveal = 'shown';
reveal.unobserve(entry.target);
});
}, { threshold: 0.6 });
document.querySelectorAll('[data-reveal]').forEach((element) => {
if (element.getBoundingClientRect().top < window.innerHeight * 0.85) {
element.dataset.reveal = 'ready';
requestAnimationFrame(() => requestAnimationFrame(() => { element.dataset.reveal = 'shown'; }));
return;
}
element.dataset.reveal = 'ready';
reveal.observe(element);
});
}
// Cards to turn over (sections/tips): [data-flip] card, [data-flip-inner], [data-flip-face="front|back"], buttons
// [data-flip-toggle] (hidden without JavaScript). The hidden face is inert, so keyboard and screen reader stay on the
// visible one; focus moves to the button of the face that turns up.
document.querySelectorAll('[data-flip]').forEach((card) => {
const front = card.querySelector('[data-flip-face="front"]');
const back = card.querySelector('[data-flip-face="back"]');
const turn = (flipped) => {
card.toggleAttribute('data-flipped', flipped);
front.inert = flipped;
back.inert = !flipped;
card.querySelectorAll('[data-flip-toggle]').forEach((button) => button.setAttribute('aria-expanded', String(flipped)));
(flipped ? back : front).querySelector('[data-flip-toggle]')?.focus({ preventScroll: true });
};
card.dataset.flip = 'ready';
back.inert = true;
card.querySelectorAll('[data-flip-toggle]').forEach((button) => {
button.hidden = false;
button.addEventListener('click', () => turn(!card.hasAttribute('data-flipped')));
});
});
// Season comparison (sections/compare): dragging or tapping moves the dividing line, the hidden range input
// ([data-compare-range]) does the same by keyboard. Once in view, the line sweeps briefly to show it can be moved.
document.querySelectorAll('[data-compare]').forEach((box) => {
const range = box.querySelector('[data-compare-range]');
let touched = false;
const set = (percent) => {
const value = Math.min(100, Math.max(0, percent));
box.style.setProperty('--split', `${value}%`);
range.value = String(Math.round(value));
};
const fromPointer = (event) => {
const rect = box.getBoundingClientRect();
set(((event.clientX - rect.left) / rect.width) * 100);
};
range.hidden = false;
range.addEventListener('input', () => { touched = true; set(Number(range.value)); });
box.addEventListener('pointerdown', (event) => {
touched = true;
box.setPointerCapture(event.pointerId);
fromPointer(event);
});
box.addEventListener('pointermove', (event) => {
if (box.hasPointerCapture(event.pointerId)) {
fromPointer(event);
}
});
if (reducedMotion() || !('IntersectionObserver' in window)) {
return;
}
const hint = new IntersectionObserver(([entry]) => {
if (!entry.isIntersecting) {
return;
}
hint.disconnect();
const keys = [[0, 50], [0.35, 68], [0.75, 34], [1, 50]];
const duration = 2200;
let begin = null;
const step = (time) => {
if (touched) {
return;
}
begin ??= time;
const t = Math.min(1, (time - begin) / duration);
const k = keys.findIndex(([at]) => at >= t);
const [t0, v0] = keys[Math.max(0, k - 1)];
const [t1, v1] = keys[k];
const local = t1 === t0 ? 1 : (t - t0) / (t1 - t0);
set(v0 + (v1 - v0) * (0.5 - Math.cos(Math.PI * local) / 2));
if (t < 1) {
requestAnimationFrame(step);
}
};
setTimeout(() => requestAnimationFrame(step), 400);
}, { threshold: 0.6 });
hint.observe(box);
});