Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support custom attributes for external links in markdown #356

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions lib/markdown/link.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// markdown-it plugin for:
// 1. adding target="_blank" to external links
// 2. converting internal links to <router-link>
const querystring = require('querystring')

module.exports = md => {
let hasOpenRouterLink = false
Expand All @@ -10,12 +11,30 @@ module.exports = md => {
const hrefIndex = token.attrIndex('href')
if (hrefIndex >= 0) {
const link = token.attrs[hrefIndex]
const href = link[1]
// resolve link query params
let href = link[1].trim()
let query
if (href.startsWith('(')) {
const queryEndIndex = href.indexOf(')')
link[1] = href.slice(queryEndIndex + 1)
query = href.slice(1, queryEndIndex)
href = link[1]
}
const queryOb = querystring.parse(query)
const isExternal = /^https?:/.test(href)
const isSourceLink = /(\/|\.md|\.html)(#.*)?$/.test(href)
if (isExternal) {
addAttr(token, 'target', '_blank')
addAttr(token, 'rel', 'noopener noreferrer')
for (const attrKey in queryOb) {
if (queryOb[attrKey].length) {
addAttr(token, attrKey, queryOb[attrKey])
}
}
if (queryOb.target === undefined) {
addAttr(token, 'target', '_blank')
}
if (queryOb.rel === undefined) {
addAttr(token, 'rel', 'noopener noreferrer')
}
} else if (isSourceLink) {
hasOpenRouterLink = true
tokens[idx] = toRouterLink(token, link)
Expand Down Expand Up @@ -64,3 +83,4 @@ function addAttr (token, name, val) {
token.attrs[targetIndex][1] = val
}
}