alinea
Version:
[](https://npmjs.org/package/alinea) [](https://packagephobia.com/result?p=alinea)
103 lines (101 loc) • 2.5 kB
JavaScript
import {
useAtom,
useAtomValue,
useSetAtom
} from "../../chunks/chunk-WF77DMLN.js";
import {
atomFamily
} from "../../chunks/chunk-ZHH24SIG.js";
import {
atom
} from "../../chunks/chunk-OBOPLPUQ.js";
import {
parse
} from "../../chunks/chunk-MOB7XDEU.js";
import "../../chunks/chunk-U5RRZUYZ.js";
// src/dashboard/atoms/LocationAtoms.ts
import { values } from "alinea/core/util/Objects";
var browser = {
get location() {
return globalThis?.location ?? { hash: "" };
}
};
var hashAtom = atom(
browser.location.hash,
(get, set, hash) => {
if (get(hashAtom) !== hash)
browser.location.hash = hash;
set(hashAtom, hash);
}
);
hashAtom.onMount = (set) => {
const listener = () => set(browser.location.hash);
window.addEventListener("hashchange", listener);
return () => window.removeEventListener("hashchange", listener);
};
var locationAtom = atom(
(get) => {
const hash = get(hashAtom);
const path = hash.slice(1) || "/";
return new URL(path, browser.location.href);
},
(get, set, url) => {
const hash = `#${url}`;
set(hashAtom, hash);
}
);
function createParams(matcher, match) {
const params = {};
if (matcher.keys)
for (let i = 0; i < matcher.keys.length; i++)
params[matcher.keys[i]] = match[i + 1];
return params;
}
var matchAtoms = atomFamily(
({ route, loose }) => {
let current;
const matcher = parse(route, loose);
return atom((get) => {
const location = get(locationAtom);
const match = matcher.pattern.exec(location.pathname);
if (match === null)
return void 0;
const result = createParams(matcher, match);
if (current) {
const resultValues = values(result);
const currentValues = values(current);
if (resultValues.every((v, i) => v === currentValues[i]))
return current;
}
return current = result;
});
},
(a, b) => a.route === b.route && a.loose === b.loose
);
function useMatch(route, loose) {
return useAtom(matchAtoms({ route, loose }));
}
var useHash = () => useAtom(hashAtom);
function useLocation() {
return useAtomValue(locationAtom);
}
function useNavigate() {
const setLocation = useSetAtom(locationAtom);
return function navigate(url) {
setLocation(url);
};
}
function link(url) {
return typeof url === "string" ? { href: `#${url}` } : {};
}
export {
createParams,
hashAtom,
link,
locationAtom,
matchAtoms,
useHash,
useLocation,
useMatch,
useNavigate
};