@ekwoka/alpine-history
Version:
Sync Component an Store values to the URL Search Params!!!
46 lines (43 loc) • 1.47 kB
JavaScript
import { isForbidden, insertDotNotatedValueIntoData } from './pathresolve.js';
const toQueryString = (data) => {
const entries = buildQueryStringEntries(data);
return entries.map((entry) => entry.join("=")).join("&");
};
const isObjectLike = (subject) => typeof subject === "object" && subject !== null;
const buildQueryStringEntries = (data, entries = [], baseKey = "") => {
Object.entries(data).forEach(([iKey, iValue]) => {
const key = baseKey ? `${baseKey}[${iKey}]` : iKey;
if (iValue === void 0)
return;
if (!isObjectLike(iValue))
entries.push([
key,
encodeURIComponent(iValue).replaceAll("%20", "+").replaceAll("%2C", ",")
]);
else
buildQueryStringEntries(iValue, entries, key);
});
return entries;
};
const fromQueryString = (queryString) => {
const data = /* @__PURE__ */ Object.create(null);
if (queryString === "")
return data;
const entries = new URLSearchParams(queryString).entries();
for (const [key, value] of entries) {
if (isForbidden(key))
continue;
if (!value)
continue;
const decoded = value;
if (!key.includes("["))
data[key] = decoded;
else {
const dotNotatedKey = key.replaceAll(/\[([^\]]+)\]/g, ".$1");
insertDotNotatedValueIntoData(dotNotatedKey, decoded, data);
}
}
return data;
};
export { buildQueryStringEntries, fromQueryString, isObjectLike, toQueryString };
//# sourceMappingURL=querystring.js.map