From 44376f7e4dbf17c6c9f3dfadfad48b461cf1d6e0 Mon Sep 17 00:00:00 2001 From: Sebastian Martinez Date: Fri, 3 Jun 2022 13:38:56 +0200 Subject: [PATCH] Improve canonicalize fn, add unit tests Signed-off-by: Sebastian Martinez --- src/utils.test.ts | 19 +++++++++++++++++++ src/utils.ts | 8 +++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/utils.test.ts b/src/utils.test.ts index 5544b3fed..74828fcca 100644 --- a/src/utils.test.ts +++ b/src/utils.test.ts @@ -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); + }); +}); diff --git a/src/utils.ts b/src/utils.ts index c75ef6f4a..18454d5b6 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -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;