Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(link): add external_link #116

Merged
merged 6 commits into from
Nov 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ marked:
sanitizeUrl: false
headerIds: true
prependRoot: false
external_link:
enable: false
exclude: []
```

- **gfm** - Enables [GitHub flavored markdown](https://help.github.com/articles/github-flavored-markdown)
Expand All @@ -50,6 +53,10 @@ marked:
root: /blog/
```
* `![text](/path/to/image.jpg)` becomes `<img src="/blog/path/to/image.jpg" alt="text">`
- **external_link**
* **enable** - Open external links in a new tab.
* **exclude** - Exclude hostname. Specify subdomain when applicable, including `www`.
* Example: `[foo](http://bar.com)` becomes `<a href="http://bar.com" target="_blank" rel="noopener">foo</a>`

## Extras

Expand Down
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ hexo.config.marked = Object.assign({
sanitizeUrl: false,
headerIds: true,
// TODO: enable prependRoot by default in v3
prependRoot: false
prependRoot: false,
external_link: {
enable: false,
exclude: []
}
}, hexo.config.marked);

hexo.extend.renderer.register('md', 'html', renderer, true);
Expand Down
62 changes: 53 additions & 9 deletions lib/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,41 @@
const { inherits } = require('util');
const marked = require('marked');
const stripIndent = require('strip-indent');
const { stripHTML, highlight, slugize, encodeURL, url_for } = require('hexo-util');
const { encodeURL, highlight, slugize, stripHTML, url_for } = require('hexo-util');
const MarkedRenderer = marked.Renderer;
const { parse } = require('url');
const { parse, URL } = require('url');

/**
* Check whether the link is external
* @param {String} url The url to check
* @param {Object} siteCfg The site config
* @param {String|array} exclude Domain(s) to be excluded
* @returns {Boolean} True if the link is an internal link or having the same host with config.url
*/
const isExternal = (url, siteCfg, exclude) => {
const sitehost = parse(siteCfg.url).hostname || siteCfg.url;
if (!sitehost) return false;

// handle relative url
const data = new URL(url, `http://${sitehost}`);

// handle mailto: javascript: vbscript: and so on
if (data.origin === 'null') return false;

const host = data.hostname;

if (exclude) {
exclude = Array.isArray(exclude) ? exclude : [exclude];

for (const i of exclude) {
if (host === i) return false;
}
}

if (host !== sitehost) return true;

return false;
};

function Renderer() {
MarkedRenderer.apply(this);
Expand Down Expand Up @@ -41,13 +73,16 @@ function anchorId(str, transformOption) {

// Support AutoLink option
Renderer.prototype.link = function(href, title, text) {
if (this.options.sanitizeUrl) {
const { options } = this;
const { external_link } = options;

if (options.sanitizeUrl) {
if (href.startsWith('javascript:') || href.startsWith('vbscript:') || href.startsWith('data:')) {
href = '';
}
}

if (!this.options.autolink && href === text && title == null) {
if (!options.autolink && href === text && title == null) {
return href;
}

Expand All @@ -57,6 +92,12 @@ Renderer.prototype.link = function(href, title, text) {
out += ` title="${title}"`;
}

if (external_link) {
if (external_link.enable && isExternal(href, options.config, external_link.exclude)) {
out += ' target="_blank" rel="noopener"';
}
}

out += `>${text}</a>`;
return out;
};
Expand All @@ -76,9 +117,11 @@ Renderer.prototype.paragraph = text => {

// Prepend root to image path
Renderer.prototype.image = function(href, title, text) {
if (!parse(href).hostname && !this.options.config.relative_link
&& this.options.prependRoot) {
href = url_for.call(this.options, href);
const { options } = this;

if (!parse(href).hostname && !options.config.relative_link
&& options.prependRoot) {
href = url_for.call(options, href);
}

return `<img src="${encodeURL(href)}" alt="${text}">`;
Expand All @@ -96,14 +139,15 @@ marked.setOptions({
});

module.exports = function(data, options) {
const url_forCfg = Object.assign({}, {
const siteCfg = Object.assign({}, {
config: {
url: this.config.url,
root: this.config.root,
relative_link: this.config.relative_link
}
});

return marked(data.text, Object.assign({
renderer: new Renderer()
}, this.config.marked, options, url_forCfg));
}, this.config.marked, options, siteCfg));
};
78 changes: 78 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,84 @@ describe('Marked renderer', () => {
});
});

describe('external_link', () => {
const renderer = require('../lib/renderer');

const ctx = {
config: {
marked: {
external_link: {
enable: false
}
},
url: 'http://example.com'
}
};

it('disable', () => {
const body = '[foo](http://bar.com/)';

const r = renderer.bind(ctx);
const result = r({text: body});

result.should.eql('<p><a href="http://bar.com/">foo</a></p>\n');
});

it('enable', () => {
ctx.config.marked.external_link.enable = true;
const body = [
'[foo](http://bar.com/)',
'[text](http://example.com/)',
'[baz](/foo/bar)'
].join('\n');

const r = renderer.bind(ctx);
const result = r({text: body});

result.should.eql([
'<p><a href="http://bar.com/" target="_blank" rel="noopener">foo</a>',
'<a href="http://example.com/">text</a>',
'<a href="/foo/bar">baz</a></p>\n'
].join('\n'));
});

it('exclude - string', () => {
ctx.config.marked.external_link.exclude = 'bar.com';
const body = [
'[foo](http://foo.com/)',
'[bar](http://bar.com/)',
'[baz](http://baz.com/)'
].join('\n');

const r = renderer.bind(ctx);
const result = r({text: body});

result.should.eql([
'<p><a href="http://foo.com/" target="_blank" rel="noopener">foo</a>',
'<a href="http://bar.com/">bar</a>',
'<a href="http://baz.com/" target="_blank" rel="noopener">baz</a></p>\n'
].join('\n'));
});

it('exclude - array', () => {
ctx.config.marked.external_link.exclude = ['bar.com', 'baz.com'];
const body = [
'[foo](http://foo.com/)',
'[bar](http://bar.com/)',
'[baz](http://baz.com/)'
].join('\n');

const r = renderer.bind(ctx);
const result = r({text: body});

result.should.eql([
'<p><a href="http://foo.com/" target="_blank" rel="noopener">foo</a>',
'<a href="http://bar.com/">bar</a>',
'<a href="http://baz.com/">baz</a></p>\n'
].join('\n'));
});
});

it('should encode image url', () => {
const urlA = '/foo/bár.jpg';
const urlB = 'http://fóo.com/bar.jpg';
Expand Down