Skip to content

Commit

Permalink
fix: make location configurable
Browse files Browse the repository at this point in the history
  • Loading branch information
jaulz authored Jun 4, 2021
1 parent 147804d commit cb0b469
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions src/js/Router.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default class Router extends String {
super();

this._config = config ?? Ziggy ?? globalThis?.Ziggy;
this._config = { ...this._config, absolute };
this._config = { location: {}, ...this._config, absolute };

if (name) {
if (!this._config.routes[name]) {
Expand Down Expand Up @@ -70,8 +70,8 @@ export default class Router extends String {
*/
current(name, params) {
const url = this._config.absolute
? window.location.host + window.location.pathname
: window.location.pathname.replace(this._config.url.replace(/^\w*:\/\/[^/]+/, ''), '').replace(/^\/+/, '/');
? this.location.host + this.location.pathname
: this.location.pathname.replace(this._config.url.replace(/^\w*:\/\/[^/]+/, ''), '').replace(/^\/+/, '/');

// Find the first route that matches the current URL
const [current, route] = Object.entries(this._config.routes).find(
Expand Down Expand Up @@ -100,6 +100,23 @@ export default class Router extends String {
return Object.entries(params).every(([key, value]) => routeParams[key] == value);
}

/**
* Get the current location
*
* @return {Object}
*/
get location() {
const defaultHost = typeof window === 'undefined' ? '' : window.location.host;
const defaultPathname = typeof window === 'undefined' ? '' : window.location.pathname;
const defaultSearch = typeof window === 'undefined' ? '' : window.location.search;

return {
host: this._config.location.host,
pathname: this._config.location.pathname,
search: this._config.location.search,
};
}

/**
* Get all parameter values from the current window URL.
*
Expand Down Expand Up @@ -223,7 +240,7 @@ export default class Router extends String {
* @return {Object} Parameters.
*/
_dehydrate(route) {
let pathname = window.location.pathname
let pathname = this.location.pathname
// If this Laravel app is in a subdirectory, trim the subdirectory from the path
.replace(this._config.url.replace(/^\w*:\/\/[^/]+/, ''), '')
.replace(/^\/+/, '');
Expand All @@ -244,9 +261,9 @@ export default class Router extends String {
}

return {
...dehydrate(window.location.host, route.domain, '.'), // Domain parameters
...dehydrate(this.location.host, route.domain, '.'), // Domain parameters
...dehydrate(pathname, route.uri, '/'), // Path parameters
...parse(window.location.search?.replace(/^\?/, '')), // Query parameters
...parse(this.location.search?.replace(/^\?/, '')), // Query parameters
};
}

Expand Down

0 comments on commit cb0b469

Please sign in to comment.