diff --git a/__tests__/stripComments.js b/__tests__/stripComments.js new file mode 100644 index 000000000..ea92dc807 --- /dev/null +++ b/__tests__/stripComments.js @@ -0,0 +1,18 @@ +import { stripComments } from '../index'; + +describe('Strip Comments', () => { + it('removes HTML comments from the text', () => { + const input = ` +# hello world +This is some text. + +More text here. +`; + + const expectedOutput = ` +This is some text. +More text here.`; + + expect(stripComments(input)).toBe(expectedOutput); + }); +}); diff --git a/index.js b/index.js index a3e90c8c0..bce49ab6a 100644 --- a/index.js +++ b/index.js @@ -32,6 +32,7 @@ const toPlainText = require('./processor/plugin/plain-text'); const sectionAnchorId = require('./processor/plugin/section-anchor-id'); const tableFlattening = require('./processor/plugin/table-flattening'); const { remarkTransformers, rehypeTransformers } = require('./processor/transform'); +const stripCommentsTransformer = require('./processor/transform/strip-comments'); const createSchema = require('./sanitize.schema'); const { @@ -107,7 +108,6 @@ export function processor(userOpts = {}) { const [, parsedOpts] = setup('', userOpts); const { sanitize } = parsedOpts; const [reusableContent, opts] = parseReusableContent(parsedOpts); - return unified() .use(remarkParse, opts.markdownOptions) .use(remarkFrontmatter, ['yaml', 'toml']) @@ -303,6 +303,16 @@ export function md(treeOrString, opts = {}) { return processor(opts).use(remarkStringify, opts.markdownOptions).use(customCompilers).stringify(tree); } +/** + * Strip HTML comments from markdown text + */ +export function stripComments(text, opts = {}) { + if (!text) return null; + [text, opts] = setup(text, opts); + + return processor(opts).use(stripCommentsTransformer).use(remarkStringify).processSync(text).toString(); +} + const ReadMeMarkdown = (text, opts = {}) => react(text, opts); export { default as Owlmoji } from './lib/owlmoji'; diff --git a/processor/transform/strip-comments.js b/processor/transform/strip-comments.js new file mode 100644 index 000000000..848d8aed2 --- /dev/null +++ b/processor/transform/strip-comments.js @@ -0,0 +1,25 @@ +import { SKIP, visit } from 'unist-util-visit'; + +const HTML_COMMENT_REGEX = //g; + +const stripCommentsTransformer = () => tree => { + console.log('STRIP COMMENTS TRANSFORMER', tree); + + visit(tree, (node, index, parent) => { + // Remove HTML comments + if (node.type === 'html' && HTML_COMMENT_REGEX.test(node.value)) { + const newValue = node.value.replace(HTML_COMMENT_REGEX, '').trim(); + if (newValue) { + node.value = newValue; + } else { + parent.children.splice(index, 1); + return [SKIP, index]; + } + } + return node; + }); + + return tree; +}; + +export default stripCommentsTransformer;