opendash
Version:
open.DASH data visualization framework
92 lines • 3.44 kB
JavaScript
import * as React from "react";
import { equals, useHref } from "..";
import { useNavigate } from "react-router-dom";
import rison from "rison";
export function useUrlParam(param, defaultValue, type) {
if (type === void 0) { type = "any"; }
var href = useHref();
var navigate = useNavigate();
var _a = React.useState(getParam(href, param, type) || defaultValue), state = _a[0], setState = _a[1];
React.useEffect(function () {
setState(getParam(href, param, type) || defaultValue);
}, [href, param]);
var updateParam = React.useCallback(function (nextValue) {
setParam(navigate, href, param, nextValue, defaultValue, type);
}, [href, param]);
return React.useMemo(function () { return [state, updateParam]; }, [state, updateParam]);
}
function getParam(href, param, type) {
var url = new URL(href);
var value = url.searchParams.get(param);
if (!value) {
return null;
}
return decode(value, type);
}
function setParam(navigate, href, param, value, defaultValue, type) {
var current = window.location.search;
var next = !value || equals(value, defaultValue)
? updateQueryString(current, param, undefined)
: updateQueryString(current, param, encode(value, type));
if (!equals(current, next)) {
navigate(next || "?");
}
}
function decode(value, type) {
switch (type) {
case "string":
return value;
case "object":
return rison.decode_object(JSON.parse(JSON.stringify(value)));
case "array":
return rison.decode_array(JSON.parse(JSON.stringify(value)));
case "json":
return JSON.parse(value);
case "any":
default:
return rison.decode(JSON.parse(JSON.stringify(value)));
}
}
function encode(value, type) {
switch (type) {
case "string":
return value;
case "object":
return rison.encode_object(JSON.parse(JSON.stringify(value)));
case "array":
return rison.encode_array(JSON.parse(JSON.stringify(value)));
case "json":
return encodeURIComponent(JSON.stringify(value));
case "any":
default:
return rison.encode(JSON.parse(JSON.stringify(value)));
}
}
function updateQueryString(current, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi");
var hash;
if (re.test(current)) {
if (typeof value !== "undefined" && value !== null)
return current.replace(re, "$1" + key + "=" + value + "$2$3");
else {
hash = current.split("#");
current = hash[0].replace(re, "$1$3").replace(/(&|\?)$/, "");
if (typeof hash[1] !== "undefined" && hash[1] !== null)
current += "#" + hash[1];
return current;
}
}
else {
if (typeof value !== "undefined" && value !== null) {
var separator = current.indexOf("?") !== -1 ? "&" : "?";
hash = current.split("#");
current = hash[0] + separator + key + "=" + value;
if (typeof hash[1] !== "undefined" && hash[1] !== null)
current += "#" + hash[1];
return current;
}
else
return current;
}
}
//# sourceMappingURL=useUrlParam.js.map