From ca840b026e8f9f2b544f811755f565b39ef7f6de Mon Sep 17 00:00:00 2001 From: Titus Wormer Date: Wed, 30 Mar 2022 16:08:05 +0200 Subject: [PATCH] rehype-minify-whitespace: do not collapse in script, style Closes GH-44. --- packages/rehype-minify-whitespace/index.js | 7 ++++++- packages/rehype-minify-whitespace/test.js | 14 +++++++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/packages/rehype-minify-whitespace/index.js b/packages/rehype-minify-whitespace/index.js index 7dc6f9c..f1412ac 100644 --- a/packages/rehype-minify-whitespace/index.js +++ b/packages/rehype-minify-whitespace/index.js @@ -318,7 +318,8 @@ function collapseFactory(replace) { } /** - * We don’t support void elements here (so `nobr wbr` -> `normal` is ignored). + * We don’t need to support void elements here (so `nobr wbr` -> `normal` is + * ignored). * * @param {Root|Element} node * @param {Context} context @@ -327,8 +328,12 @@ function collapseFactory(replace) { function inferWhiteSpace(node, context) { if ('tagName' in node && node.properties) { switch (node.tagName) { + // Whitespace in script/style, while not displayed by CSS as significant, + // could have some meaning in JS/CSS, so we can’t touch them. case 'listing': case 'plaintext': + case 'script': + case 'style': case 'xmp': return 'pre' case 'nobr': diff --git a/packages/rehype-minify-whitespace/test.js b/packages/rehype-minify-whitespace/test.js index c2b7017..2641799 100644 --- a/packages/rehype-minify-whitespace/test.js +++ b/packages/rehype-minify-whitespace/test.js @@ -419,10 +419,10 @@ test('rehype-minify-whitespace', (t) => { h('meta', {charSet: 'utf8'}), h('title', 'a'), h('link'), - h('script', 'b'), + h('script', ' b '), h('meta'), - h('script', 'c'), - h('style', 'd') + h('script', ' c '), + h('style', ' d ') ]) ]), 'should trim whitespace in head' @@ -827,5 +827,13 @@ test('rehype-minify-whitespace', (t) => { 'should collapse and trim whitespace in tables' ) + t.deepEqual( + rehype() + .use(min) + .runSync(u('root', [h('script', ' // a \n b ')])), + u('root', [h('script', ' // a \n b ')]), + 'should not collapse whitespace in scripts' + ) + t.end() })