Skip to content

Commit

Permalink
Adds better JSDoc types and exports named plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
webketje committed Dec 17, 2021
1 parent fc4301c commit a49e465
Showing 1 changed file with 41 additions and 32 deletions.
73 changes: 41 additions & 32 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,43 +10,52 @@ const cheerio = require('cheerio')
*/
const html = (file) => /\.html?/.test(extname(file))

/**
* @typedef {Object} Options
* @property {Boolean} [multipleFormats] set to true to store both a `excerpt.html` and `excerpt.text`
*/

/**
* A Metalsmith plugin to extract an excerpt from HTML files.
*
* @return {Function}
* @param {Options} [options]
* @return {import('metalsmith').Plugin}
*/
const plugin = (options) => (files, metalsmith, done) => {
options = options || {}
setImmediate(done)
Object.keys(files).forEach((file) => {
debug('checking file: %s', file)
if (!html(file)) {
return
}

const data = files[file]

if (typeof data.excerpt === 'string' && data.excerpt.length > 0) {
return // Don't mutate data
}

debug('storing excerpt: %s', file)
const $ = cheerio.load(data.contents.toString())
let p = $('p').first()
while (p.children('img').length > 0) {
p = p.next()
}

if (options.multipleFormats) {
data.excerpt = {
html: $.html(p).trim(),
text: $.text(p).trim()
function plugin(options) {
return function excerpts(files, metalsmith, done) {
setImmediate(done)

options = options || {}

Object.keys(files).forEach((file) => {
debug('checking file: %s', file)
if (!html(file)) {
return
}

const data = files[file]

if (typeof data.excerpt === 'string' && data.excerpt.length > 0) {
return // Don't mutate data
}

debug('storing excerpt: %s', file)
const $ = cheerio.load(data.contents.toString())
let p = $('p').first()
while (p.children('img').length > 0) {
p = p.next()
}

if (options.multipleFormats) {
data.excerpt = {
html: $.html(p).trim(),
text: $.text(p).trim()
}
} else {
data.excerpt = $.html(p).trim()
}
} else {
data.excerpt = $.html(p).trim()
}
})
})
}
}

// Expose `plugin`
module.exports = plugin

0 comments on commit a49e465

Please sign in to comment.