diff --git a/src/generators/plaintext.js b/src/generators/plaintext.js index 46b03db5..0461688a 100644 --- a/src/generators/plaintext.js +++ b/src/generators/plaintext.js @@ -5,6 +5,37 @@ const {stripHtml} = require('string-strip-html') const defaultConfig = require('./posthtml/defaultConfig') const self = { + removeCustomTags: (tag, html, config = {}) => { + const posthtmlOptions = get(config, 'build.posthtml.options', {}) + + const posthtmlPlugin = () => tree => { + const process = node => { + if (!node.tag) { + return node + } + + if (node.tag === tag) { + return { + tag: false, + content: [''] + } + } + + if (Array.isArray(tag) && tag.includes(node.tag)) { + return { + tag: false, + content: [''] + } + } + + return node + } + + return tree.walk(process) + } + + return posthtml([posthtmlPlugin()]).process(html, {...posthtmlOptions, sync: true}).html + }, handleCustomTags: (html, config = {}) => { const posthtmlOptions = merge(defaultConfig, get(config, 'build.posthtml.options', {})) @@ -32,16 +63,18 @@ const self = { return posthtml([posthtmlPlugin()]).process(html, {...posthtmlOptions, sync: true}).html }, - generate: async (html, destination, config) => { + generate: async (html, destination, config = {}) => { const configDestinationPath = get(config, 'destination.path') const extension = get(config, 'destination.extension', 'txt') - const plaintext = stripHtml(html, { + const strippedHTML = self.removeCustomTags('not-plaintext', html, config) + + const plaintext = stripHtml(strippedHTML, { dumpLinkHrefsNearby: { enabled: true }, - stripTogetherWithTheirContents: ['script', 'style', 'xml', 'not-plaintext'], - ...get(config, 'options', {}) + stripTogetherWithTheirContents: ['script', 'style', 'xml'], + ...config }).result html = self.handleCustomTags(html, config) diff --git a/test/stubs/plaintext/plaintext.html b/test/stubs/plaintext/plaintext.html index fec1e0bc..3452ac92 100644 --- a/test/stubs/plaintext/plaintext.html +++ b/test/stubs/plaintext/plaintext.html @@ -1,5 +1,5 @@
Show in HTML
Show in plaintext</plaintext> <not-plaintext> - <table><tr><td>Remove from plaintext</td></tr></table> + <p>Do not show <a href="url">this</a> in plaintext.</p> </not-plaintext> diff --git a/test/test-todisk.js b/test/test-todisk.js index 134b1500..c831a046 100644 --- a/test/test-todisk.js +++ b/test/test-todisk.js @@ -153,7 +153,7 @@ test('outputs plaintext files', async t => { t.is( await fs.readFile(`${t.context.folder}/plaintext.html`, 'utf8'), - '<div>Show in HTML</div>\n\n\n <table><tr><td>Remove from plaintext</td></tr></table>\n\n' + '<div>Show in HTML</div>\n\n\n <p>Do not show <a href="url">this</a> in plaintext.</p>\n\n' ) })