From 764d3a23e3e0762458a59df003ed25f53d42d505 Mon Sep 17 00:00:00 2001 From: Titus Date: Thu, 9 Feb 2023 17:25:55 +0100 Subject: [PATCH] Remove whitespace between unraveled text nodes Closes GH-2000. Closes GH-2252. --- .../mdx/lib/plugin/remark-mark-and-unravel.js | 15 ++++++- packages/mdx/test/compile.js | 42 ++++++++++++++++++- 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/packages/mdx/lib/plugin/remark-mark-and-unravel.js b/packages/mdx/lib/plugin/remark-mark-and-unravel.js index 68e6eb76a..5fc86c4ca 100644 --- a/packages/mdx/lib/plugin/remark-mark-and-unravel.js +++ b/packages/mdx/lib/plugin/remark-mark-and-unravel.js @@ -1,4 +1,5 @@ /** + * @typedef {import('mdast').Content} Content * @typedef {import('mdast').Root} Root * * @typedef {import('remark-mdx')} DoNotTouchAsThisImportItIncludesMdxInTree @@ -47,6 +48,9 @@ export function remarkMarkAndUnravel() { if (all && oneOrMore) { offset = -1 + /** @type {Array} */ + const newChildren = [] + while (++offset < children.length) { const child = children[offset] @@ -59,9 +63,18 @@ export function remarkMarkAndUnravel() { // @ts-expect-error: content model is fine. child.type = 'mdxFlowExpression' } + + if ( + child.type === 'text' && + /^[\t\r\n ]+$/.test(String(child.value)) + ) { + // Empty. + } else { + newChildren.push(child) + } } - parent.children.splice(index, 1, ...children) + parent.children.splice(index, 1, ...newChildren) return index } } diff --git a/packages/mdx/test/compile.js b/packages/mdx/test/compile.js index d08cd07fc..65c5ed128 100644 --- a/packages/mdx/test/compile.js +++ b/packages/mdx/test/compile.js @@ -1256,7 +1256,7 @@ test('MDX (JSX)', async () => { renderToStaticMarkup( React.createElement(await run(compileSync('b\tc'))) ), - 'b\n\t\nc', + 'b\nc', 'should unravel JSX (text) and whitespace as only children' ) @@ -1363,6 +1363,46 @@ test('MDX (JSX)', async () => { 'the sum of one and one is: 2', 'should support JSX in expressions' ) + + // Important: there should not be whitespace in the `tr`. + // This is normally not present, but unraveling makes this a bit more complex. + // See: . + assert.equal( + compileSync(` + + + + + + +
ab
`).value, + [ + '/*@jsxRuntime automatic @jsxImportSource react*/', + 'import {jsx as _jsx, jsxs as _jsxs} from "react/jsx-runtime";', + 'function _createMdxContent(props) {', + ' return _jsx("table", {', + ' children: _jsx("thead", {', + ' children: _jsxs("tr", {', + ' children: [_jsx("th", {', + ' children: "a"', + ' }), _jsx("th", {', + ' children: "b"', + ' })]', + ' })', + ' })', + ' });', + '}', + 'function MDXContent(props = {}) {', + ' const {wrapper: MDXLayout} = props.components || ({});', + ' return MDXLayout ? _jsx(MDXLayout, Object.assign({}, props, {', + ' children: _jsx(_createMdxContent, props)', + ' })) : _createMdxContent(props);', + '}', + 'export default MDXContent;', + '' + ].join('\n'), + 'should support JSX in expressions' + ) }) test('MDX (ESM)', async () => {