Last active
May 4, 2021 10:01
-
-
Save joshcawthorne/4b50a9a5f56f4ff3c4fe939a42ad5a93 to your computer and use it in GitHub Desktop.
Util to parse Storyblok Links
This file contains hidden or 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
const nullLink = null; | |
function isValidFullSlug(link) { | |
return typeof link == "string" && link[0] !== "/"; | |
} | |
function parseStoryblokLink(link) { | |
if (!parseStoryblokLink.isValidUrl(link)) { | |
return nullLink; | |
} | |
if (link.url) { | |
if (link.anchor) { | |
return ( | |
"/" + link.url + "#" + link.anchor.replace(/\s/g, "").toLowerCase() | |
); | |
} | |
return link.url; | |
} | |
if (link.email) { | |
return "mailto:" + link.email; | |
} | |
if (link.cached_url) { | |
if (link.anchor) { | |
return ( | |
"/" + | |
link.cached_url + | |
"#" + | |
link.anchor.replace(/\s/g, "").toLowerCase() | |
); | |
} | |
return "/" + link.cached_url; | |
} | |
return `/${link}`; | |
} | |
parseStoryblokLink.isValidUrl = function (link) { | |
return ( | |
link && (link.url || link.email || link.cached_url || isValidFullSlug(link)) | |
); | |
}; | |
export default parseStoryblokLink; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment