46 lines
1.9 KiB
JavaScript
46 lines
1.9 KiB
JavaScript
import { isServer } from "solid-js/web";
|
|
import { createRouter, scrollToHash, bindEvent } from "./createRouter.js";
|
|
import { StaticRouter } from "./StaticRouter.js";
|
|
import { setupNativeEvents } from "../data/events.js";
|
|
import { createBeforeLeave, keepDepth, notifyIfNotBlocked, saveCurrentDepth } from "../lifecycle.js";
|
|
export function Router(props) {
|
|
if (isServer)
|
|
return StaticRouter(props);
|
|
const getSource = () => {
|
|
const url = window.location.pathname.replace(/^\/+/, "/") + window.location.search;
|
|
const state = window.history.state && window.history.state._depth && Object.keys(window.history.state).length === 1 ? undefined : window.history.state;
|
|
return {
|
|
value: url + window.location.hash,
|
|
state
|
|
};
|
|
};
|
|
const beforeLeave = createBeforeLeave();
|
|
return createRouter({
|
|
get: getSource,
|
|
set({ value, replace, scroll, state }) {
|
|
if (replace) {
|
|
window.history.replaceState(keepDepth(state), "", value);
|
|
}
|
|
else {
|
|
window.history.pushState(state, "", value);
|
|
}
|
|
scrollToHash(decodeURIComponent(window.location.hash.slice(1)), scroll);
|
|
saveCurrentDepth();
|
|
},
|
|
init: notify => bindEvent(window, "popstate", notifyIfNotBlocked(notify, delta => {
|
|
if (delta) {
|
|
return !beforeLeave.confirm(delta);
|
|
}
|
|
else {
|
|
const s = getSource();
|
|
return !beforeLeave.confirm(s.value, { state: s.state });
|
|
}
|
|
})),
|
|
create: setupNativeEvents({ preload: props.preload, explicitLinks: props.explicitLinks, actionBase: props.actionBase, transformUrl: props.transformUrl }),
|
|
utils: {
|
|
go: delta => window.history.go(delta),
|
|
beforeLeave
|
|
}
|
|
})(props);
|
|
}
|