Improve canonicalize fn, add unit tests

Signed-off-by: Sebastian Martinez <me@sebastinez.dev>
This commit is contained in:
Sebastian Martinez
2022-06-08 22:46:27 +02:00
parent a01edf4bec
commit 44376f7e4d
2 changed files with 24 additions and 3 deletions
+19
View File
@@ -274,3 +274,22 @@ describe("Parse Strings", () => {
).toEqual(expected);
});
});
describe("Path Manipulation", () => {
test.each([
{ imagePath: "/assets/images/tux.png", base: "/", origin: "https://app.radicle.network", expected: "assets/images/tux.png" },
{ imagePath: "assets/images/tux.png", base: "/", origin: "https://app.radicle.network", expected: "assets/images/tux.png" },
{ imagePath: "assets/images/tux.png", base: "/", origin: "http://localhost:3000", expected: "assets/images/tux.png" },
{ imagePath: "../tux.png", base: "/components/assets/README.md", origin: "http://localhost:3000", expected: "components/tux.png" },
{ imagePath: "../tux.png", base: "/components/assets/", origin: "http://localhost:3000", expected: "components/tux.png" },
{ imagePath: "../../tux.png", base: "/components/assets/images/README.md", origin: "http://localhost:3000", expected: "components/tux.png" },
])("canonicalize origin: $origin base: $base, path: $imagePath => $expected", ({ imagePath, base, expected, origin }) => {
expect(
utils.canonicalize(
imagePath,
base,
origin
)
).toEqual(expected);
});
});
+5 -3
View File
@@ -213,8 +213,10 @@ export function getImageMime(path: string): string | null {
return null;
}
// TODO: Needs testing with absolute and relative paths.
export function canonicalize(path: string, base: string): string {
// Takes a path, eg. "../images/image.png", and a base from where to start resolving, e.g. "static/images/index.html".
// Returns the resolved path.
export function canonicalize(path: string, base: string, origin = document.location.origin): string {
path = path.replace(/^\//, ""); // Remove leading slash
const finalPath = base
.split("/")
.slice(0, -1) // Remove file name.
@@ -222,7 +224,7 @@ export function canonicalize(path: string, base: string): string {
.join("/");
// URL is used to resolve relative paths, eg. `../../assets/image.png`.
const url = new URL(finalPath, document.location.origin);
const url = new URL(finalPath, origin);
const pathname = url.pathname.replace(/^\//, "");
return pathname;