Skip to content

Commit

Permalink
refactor(open_graph): drop cheerio and use regex (hexojs#3680)
Browse files Browse the repository at this point in the history
* refactor(open_graph): drop cheerio and use regex

* feat(open_graph): faster regex pattern for img tag

* refactor(open_graph): eliminate unnecessary checks

* feat(open_graph): a new regex which use less steps

* test(open_graph): add img with empty src attribute
  • Loading branch information
SukkaW authored and Thomas Parisot committed Jan 17, 2020
1 parent 7a413f7 commit 064e7e7
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
14 changes: 7 additions & 7 deletions lib/plugins/helper/open_graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
const urlFn = require('url');
const moment = require('moment');
const { escapeHTML, htmlTag, stripHTML } = require('hexo-util');
let cheerio;

function meta(name, content, escape) {
if (escape !== false && typeof content === 'string') {
Expand All @@ -28,7 +27,6 @@ function og(name, content, escape) {
}

function openGraphHelper(options = {}) {
if (!cheerio) cheerio = require('cheerio');

const { config, page } = this;
const { content } = page;
Expand Down Expand Up @@ -59,12 +57,14 @@ function openGraphHelper(options = {}) {
if (!images.length && content) {
images = images.slice();

const $ = cheerio.load(content);
if (content.includes('<img')) {
let img;
const imgPattern = /<img [^>]*src=['"]([^'"]+)([^>]*>)/gi;
while ((img = imgPattern.exec(content)) !== null) {
images.push(img[1]);
}
}

$('img').each(function() {
const src = $(this).attr('src');
if (src) images.push(src);
});
}

let result = '';
Expand Down
8 changes: 6 additions & 2 deletions test/scripts/helpers/open_graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,9 @@ describe('open_graph', () => {
page: {
content: [
'<p>123456789</p>',
'<img src="https://hexo.io/test.jpg">'
'<img src="https://hexo.io/test.jpg">',
'<img src="">',
'<img class="img">'
].join('')
},
config: hexo.config,
Expand Down Expand Up @@ -163,7 +165,9 @@ describe('open_graph', () => {
page: {
content: [
'<p>123456789</p>',
'<img src="https://hexo.io/test.jpg">'
'<img src="https://hexo.io/test.jpg">',
'<img src="">',
'<img class="img">'
].join(''),
photos: []
},
Expand Down

0 comments on commit 064e7e7

Please sign in to comment.