'use strict';
/** Namespace common functions to parse and manipulate URLs
* @module locationTools
*/
//
// Utility
//
/** Manipulate/parse the location bar of the browser
*
* This is here because we have a couple of places where we want to remove
* query parameters from the location bar. This simplifies and helps us
* maintain DRY.
*
* I call this `LocationTools`, because I do not want to call it simply `Location`,
* because that seems woefully prone to naming colission.
*/
class LocationTools {
/* eslint-disable class-methods-use-this */
/** Remove query parameters from the location bar
*
* (This is done via the `history` object)
*/
removeParams(...remove) {
const params = new URLSearchParams(window.location.search);
remove.forEach(param => params.delete(param));
const query = params.toString();
// Only add the `?` if there are items in our parsed dictionary
const locationQuery = (query !== '') ? '?' + query : ''; // eslint-disable-line no-negated-condition
const url =
location.origin +
location.pathname +
locationQuery +
location.hash;
history.replaceState({}, '', url);
}
/* eslint-enable */
/* eslint-disable class-methods-use-this */
/** Get the current location without hash
* @return {external:Location#hrefSansHash}
*/
uriAndQueryString() {
return location.origin +
location.pathname +
location.search;
}
/* eslint-enable */
/* eslint-disable class-methods-use-this */
/** Get query parameters string after the initial "?"
* Chiefly used to set cookies later read by our backend
* @return {string}
*/
noQuestionSearchString() {
return window.location.search.indexOf('?') === 0 ?
window.location.search.substr(1) : window.location.search;
}
/* eslint-enable */
/* eslint-disable class-methods-use-this */
/** Return the domain (removes the subdomain from the domain)
* Note: this will not work if we ever use public suffixes such as co.uk
* If that is the case, we should use something like https://github.com/lupomontero/psl
* @return {string}
*/
domain() {
const splitDomain = window.location.hostname.split('.');
if (splitDomain.length > 2) splitDomain.shift();
return splitDomain.join('.');
}
/* eslint-enable */
}
/** Instance of the class of this module
* @type {module:locationTools~LocationTools}
*/
export const locationTools = new LocationTools();