From 1c31d3f56b64a00387489c147d2c9f095c4f6f31 Mon Sep 17 00:00:00 2001 From: Titus Wormer Date: Wed, 19 Jun 2019 10:32:05 +0200 Subject: [PATCH] Add support for interactive ancestors --- index.js | 22 ++++++++++++++++++---- package.json | 3 ++- test.js | 20 ++++++++++++++++++++ 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index 3e67a4a..fbc876a 100644 --- a/index.js +++ b/index.js @@ -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 @@ -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, @@ -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, @@ -39,6 +53,6 @@ function ontext(node, index, parent) { } } - parent.children[index] = next + siblings[siblings.indexOf(node)] = next } } diff --git a/package.json b/package.json index 583d734..857e6da 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/test.js b/test.js index 2f19390..12b4976 100644 --- a/test.js +++ b/test.js @@ -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() })