mirror of
https://seed.radicle.dev/rad:z4V1sjrXqjvFdnCUbxPFqd5p4DtH5.git
synced 2026-11-13 18:40:50 +08:00
Improve canonicalize fn, add unit tests
Signed-off-by: Sebastian Martinez <me@sebastinez.dev>
This commit is contained in:
@@ -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
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user