Skip to content

Commit

Permalink
Replace internal vars in markdown
Browse files Browse the repository at this point in the history
  • Loading branch information
jlpereira committed Aug 15, 2023
1 parent 0d2a236 commit c4b5c5f
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 4 deletions.
2 changes: 2 additions & 0 deletions src/plugins/markdown/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './relativeToRouter'
export * from './variableReplacement'
8 changes: 6 additions & 2 deletions src/plugins/markdown/relativeToRouter.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export default (md) => {
export function relativeToRouterPlugin(md) {
const scan = (state) => {
state.tokens.forEach((tokens) => {
if (tokens.type !== 'inline') {
Expand All @@ -13,7 +13,11 @@ export default (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')) {
if (
href &&
!href[1].startsWith('http') &&
!href[1].startsWith('mailto')
) {
inlineTokens[i].tag = 'router-link'
inlineTokens[i].attrs = [['to', href[1]]]
isRT = true
Expand Down
14 changes: 14 additions & 0 deletions src/plugins/markdown/variableReplacement.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export function variableReplacementPlugin(md, options) {
const regex = /{{\s*app:(.*?)\s*}}/g
const variables = options.variables || {}

md.core.ruler.before('normalize', 'variable_replacement', (state) => {
state.src = state.src.replace(regex, (match, content) => {
if (Object.hasOwn(variables, content)) {
return variables[content]
}

return match
})
})
}
10 changes: 8 additions & 2 deletions vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import path from 'path'
import Vue from '@vitejs/plugin-vue'
import Markdown from 'vite-plugin-md'
import markdownAnchor from 'markdown-it-anchor'
import markdownRelativeToRouter from './src/plugins/markdown/relativeToRouter.js'
import {
relativeToRouterPlugin,
variableReplacementPlugin
} from './src/plugins/markdown'
import Pages from 'vite-plugin-pages'
import './src/utils/globalVars'

Expand All @@ -31,8 +34,11 @@ export default () => {
'!container mx-auto p-4 sm:pl-0 sm:pr-0 prose dark:prose-invert box-border',
markdownItSetup(md) {
md.use(markdownAnchor)
md.use(variableReplacementPlugin, {
variables: { ...configuration }
})
},
markdownItUses: [markdownRelativeToRouter]
markdownItUses: [relativeToRouterPlugin]
}),
Pages({
dirs: 'pages',
Expand Down

0 comments on commit c4b5c5f

Please sign in to comment.