upend/webui/src/util/history.ts
2022-01-13 19:02:08 +01:00

45 lines
1.1 KiB
TypeScript

import { createHashHistory } from "history";
import type { HistorySource } from "svelte-navigator";
export default function (): HistorySource {
const history = createHashHistory({ window });
let listeners = [];
history.listen((location) => {
if (history.action === "POP") {
listeners.forEach((listener) => listener(location));
}
});
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() {
return history.location.state;
},
pushState(state, title, uri) {
history.push(uri, state);
},
replaceState(state, title, uri) {
history.replace(uri, state);
},
go(to) {
history.go(to);
},
},
};
}
export function normUrl(url: string) {
return `/#${url.startsWith("/") ? "" : "/"}${url}`;
}