1
Fork 0
svelte-dynamic-router/src/components/Router.html

40 lines
1.1 KiB
HTML

<script context='module'>
export const ROUTER = {};
</script>
<script>
import { setContext, onDestroy } from 'svelte';
import { writable } from 'svelte/store';
const pathname = writable(document.location.pathname);
const go = (url, replace) => {
history[replace ? 'replaceState' : 'pushState'](null, '', location.origin + url);
pathname.set(url);
};
setContext(ROUTER, { pathname, go });
const clickHandler = event => {
if (!event.ctrlKey && !event.metaKey && !event.shiftKey && event.which === 1) {
const elm = event.target.closest('a');
if (elm && !elm.target) {
const url = elm.href;
if (url.startsWith(document.location.origin + '/')) {
event.preventDefault();
go(url.slice(document.location.origin.length));
}
}
}
};
document.addEventListener('click', clickHandler);
const popstateHandler = () => pathname.set(document.location.pathname);
window.addEventListener('popstate', popstateHandler);
onDestroy(() => {
document.removeEventListener('click', clickHandler);
window.removeEventListener('popstate', popstateHandler);
});
</script>
<slot/>