UNPKG

@westacks/vortex

Version:

Server-based routing for SPAs

72 lines (71 loc) 2.36 kB
import { g as getPage, s as setPage } from "./page-ILOxo6kg.js"; import http from "axios"; let axios; const popstate = (event) => { if (!event.state) return; setPage(event.state.page); }; function install(...extensions) { if (!axios) throw new Error("Router not initialized!"); const uninstall = extensions.reduce((acc, x) => { const extension = x(axios.interceptors); if ((extension == null ? void 0 : extension.name) && typeof window !== "undefined") { window.dispatchEvent(new CustomEvent(`vortex:extension-installed`, { detail: extension.name })); } acc.request = [...acc.request, ...(extension == null ? void 0 : extension.request) ? [extension.request] : []]; acc.response = [...acc.response, ...(extension == null ? void 0 : extension.response) ? [extension.response] : []]; return acc; }, { request: [], response: [] }); return () => { uninstall.request.forEach((x) => axios == null ? void 0 : axios.interceptors.request.eject(x)); uninstall.response.forEach((x) => axios == null ? void 0 : axios.interceptors.response.eject(x)); }; } function createRouter() { var _a; axios = http.create(); axios.reload = function(config) { var _a2; return this({ url: (_a2 = getPage()) == null ? void 0 : _a2.url, ...config }); }; window.history.replaceState({ page: getPage() }, "", (_a = getPage()) == null ? void 0 : _a.url); window.addEventListener("popstate", popstate); axios.defaults.withCredentials = true; axios.defaults.vortex = true; } function destroyRouter() { window.removeEventListener("popstate", popstate); axios = void 0; } function link(node, options = {}) { function mergeOptions(options2) { options2.method = options2.method || "get"; options2.url = options2.url || node.href || ""; options2.data = options2.data || {}; if (node instanceof HTMLAnchorElement) { node.href = options2.url; } return options2; } function navigate(event) { event.preventDefault(); axios(options); } options = mergeOptions(options); node.addEventListener("click", navigate); return { update(newOptions) { options = mergeOptions(newOptions); }, destroy() { node.removeEventListener("click", navigate); } }; } export { axios as a, createRouter as c, destroyRouter as d, install as i, link as l };