@koordinates/xstate-tree
Version:
Build UIs with Actors using xstate and React
40 lines (39 loc) • 1.21 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.matchRoute = void 0;
/**
* @public
*/
function matchRoute(routes, basePath, path, search) {
const realBase = basePath.endsWith("/") ? basePath.slice(0, -1) : basePath;
const realPath = (() => {
if (path.startsWith(realBase) && realBase.length > 0) {
return path.substring(realBase.length);
}
return path;
})();
const [matchingRoute, event] = routes
.map((route) => {
try {
const match = route.matches(realPath, search);
if (match) {
return [route, match];
}
}
catch (e) {
if (e instanceof Error) {
return [e, undefined];
}
}
return [undefined, undefined];
})
.find(([match]) => Boolean(match)) ?? [undefined, undefined];
if (matchingRoute === undefined) {
return { type: "no-matches" };
}
else if (matchingRoute instanceof Error) {
return { type: "match-error", error: matchingRoute };
}
return { type: "matched", route: matchingRoute, event: event };
}
exports.matchRoute = matchRoute;