UNPKG

jotai-location

Version:
60 lines (59 loc) • 2.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.atomWithLocation = atomWithLocation; const vanilla_1 = require("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); }; 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 = (0, vanilla_1.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 = (0, vanilla_1.atom)((get) => get(baseAtom), (get, set, arg, atomOptions = {}) => { set(baseAtom, arg); appL(get(baseAtom), { ...options, ...atomOptions }); }); return derivedAtom; }