Skip to content

Commit

Permalink
feat(router): add hook
Browse files Browse the repository at this point in the history
  • Loading branch information
aidenybai committed Apr 28, 2022
1 parent ed165f5 commit b1b6dee
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 63 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@
"@types/benchmark": "^2.1.1",
"@types/canvas-confetti": "^1.4.2",
"@types/lodash": "^4.14.182",
"@types/node": "^17.0.29",
"@types/node": "^17.0.30",
"@types/virtual-dom": "^2.1.1",
"@typescript-eslint/eslint-plugin": "^5.21.0",
"@typescript-eslint/parser": "^5.21.0",
Expand Down Expand Up @@ -147,7 +147,7 @@
"source-map": "^0.7.3",
"taze": "^0.5.0",
"tslib": "^2.4.0",
"typescript": "^4.6.3",
"typescript": "^4.6.4",
"unbuild": "^0.7.4",
"virtual-dom": "^2.1.1",
"vite": "^2.9.6",
Expand Down
18 changes: 11 additions & 7 deletions packages/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,17 @@ export const navigate = async (url: URL, opts?: RequestInit, goBack = false): Pr
}
};

export const router = (routes?: Record<string, VElement>): Controller => {
export const router = (
routes: Record<string, VElement> = {},
hook: (url: URL) => boolean = () => true,
): Controller => {
for (const route in routes) {
routeMap.set(route, routes[route]);
}

window.addEventListener('click', (event) => {
const url = getURL(event);
if (!url) return;
if (!url || !hook(url)) return;
event.preventDefault();
try {
navigate(url);
Expand All @@ -75,7 +78,7 @@ export const router = (routes?: Record<string, VElement>): Controller => {

window.addEventListener('mouseover', async (event) => {
const url = getURL(event);
if (!url) return;
if (!url || !hook(url)) return;
event.preventDefault();
if (routeMap.has(url.pathname)) return;
const content = await getContent(url);
Expand All @@ -94,16 +97,17 @@ export const router = (routes?: Record<string, VElement>): Controller => {
event.stopPropagation();
event.preventDefault();

const el = event.target;
if (!(el instanceof HTMLFormElement)) return;
const el = event.target as HTMLFormElement;
const url = new URL(el.action);
if (!el.action || !hook(url) || !(el instanceof HTMLFormElement)) return;

const formData = new FormData(el);
const body = {};
formData.forEach((value, key) => {
body[key] = value;
});

navigate(new URL(el.action), {
navigate(url, {
method: el.method,
redirect: 'follow',
body:
Expand All @@ -114,8 +118,8 @@ export const router = (routes?: Record<string, VElement>): Controller => {
});

window.addEventListener('popstate', () => {
if (window.location.hash) return;
const url = new URL(window.location.toString());
if (window.location.hash || !hook(url)) return;
try {
navigate(url, {}, true);
} catch (e) {
Expand Down

0 comments on commit b1b6dee

Please sign in to comment.