UNPKG

1.56 kBJavaScriptView Raw
1/**
2 * react-router v8.2.0
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11//#region lib/href.ts
12function stringify(p) {
13 return p == null ? "" : typeof p === "string" ? p : String(p);
14}
15/**
16Returns a resolved URL path for the specified route.
17
18```tsx
19const h = href("/:lang?/about", { lang: "en" })
20// -> `/en/about`
21
22<Link to={href("/products/:id", { id: "abc123" })} />
23```
24*/
25function href(path, ...args) {
26 let params = args[0];
27 let result = trimTrailingSplat(path).replace(/\/:([\w-]+)(\?)?/g, (_, param, questionMark) => {
28 const isRequired = questionMark === void 0;
29 const value = params?.[param];
30 if (isRequired && value === void 0) throw new Error(`Path '${path}' requires param '${param}' but it was not provided`);
31 return value == null ? "" : "/" + encodeURIComponent(stringify(value));
32 });
33 if (path.endsWith("*")) {
34 const value = params?.["*"];
35 if (value !== void 0) result += "/" + stringify(value).split("/").map(encodeURIComponent).join("/");
36 }
37 return result || "/";
38}
39/**
40* Removes a trailing splat and any number of slashes from the end of the path.
41*
42* Benchmarked to be faster than `path.replace(/\/*\*?$/, "")`, which backtracks.
43*/
44function trimTrailingSplat(path) {
45 let i = path.length - 1;
46 let char = path[i];
47 if (char !== "*" && char !== "/") return path;
48 i--;
49 for (; i >= 0; i--) if (path[i] !== "/") break;
50 return path.slice(0, i + 1);
51}
52//#endregion
53export { href };