|
2 | 2 |
|
3 | 3 | const cheerio = require('cheerio') |
4 | 4 |
|
5 | | -const SUMMARY_LENGHT = 400 |
| 5 | +const SUMMARY_MAX_LENGTH = 300 |
| 6 | +const IGNORE_SELECTORS = ['.blogpost-header', '.anchor', 'h1', 'h2', 'h3', 'blockquote'] |
| 7 | + |
| 8 | +/** |
| 9 | + * Due to the nature of metalsmith and |
| 10 | + * how the metalsmith-paginate plugin operates, |
| 11 | + * this helper has to handle two different types of |
| 12 | + * HTML contents: |
| 13 | + * - clean blog posts converted from markdown to HTML, |
| 14 | + * seen on the first page of blog posts |
| 15 | + * - the remaining paginated pages has gone |
| 16 | + * through the handlebars process and therefore has the |
| 17 | + * entire page layout (w/<html>, <head> and <body> etc) |
| 18 | + * wrapped around the actual blog contents :( |
| 19 | + */ |
6 | 20 |
|
7 | 21 | module.exports = function (contents, locale, path) { |
8 | | - let $ = cheerio.load(contents) |
| 22 | + const $ = cheerio.load(contents) |
| 23 | + const $body = $('body') |
| 24 | + const hasBody = $body.length > 0 |
| 25 | + const $elements = hasBody ? $body.find('article > *') : $('*') |
9 | 26 |
|
10 | 27 | let summary = '' |
11 | 28 |
|
12 | | - $('*').each((i, elem) => { |
13 | | - if (summary.length > SUMMARY_LENGHT) { |
14 | | - summary += `<p><a href='/${locale}/${path}/'>Read more...</a></p>` |
15 | | - return false |
16 | | - } |
17 | | - |
18 | | - if (elem.parent) { |
19 | | - return |
20 | | - } |
21 | | - |
22 | | - summary += $.html(elem) |
23 | | - }) |
| 29 | + $elements |
| 30 | + .not((i, elem) => IGNORE_SELECTORS.some((selector) => $(elem).is(selector))) |
| 31 | + .each((i, elem) => { |
| 32 | + if (summary.length > SUMMARY_MAX_LENGTH) { |
| 33 | + summary += `<p><a href='/${locale}/${path}/'>Read more...</a></p>` |
| 34 | + return false |
| 35 | + } |
| 36 | + |
| 37 | + // dont re-add nested elements when extracting summary |
| 38 | + // from blog posts not contained in a complete HTML document |
| 39 | + if (!hasBody && elem.parent) { |
| 40 | + return |
| 41 | + } |
| 42 | + |
| 43 | + summary += $.html(elem) |
| 44 | + }) |
24 | 45 |
|
25 | 46 | return summary |
26 | 47 | } |
0 commit comments