From 4f883ce61ccc1c3abb2c7f2fb7eb1f8411615424 Mon Sep 17 00:00:00 2001 From: ULIVZ <472590061@qq.com> Date: Tue, 8 May 2018 01:02:44 +0800 Subject: [PATCH 1/2] feat: support custom attributes for external links in markdown --- lib/markdown/link.js | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/lib/markdown/link.js b/lib/markdown/link.js index 969fedde75..b2f0bacaae 100644 --- a/lib/markdown/link.js +++ b/lib/markdown/link.js @@ -1,6 +1,7 @@ // markdown-it plugin for: // 1. adding target="_blank" to external links // 2. converting internal links to +const querystring = require('querystring') module.exports = md => { let hasOpenRouterLink = false @@ -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]) { + 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) @@ -64,3 +83,4 @@ function addAttr (token, name, val) { token.attrs[targetIndex][1] = val } } + From f16bcdacc6292247d1f42da9bbbdd4b79b5b7959 Mon Sep 17 00:00:00 2001 From: ULIVZ <472590061@qq.com> Date: Tue, 8 May 2018 01:11:44 +0800 Subject: [PATCH 2/2] chore: tweaks --- lib/markdown/link.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/markdown/link.js b/lib/markdown/link.js index b2f0bacaae..5dccc05d0e 100644 --- a/lib/markdown/link.js +++ b/lib/markdown/link.js @@ -25,14 +25,14 @@ module.exports = md => { const isSourceLink = /(\/|\.md|\.html)(#.*)?$/.test(href) if (isExternal) { for (const attrKey in queryOb) { - if (queryOb[attrKey]) { + if (queryOb[attrKey].length) { addAttr(token, attrKey, queryOb[attrKey]) } } if (queryOb.target === undefined) { addAttr(token, 'target', '_blank') } - if (!queryOb.rel === undefined) { + if (queryOb.rel === undefined) { addAttr(token, 'rel', 'noopener noreferrer') } } else if (isSourceLink) {