fix: errors loading relative path img URLs

This commit is contained in:
Corbin Crutchley
2021-11-30 07:12:02 -08:00
parent 773cf54e50
commit 3b45934490
3 changed files with 17 additions and 13 deletions

View File

@@ -1,4 +1,6 @@
import urljoin from "url-join";
import {join} from "path";
import slash from "slash";
/**
* Matches:
@@ -11,17 +13,11 @@ export const absolutePathRegex = /^(?:[a-z]+:)?\/\//;
export const isRelativePath = (str: string) => {
const isAbsolute = absolutePathRegex.exec(str);
if (isAbsolute) return false;
// Matches simple `test.png` links
const simpleRelativePath = /^\w/.exec(str);
return str.startsWith('./') || str.startsWith('/') || (
simpleRelativePath
)
return true;
}
export const getFullRelativePath = (slug: string, srcStr: string) => {
if (srcStr.startsWith('./')) srcStr = srcStr.slice(2);
return isRelativePath(srcStr) && !srcStr.startsWith('/') ?
// URLJoin doesn't seem to handle the `./` well
urljoin('/posts', slug, srcStr)
return isRelativePath(srcStr) ?
slash(join('/posts', slug, srcStr))
: srcStr
}