traxxx-web/src/navigate.js

25 lines
867 B
JavaScript

import events from './events.js';
export default function navigate(path, query, options = {}) {
const curatedQuery = Object.fromEntries(Object.entries(query || {}).map(([key, value]) => (value === undefined ? null : [key, value])).filter(Boolean));
const queryString = new URLSearchParams({
...(options.preserveQuery ? Object.fromEntries(new URL(window.location).searchParams.entries()) : {}),
...curatedQuery,
}).toString();
const url = queryString
? `${path}?${queryString.replace(/%2C/g, ',')}` // URLSearchParams encodes commas, we don't want that
: path;
if (options.redirect) {
window.location.href = url;
} else if (options.replace) {
history.replaceState({}, '', url); // eslint-disable-line no-restricted-globals
} else {
history.pushState({}, '', url); // eslint-disable-line no-restricted-globals
}
events.emit('route', url);
}