Skip to content

Commit

Permalink
Fix: Do not convert URLs in Markdown to auto links
Browse files Browse the repository at this point in the history
Auto links (<http://example.com>) are rendered as JSX tags, which results in an error.

Close #793
  • Loading branch information
sapegin committed Mar 30, 2018
1 parent 25cb1ef commit 71d1425
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
20 changes: 20 additions & 0 deletions loaders/utils/__tests__/noAutoLinkRemarkPlugin.spec.js
@@ -0,0 +1,20 @@
import remark from 'remark';
import noAutoLink from '../noAutoLinkRemarkPlugin';

const transform = markdown =>
remark()
.use(noAutoLink)
.processSync(markdown)
.toString();

it('should not convert URLs to auto links', () => {
const markdown = 'http://example.com';
const result = transform(markdown);
expect(result.trim()).toBe('[http://example.com](http://example.com "http&#x3A;//example.com")');
});

it('should keep full inks as is', () => {
const markdown = '[Pizza](http://example.com)';
const result = transform(markdown);
expect(result.trim()).toBe(markdown);
});
2 changes: 2 additions & 0 deletions loaders/utils/highlightCodeInMarkdown.js
@@ -1,6 +1,7 @@
const remark = require('remark');
const visit = require('unist-util-visit');
const highlightCode = require('./highlightCode');
const noAutoLink = require('./noAutoLinkRemarkPlugin');

function highlight() {
return ast => {
Expand All @@ -19,6 +20,7 @@ function highlight() {
module.exports = function highlightCodeInMarkdown(markdown) {
return remark()
.use(highlight)
.use(noAutoLink)
.processSync(markdown)
.toString();
};
30 changes: 30 additions & 0 deletions loaders/utils/noAutoLinkRemarkPlugin.js
@@ -0,0 +1,30 @@
const visit = require('unist-util-visit');

// Return a Remark AST link node's link text
const getLinkValue = node =>
node.children.reduce((value, child) => {
if (child.type === 'text') {
value += child.value;
}
return value;
}, '');

/**
* Prevent printing URLs as auto links (<http://example.com>).
* Remark prints all links without a text as auto links, so we're adding a URL
* as a title. It has an unfortunate side effect: a link has a title of
* "http&#x3A;//..."
*
* @return {Object}
*/
module.exports = function noAutoLinkRemarkPlugin() {
return ast => {
visit(ast, 'link', node => {
const value = getLinkValue(node);

if (value === node.url) {
node.title = node.url;
}
});
};
};

0 comments on commit 71d1425

Please sign in to comment.