-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathRouter.ts
More file actions
68 lines (66 loc) · 1.92 KB
/
Router.ts
File metadata and controls
68 lines (66 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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 type { BaseRouterProps } from "./components.jsx";
import type { JSX } from "solid-js";
import {
createBeforeLeave,
keepDepth,
notifyIfNotBlocked,
saveCurrentDepth
} from "../lifecycle.js";
export type RouterProps = BaseRouterProps & {
url?: string;
actionBase?: string;
explicitLinks?: boolean;
preload?: boolean;
};
export function Router(props: RouterProps): JSX.Element {
if (isServer) return StaticRouter(props);
const getSource = () => {
const url = window.location.pathname.replace(/^\/+/, "/") + window.location.search;
return {
value: props.transformUrl
? props.transformUrl(url) + window.location.hash
: url + window.location.hash,
state: window.history.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 && delta < 0) {
return !beforeLeave.confirm(delta);
} else {
const s = getSource();
return !beforeLeave.confirm(s.value, { state: s.state });
}
})
),
create: setupNativeEvents(
props.preload,
props.explicitLinks,
props.actionBase,
props.transformUrl
),
utils: {
go: delta => window.history.go(delta),
beforeLeave
}
})(props);
}