From 6a7ffc41c6051cd4d3a13d013aff3eb87c7dd7a7 Mon Sep 17 00:00:00 2001 From: jlpereira Date: Mon, 2 Oct 2023 18:28:01 -0300 Subject: [PATCH] Update markdown plugin --- src/plugins/markdown/relativeToRouter.js | 35 +++++++++++++++++++++--- vite.config.js | 4 +-- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/plugins/markdown/relativeToRouter.js b/src/plugins/markdown/relativeToRouter.js index 8fa9ebb..92ee120 100644 --- a/src/plugins/markdown/relativeToRouter.js +++ b/src/plugins/markdown/relativeToRouter.js @@ -1,4 +1,22 @@ -export function relativeToRouterPlugin(md) { +export function relativeToRouterPlugin(md, configuration) { + const isStaticAsset = (url) => { + const regex = /\.\w+$/ + + return regex.test(url) + } + + const makeUrlToStaticAsset = (url) => { + const baseUrl = configuration.base_url || '' + + return (baseUrl + url).replaceAll('//', '/') + + if (!url.startsWith('/')) { + return (baseUrl + url).replaceAll('//', '/') + } else { + return url + } + } + const scan = (state) => { state.tokens.forEach((tokens) => { if (tokens.type !== 'inline') { @@ -13,14 +31,23 @@ export function relativeToRouterPlugin(md) { } else if (inlineTokens[i].type === 'link_open') { const attrs = inlineTokens[i].attrs const href = attrs?.find((v) => v[0] === 'href') + if ( href && !href[1].startsWith('http') && !href[1].startsWith('mailto') ) { - inlineTokens[i].tag = 'router-link' - inlineTokens[i].attrs = [['to', href[1]]] - isRT = true + if (isStaticAsset(href[1])) { + inlineTokens[i].attrs.push([ + 'href', + makeUrlToStaticAsset(href[1]) + ]) + inlineTokens[i].attrs.push(['target', '_blank']) + } else { + inlineTokens[i].tag = 'router-link' + inlineTokens[i].attrs = [['to', href[1]]] + isRT = true + } } else { inlineTokens[i].attrs.push(['rel', 'noopener noreferrer']) inlineTokens[i].attrs.push(['target', '_blank']) diff --git a/vite.config.js b/vite.config.js index e734819..cca6049 100644 --- a/vite.config.js +++ b/vite.config.js @@ -38,8 +38,8 @@ export default () => { md.use(variableReplacementPlugin, { variables: { ...configuration } }) - }, - markdownItUses: [relativeToRouterPlugin] + md.use(relativeToRouterPlugin, configuration) + } }), Pages({