52 lines
1.5 KiB
JavaScript
52 lines
1.5 KiB
JavaScript
// modules/core/navigateTo.js
|
|
import { getPrefetched } from './ClickManager.js';
|
|
|
|
/**
|
|
* Funktion für SPA-Navigation mit optionaler ViewTransition
|
|
* Diese Funktion kann als generische Utility überall eingebunden werden!
|
|
*
|
|
* @param {string} href - Die Ziel-URL
|
|
* @param {object} options - Steueroptionen
|
|
* @param {boolean} [options.replace=false] - history.replaceState statt push
|
|
* @param {boolean} [options.viewTransition=false] - ViewTransition API verwenden
|
|
* @param {Function} [options.onUpdate] Wird nach Laden des HTML aufgerufen (html)
|
|
* @param {Function} [options.getPrefetched] Funktion zum Abrufen gecachter Daten (optional)
|
|
*/
|
|
export async function navigateTo(href, options = {}) {
|
|
const {
|
|
replace = false,
|
|
viewTransition = false,
|
|
onUpdate = html => {},
|
|
getPrefetched = null
|
|
/*onUpdate = (html) => {
|
|
const container = document.querySelector('main');
|
|
if (container) container.innerHTML = html;
|
|
}*/
|
|
} = options;
|
|
|
|
const fetchHtml = async () => {
|
|
|
|
let html = '';
|
|
if(getPrefetched) {
|
|
html = getPrefetched(href) || '';
|
|
}
|
|
|
|
if(!html) {
|
|
html = await fetch(href).then(r => r.text());
|
|
}
|
|
|
|
onUpdate(html);
|
|
if(replace) {
|
|
history.replaceState(null, '', href);
|
|
} else {
|
|
history.pushState(null, '', href);
|
|
}
|
|
};
|
|
|
|
if (viewTransition && document.startViewTransition) {
|
|
document.startViewTransition(fetchHtml);
|
|
} else {
|
|
await fetchHtml();
|
|
}
|
|
}
|