Adds internal and external links

This commit is contained in:
Corbin Crutchley
2021-11-29 09:34:58 -08:00
parent bdbfb3ae7d
commit a082741861
4 changed files with 44 additions and 5 deletions

View File

@@ -1,12 +1,26 @@
import urljoin from "url-join";
/**
* Matches:
* - ftp://
* - https://
* - //
*/
export const absolutePathRegex = /^(?:[a-z]+:)?\/\//;
export const isRelativePath = (str: string) => {
return str.startsWith('./') || /^\w/.exec(str);
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
)
}
export const getFullRelativePath = (slug: string, srcStr: string) => {
if (srcStr.startsWith('./')) srcStr = srcStr.slice(2);
return isRelativePath(srcStr) ?
return isRelativePath(srcStr) && !srcStr.startsWith('/') ?
// URLJoin doesn't seem to handle the `./` well
urljoin('/posts', slug, srcStr)
: srcStr