From a49e4655c83ab26cf450c6c18fb5ccf9f99fe4e0 Mon Sep 17 00:00:00 2001 From: Kevin Van Lierde Date: Fri, 17 Dec 2021 15:24:30 +0100 Subject: [PATCH] Adds better JSDoc types and exports named plugin --- lib/index.js | 73 +++++++++++++++++++++++++++++----------------------- 1 file changed, 41 insertions(+), 32 deletions(-) diff --git a/lib/index.js b/lib/index.js index 10eeb38..70f8aed 100644 --- a/lib/index.js +++ b/lib/index.js @@ -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