Skip to content

Commit

Permalink
Add support for interactive ancestors
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Jun 19, 2019
1 parent 7438b11 commit 1c31d3f
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 5 deletions.
22 changes: 18 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
const isUrl = require('is-url')
const visit = require('unist-util-visit')
const visit = require('unist-util-visit-parents')
const convert = require('unist-util-is/convert')

const isImgExt = str => /\.(svg|png|jpg|jpeg|gif)$/.test(str)
const isAbsolutePath = str => str.startsWith('/')
const isRelativePath = str => str.startsWith('./') || str.startsWith('../')
const isImgPath = str => isAbsolutePath(str) || isRelativePath(str)
const isInteractive = convert(['link', 'linkReference'])

module.exports = images

Expand All @@ -16,10 +18,22 @@ function transform(tree) {
visit(tree, 'text', ontext)
}

function ontext(node, index, parent) {
function ontext(node, parents) {
const value = String(node.value).trim()

if ((isUrl(value) || isImgPath(value)) && isImgExt(value)) {
let interactive = false
let length = parents.length
const siblings = parents[length - 1].children

// Check if we’re in interactive content.
while (length--) {
if (isInteractive(parents[length])) {
interactive = true
break
}
}

let next = {
type: 'image',
url: value,
Expand All @@ -29,7 +43,7 @@ function ontext(node, index, parent) {
}

// Add a link if we’re not already in one.
if (parent.type !== 'link' && parent.type !== 'linkReference') {
if (!interactive) {
next = {
type: 'link',
url: value,
Expand All @@ -39,6 +53,6 @@ function ontext(node, index, parent) {
}
}

parent.children[index] = next
siblings[siblings.indexOf(node)] = next
}
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
],
"dependencies": {
"is-url": "^1.2.2",
"unist-util-visit": "^1.3.0"
"unist-util-is": "^3.0.0",
"unist-util-visit-parents": "^2.1.0"
},
"devDependencies": {
"nyc": "^14.0.0",
Expand Down
20 changes: 20 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,25 @@ test('remark-images', function(t) {
'should support link references'
)

t.equal(
remark()
.use(images)
.processSync('**https://example.com/alpha.jpg**')
.toString(),
'**[![](https://example.com/alpha.jpg)](https://example.com/alpha.jpg)**\n',
'should support image URLs inside other stuff'
)

t.equal(
remark()
.use(images)
.processSync(
'[**https://example.com/alpha.jpg**](https://example.com/bravo.jpg)'
)
.toString(),
'[**![](https://example.com/alpha.jpg)**](https://example.com/bravo.jpg)\n',
'should support image URLs inside other stuff in links'
)

t.end()
})

0 comments on commit 1c31d3f

Please sign in to comment.