(parser, route, path, loose)
| 87 | }; |
| 88 | |
| 89 | export const matchRoute = (parser, route, path, loose) => { |
| 90 | // if the input is a regexp, skip parsing |
| 91 | const { pattern, keys } = |
| 92 | route instanceof RegExp |
| 93 | ? { keys: false, pattern: route } |
| 94 | : parser(route || "*", loose); |
| 95 | |
| 96 | // array destructuring loses keys, so this is done in two steps |
| 97 | const result = pattern.exec(path) || []; |
| 98 | |
| 99 | // when parser is in "loose" mode, `$base` is equal to the |
| 100 | // first part of the route that matches the pattern |
| 101 | // (e.g. for pattern `/a/:b` and path `/a/1/2/3` the `$base` is `a/1`) |
| 102 | // we use this for route nesting |
| 103 | const [$base, ...matches] = result; |
| 104 | |
| 105 | return $base !== undefined |
| 106 | ? [ |
| 107 | true, |
| 108 | |
| 109 | (() => { |
| 110 | // for regex paths, `keys` will always be false |
| 111 | |
| 112 | // an object with parameters matched, e.g. { foo: "bar" } for "/:foo" |
| 113 | // we "zip" two arrays here to construct the object |
| 114 | // ["foo"], ["bar"] → { foo: "bar" } |
| 115 | const groups = |
| 116 | keys !== false |
| 117 | ? Object.fromEntries(keys.map((key, i) => [key, matches[i]])) |
| 118 | : result.groups; |
| 119 | |
| 120 | // convert the array to an instance of object |
| 121 | // this makes it easier to integrate with the existing param implementation |
| 122 | let obj = { ...matches }; |
| 123 | |
| 124 | // merge named capture groups with matches array |
| 125 | groups && Object.assign(obj, groups); |
| 126 | |
| 127 | return obj; |
| 128 | })(), |
| 129 | |
| 130 | // the third value if only present when parser is in "loose" mode, |
| 131 | // so that we can extract the base path for nested routes |
| 132 | ...(loose ? [$base] : []), |
| 133 | ] |
| 134 | : [false, null]; |
| 135 | }; |
| 136 | |
| 137 | export const useRoute = (pattern) => |
| 138 | matchRoute(useRouter().parser, pattern, useLocation()[0]); |
no test coverage detected
searching dependent graphs…