upend/webui/src/util/history.ts

46 lines
1.1 KiB
TypeScript
Raw Normal View History

2021-11-11 23:37:42 +01:00
import { createHashHistory } from "history";
import type { HistorySource } from "svelte-navigator";
2021-12-12 14:38:34 +01:00
export default function (): HistorySource {
const history = createHashHistory({ window });
let listeners = [];
2021-11-11 23:37:42 +01:00
2021-12-12 14:38:34 +01:00
history.listen((location) => {
if (history.action === "POP") {
listeners.forEach((listener) => listener(location));
}
});
2021-11-11 23:37:42 +01:00
2021-12-12 14:38:34 +01:00
return {
get location() {
return history.location as any;
},
addEventListener(name, handler) {
if (name !== "popstate") return;
listeners.push(handler);
},
removeEventListener(name, handler) {
if (name !== "popstate") return;
listeners = listeners.filter((fn) => fn !== handler);
},
history: {
get state() {
2022-01-28 20:39:00 +01:00
return history.location.state as object;
2021-12-12 14:38:34 +01:00
},
pushState(state, title, uri) {
history.push(uri, state);
},
replaceState(state, title, uri) {
history.replace(uri, state);
},
go(to) {
history.go(to);
},
},
};
}
2021-12-12 14:39:08 +01:00
export function normUrl(url: string) {
return `/#${url.startsWith("/") ? "" : "/"}${url}`;
}