Skip to content

Commit 71d1425

Browse files
committed
Fix: Do not convert URLs in Markdown to auto links
Auto links (<http://example.com>) are rendered as JSX tags, which results in an error. Close styleguidist#793
1 parent 25cb1ef commit 71d1425

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import remark from 'remark';
2+
import noAutoLink from '../noAutoLinkRemarkPlugin';
3+
4+
const transform = markdown =>
5+
remark()
6+
.use(noAutoLink)
7+
.processSync(markdown)
8+
.toString();
9+
10+
it('should not convert URLs to auto links', () => {
11+
const markdown = 'http://example.com';
12+
const result = transform(markdown);
13+
expect(result.trim()).toBe('[http://example.com](http://example.com "http&#x3A;//example.com")');
14+
});
15+
16+
it('should keep full inks as is', () => {
17+
const markdown = '[Pizza](http://example.com)';
18+
const result = transform(markdown);
19+
expect(result.trim()).toBe(markdown);
20+
});

loaders/utils/highlightCodeInMarkdown.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const remark = require('remark');
22
const visit = require('unist-util-visit');
33
const highlightCode = require('./highlightCode');
4+
const noAutoLink = require('./noAutoLinkRemarkPlugin');
45

56
function highlight() {
67
return ast => {
@@ -19,6 +20,7 @@ function highlight() {
1920
module.exports = function highlightCodeInMarkdown(markdown) {
2021
return remark()
2122
.use(highlight)
23+
.use(noAutoLink)
2224
.processSync(markdown)
2325
.toString();
2426
};
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const visit = require('unist-util-visit');
2+
3+
// Return a Remark AST link node's link text
4+
const getLinkValue = node =>
5+
node.children.reduce((value, child) => {
6+
if (child.type === 'text') {
7+
value += child.value;
8+
}
9+
return value;
10+
}, '');
11+
12+
/**
13+
* Prevent printing URLs as auto links (<http://example.com>).
14+
* Remark prints all links without a text as auto links, so we're adding a URL
15+
* as a title. It has an unfortunate side effect: a link has a title of
16+
* "http&#x3A;//..."
17+
*
18+
* @return {Object}
19+
*/
20+
module.exports = function noAutoLinkRemarkPlugin() {
21+
return ast => {
22+
visit(ast, 'link', node => {
23+
const value = getLinkValue(node);
24+
25+
if (value === node.url) {
26+
node.title = node.url;
27+
}
28+
});
29+
};
30+
};

0 commit comments

Comments
 (0)