-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #189 from charlesLoder/fix-base-path
Update documentation site
- Loading branch information
Showing
3 changed files
with
87 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
// @ts-check | ||
import { CONTINUE, visit } from "unist-util-visit"; | ||
|
||
/** | ||
* Check if url is absolute | ||
* | ||
* @param {string} url | ||
* @returns {boolean} | ||
*/ | ||
function isAbsoluteUrl(url) { | ||
return url.startsWith("http://") || url.startsWith("https://"); | ||
} | ||
|
||
/** | ||
* Check if url is a heading link | ||
* | ||
* @param {string} url | ||
*/ | ||
function isHeadingLink(url) { | ||
return url.startsWith("#"); | ||
} | ||
|
||
/** | ||
* Check if node is a link node | ||
* | ||
*/ | ||
function isLinkNode(node) { | ||
return node.type === "link" && !!node.url; | ||
} | ||
|
||
/** | ||
* Check if url starts with base path | ||
* | ||
* @param {string} str | ||
* @param {string} base | ||
*/ | ||
function startsWithBasePath(str, base) { | ||
return str.startsWith(base); | ||
} | ||
|
||
export function remarkBasePath(options = {}) { | ||
const { base = "" } = options; | ||
|
||
return (tree) => { | ||
visit(tree, (node) => { | ||
// Handle link nodes | ||
if (isLinkNode(node)) { | ||
if (!isAbsoluteUrl(node.url) && !isHeadingLink(node.url) && !startsWithBasePath(node.url, base)) { | ||
node.url = `${base}${node.url}`; | ||
} | ||
return CONTINUE; | ||
} | ||
|
||
const hasAttrs = !!node.attributes && Array.isArray(node.attributes); | ||
if (!hasAttrs) { | ||
return; | ||
} | ||
const hasHref = node?.attributes?.find((a) => a.name === "href"); | ||
|
||
if (hasHref) { | ||
node.attributes = node.attributes.map((a) => { | ||
if ( | ||
a.name === "href" && | ||
!isAbsoluteUrl(a.value) && | ||
!isHeadingLink(a.value) && | ||
!startsWithBasePath(a.value, base) | ||
) { | ||
a.value = `${base}${a.value}`; | ||
return a; | ||
} | ||
return a; | ||
}); | ||
} | ||
}); | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters