/**
* This is the basic router for the Shark environment.
* <br>Fun Fuct: SwimWay is a name given by some researcher to a sort of route followd in the ocean by a great amount of Sharks.
* @constructor
* @param {string} [routingMethod=pathname] - The routing method used for this router: value could be one of pathname, url or hash.
*/
class SwimWay {
constructor (routingMethod = "pathname") {
this.routingMethod = routingMethod;
}
/**
* Parse the document.location properties and return the requested View in the URL.
*
* @returns {string} requestedView - The name of the View extracted from the current URL.
*/
getRequestedViewFromLocation () {
let requestedView = ["url", "pathname"].includes(this.routingMethod) ? document.location.pathname : document.location.hash;
if (requestedView !== "") {
requestedView = requestedView.slice(1);
}
return requestedView;
}
/**
* Set current URLSearchParams without creating a new state in browser's history.
*
* @param {strin|object|URLSearchParams} urlSearchParams - Could be a string, an object or a URLSearchParams instance.
*/
setURLSearchParams (urlSearchParams = null) {
//Dave: Devo gestire la possibilità che urlSearchParams sia un oggetto, nativo o URLSearchParams
const stateObj = {
// jawId: currJaw.className,
urlSearchParams,
};
const destinationURL = new URL(window.location);
// const destinationViewURL = currJaw.route || currJaw.className;
if (urlSearchParams === null) {
destinationURL.searchParams.forEach((val, key) => destinationURL.searchParams.delete(key));
}
else if (typeof urlSearchParams === "string" && urlSearchParams !== "") {
const urlParamsList = urlSearchParams.split("&");
urlParamsList.forEach(param => {
const params = param.split("=");
destinationURL.searchParams.set(params[0], params[1]);
});
}
else if (typeof urlSearchParams === "object") {
for (let param in urlSearchParams) {
destinationURL.searchParams.set(param, urlSearchParams[param]);
};
}
if (typeof history.replaceState === "function") {
//Qui c'è da gestire l'idea che il routing usi la forma nomeORouteView/parametro1/parametro2/parametro3 ecc...
if (["url", "pathname"].includes(this.routingMethod)) {
destinationURL.pathname = destinationURL.pathname.slice(0, destinationURL.pathname.lastIndexOf("/")) + "/" + destinationViewURL;
}
else {
destinationURL.hash = destinationViewURL;
}
history.replaceState(stateObj, "" /*currJaw.className*/, destinationURL);
}
}
}
export default SwimWay;