UNPKG

jotai-location

Version:
57 lines (56 loc) • 2.04 kB
import { atom } from 'jotai/vanilla'; const getLocation = () => { if (typeof window === 'undefined' || !window.location) { return {}; } return { pathname: window.location.pathname, searchParams: new URLSearchParams(window.location.search), hash: window.location.hash, }; }; const applyLocation = (location, options) => { const url = new URL(window.location.href); if ('pathname' in location) { url.pathname = location.pathname; } if ('searchParams' in location) { url.search = location.searchParams.toString(); } if ('hash' in location) { url.hash = location.hash; } if (options === null || options === void 0 ? void 0 : options.replace) { window.history.replaceState(window.history.state, '', url); } else { window.history.pushState(null, '', url); } }; const subscribe = (callback) => { window.addEventListener('popstate', callback); return () => window.removeEventListener('popstate', callback); }; export function atomWithLocation(options) { var _a; const getL = (options === null || options === void 0 ? void 0 : options.getLocation) || getLocation; const appL = (options === null || options === void 0 ? void 0 : options.applyLocation) || applyLocation; const sub = (options === null || options === void 0 ? void 0 : options.subscribe) || subscribe; const baseAtom = atom((_a = options === null || options === void 0 ? void 0 : options.preloaded) !== null && _a !== void 0 ? _a : getL()); if (process.env.NODE_ENV !== 'production') { baseAtom.debugPrivate = true; } baseAtom.onMount = (set) => { const callback = () => set(getL()); const unsub = sub(callback); callback(); return unsub; }; const derivedAtom = atom((get) => get(baseAtom), (get, set, arg, atomOptions = {}) => { set(baseAtom, arg); appL(get(baseAtom), { ...options, ...atomOptions }); }); return derivedAtom; }