Skip to content

Commit 204b96d

Browse files
gnestorrgbkrk
authored andcommitted
Fix linking regex and clean up logic (#22)
1 parent ec2c220 commit 204b96d

File tree

2 files changed

+29
-25
lines changed

2 files changed

+29
-25
lines changed

src/index.js

Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -40,32 +40,24 @@ function ansiToInlineStyle(text) {
4040
function linkifyBundle(bundle) {
4141
return {
4242
...bundle,
43-
content: bundle.content.split(' ').reduce(
44-
(result, word) => {
45-
// If word is a URL
46-
if (/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/.test(word)) {
47-
return [
48-
...result,
49-
' ',
50-
React.createElement('a', {
51-
href: word ,
43+
content: bundle.content.split(' ').reduce((result, word, index) => [
44+
...result,
45+
// Unless word is the first, prepend a space
46+
index === 0 ? '' : ' ',
47+
// If word is a URL, return an <a> element
48+
/(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/.test(word)
49+
? React.createElement(
50+
'a',
51+
{
52+
key: index,
53+
href: word,
5254
target: '_blank'
53-
}, `${word}`)
54-
];
55-
}
56-
const lastWord = result.pop();
57-
if (lastWord) {
58-
// If lastWord is a `<a>` element
59-
if (lastWord.type) return [...result, lastWord, ' ', word];
60-
// If not, combine lastWord and word into single string
61-
return [...result, [lastWord, word].join(' ')];
62-
}
63-
// If there is no lastWord because word is the first
64-
return [...result, word];
65-
},
66-
[]
67-
)
68-
}
55+
},
56+
`${word}`
57+
)
58+
: word
59+
], [])
60+
};
6961
}
7062

7163
function inlineBundleToReact(bundle, key) {

test/index-spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,16 @@ describe('Ansi', () => {
4040
expect(el.text()).to.equal('this is a link: https://nteract.io/');
4141
expect(el.html()).to.equal('<code><span>this is a link: <a href="https://nteract.io/" target="_blank">https://nteract.io/</a></span></code>');
4242
});
43+
44+
it('can distinguish URL-ish text', () => {
45+
const el = enzyme.shallow(React.createElement(Ansi, {linkify: true}, '<transport.model.TransportInfo'));
46+
expect(el).to.not.be.null;
47+
expect(el.text()).to.equal('<transport.model.TransportInfo');
48+
});
49+
50+
it('can distinguish URL-ish text', () => {
51+
const el = enzyme.shallow(React.createElement(Ansi, {linkify: true}, "<module 'something' from '/usr/local/lib/python2.7/dist-packages/something/__init__.pyc'>"));
52+
expect(el).to.not.be.null;
53+
expect(el.text()).to.equal("<module 'something' from '/usr/local/lib/python2.7/dist-packages/something/__init__.pyc'>");
54+
});
4355
});

0 commit comments

Comments
 (0)