UNPKG

uno-react

Version:

Common functions, and hooks for React.

61 lines (60 loc) 2.62 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useUrlId = exports.buildUrl = exports.resetBaseUrl = exports.getBaseUrl = void 0; const React = __importStar(require("react")); const getBaseUrl = (windowLocation) => windowLocation.href.split('?')[0]; exports.getBaseUrl = getBaseUrl; const resetBaseUrl = (window) => window.history.pushState('', '', (0, exports.getBaseUrl)(window.location)); exports.resetBaseUrl = resetBaseUrl; const buildUrl = (keys, values) => { if (!values || !keys) return null; let url = (0, exports.getBaseUrl)(window.location); if (typeof keys !== 'object') return `${url}?${keys}=${values}`; keys.forEach((key, index) => { if (values[index] !== null) url = url.concat(`${index === 0 ? '?' : '&'}${key}=${values[index]}`); }); return url; }; exports.buildUrl = buildUrl; const useUrlId = (idName, window) => { const [getId, setId] = React.useState(null); React.useEffect(() => typeof idName === 'object' ? setId(idName.map((x) => new URLSearchParams(window.location.search).get(x))) : setId(new URLSearchParams(window.location.search).get(idName)), [idName, window.location.search]); React.useEffect(() => { if (getId !== null) window.history.pushState(null, null, (0, exports.buildUrl)(idName, getId)); }, [idName, window.location, window.history, getId]); const reset = () => { (0, exports.resetBaseUrl)(window); setId(null); }; return [getId, setId, reset]; }; exports.useUrlId = useUrlId;