react-view-router
Version:
react-view-router
94 lines • 2.81 kB
JavaScript
import _toArray from "@babel/runtime/helpers/toArray";
import "core-js/modules/es6.regexp.replace.js";
import "core-js/modules/es6.object.to-string.js";
import "core-js/modules/es6.array.iterator.js";
import "core-js/modules/web.dom.iterable.js";
import "core-js/modules/es6.array.slice.js";
import { pathToRegexp } from 'path-to-regexp';
var cache = {};
var cacheLimit = 10000;
var cacheCount = 0;
function compilePath(path, options) {
var cacheKey = `${options.end}${options.strict}${options.sensitive}`;
var pathCache = cache[cacheKey] || (cache[cacheKey] = {});
if (pathCache[path]) return pathCache[path];
var keys = [];
var regx = pathToRegexp(path, keys, options);
var result = {
regx,
keys
};
if (cacheCount < cacheLimit) {
pathCache[path] = result;
cacheCount++;
}
return result;
}
/**
* Public API for matching a URL pathname to a path.
*/
function matchPath(pathname, options = {}) {
if (typeof options === 'string' || Array.isArray(options)) {
options = {
path: options
};
}
var _options = options,
subpath = _options.subpath,
_options$exact = _options.exact,
exact = _options$exact === void 0 ? false : _options$exact,
_options$strict = _options.strict,
strict = _options$strict === void 0 ? false : _options$strict,
_options$sensitive = _options.sensitive,
sensitive = _options$sensitive === void 0 ? false : _options$sensitive;
var _options2 = options,
_options2$path = _options2.path,
path = _options2$path === void 0 ? '' : _options2$path;
if (subpath === '*') {
path = path.replace(/\*$/, ':fallback([^\\/]*)');
}
var paths = [].concat(path || []);
return paths.reduce((matched, path) => {
if (!path && path !== '') return null;
if (matched) return matched;
var _compilePath = compilePath(path, {
end: exact,
strict,
sensitive
}),
regx = _compilePath.regx,
keys = _compilePath.keys;
var match = regx.exec(pathname);
if (!match) return null;
var _match = _toArray(match),
url = _match[0],
values = _match.slice(1);
var isExact = pathname === url;
if (exact && !isExact) return null;
return {
path,
// the path used to match
url: path === '/' && url === '' ? '/' : url,
// the matched portion of the URL
isExact,
// whether or not we matched exactly
regx,
params: keys.reduce((memo, key, index) => {
memo[key.name] = values[index];
return memo;
}, {})
};
}, null);
}
export function computeRootMatch(pathname = '/') {
return {
path: '/',
url: '/',
params: {},
regx: compilePath('/', {}),
isExact: pathname === '/',
isNull: true
};
}
export default matchPath;
//# sourceMappingURL=match-path.js.map