rvx
Version:
A signal based rendering library
54 lines • 1.71 kB
JavaScript
import { ENV } from "../core/env.js";
import { teardown } from "../core/lifecycle.js";
import { $, batch } from "../core/signals.js";
import { normalize } from "./path.js";
import { Query } from "./query.js";
export class HashRouter {
#env = ENV.current;
#path = $(undefined);
#query = $(undefined);
constructor(options) {
const env = this.#env;
const parseEvents = options?.parseEvents ?? ["hashchange"];
const parse = this.parse.bind(this);
for (const name of parseEvents) {
env.window.addEventListener(name, parse, { passive: true });
teardown(() => env.window.removeEventListener(name, parse));
}
this.parse();
}
parse() {
batch(() => {
const hash = this.#env.location.hash.slice(1);
const queryStart = hash.indexOf("?");
if (queryStart < 0) {
this.#path.value = normalize(hash);
this.#query.value = undefined;
}
else {
this.#path.value = normalize(hash.slice(0, queryStart));
this.#query.value = new Query(hash.slice(queryStart + 1));
}
});
}
;
get root() {
return this;
}
get parent() {
return undefined;
}
get path() {
return this.#path.value;
}
get query() {
return this.#query.value;
}
push(path, query) {
this.#env.location.hash = `#${normalize(path)}${query === undefined ? "" : `?${typeof query === "string" ? query : new URLSearchParams(query)}`}`;
}
replace(path, query) {
this.push(path, query);
}
}
//# sourceMappingURL=hash-router.js.map