Radish alpha
r
Radicle web interface
Radicle
Git (anonymous pull)
Log in to clone via SSH
Improve canonicalize fn, add unit tests
Sebastian Martinez committed 3 years ago
commit 44376f7e4dbf17c6c9f3dfadfad48b461cf1d6e0
parent a01edf4bec32501da4f9d4b8e430a8a2d9f8a090
2 files changed +24 -3
modified 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);
+
  });
+
});
modified 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;