diff --git a/lib/index.js b/lib/index.js index b66c2cf..6cee227 100644 --- a/lib/index.js +++ b/lib/index.js @@ -177,9 +177,23 @@ import {stringify as spaces} from 'space-separated-tokens' import styleToObject from 'style-to-object' import {pointStart} from 'unist-util-position' import {VFileMessage} from 'vfile-message' +import {whitespace} from 'hast-util-whitespace' const own = {}.hasOwnProperty +// `react-dom` triggers a warning for *any* white space in tables. +// To follow GFM, `mdast-util-to-hast` injects line endings between elements. +// Other tools might do so too, but they don’t do here, so we remove all of +// that. + +// See: . +// See: . +// See: . +// See: . +// See: . +// See: . +const tableElements = new Set(['table', 'thead', 'tbody', 'tfoot', 'tr']) + /** * Transform a hast tree to preact, react, solid, svelte, vue, etc., * with an automatic JSX runtime. @@ -272,14 +286,21 @@ function one(state, node, key) { state.schema = schema } - const children = createChildren(state, node) + let children = createChildren(state, node) const props = createProperties(state, node) + let type = state.Fragment - let type = node.type === 'root' ? state.Fragment : node.tagName + if (node.type === 'element') { + if (tableElements.has(node.tagName)) { + children = children.filter((child) => !whitespace(child)) + } - if (typeof type === 'string' && own.call(state.components, type)) { - const key = /** @type {keyof JSX.IntrinsicElements} */ (type) - type = state.components[key] + if (own.call(state.components, node.tagName)) { + const key = /** @type {keyof JSX.IntrinsicElements} */ (node.tagName) + type = state.components[key] + } else { + type = node.tagName + } } props.children = children diff --git a/package.json b/package.json index aec48e7..8e6473b 100644 --- a/package.json +++ b/package.json @@ -39,6 +39,7 @@ "@types/hast": "^2.0.0", "@types/unist": "^2.0.0", "comma-separated-tokens": "^2.0.0", + "hast-util-whitespace": "^2.0.0", "property-information": "^6.0.0", "space-separated-tokens": "^2.0.0", "style-to-object": "^0.4.1", diff --git a/test/index.js b/test/index.js index efc97fd..cd0d728 100644 --- a/test/index.js +++ b/test/index.js @@ -401,3 +401,38 @@ test('components', () => { 'should support class components' ) }) + +test('react specific: filter whitespace in tables', () => { + assert.equal( + renderToStaticMarkup( + toJsxRuntime( + h(null, [ + h('table', [ + ' ', + h('thead', [ + ' ', + h('tr', [' ', h('th', [' ', h('b', 'a'), ' ']), ' ']), + ' ' + ]), + ' ', + h('tbody', [ + ' ', + h('tr', [' ', h('td', [' ', h('b', 'b'), ' ']), ' ']), + ' ' + ]), + ' ', + h('tfoot', [ + ' ', + h('tr', [' ', h('td', [' ', h('b', 'c'), ' ']), ' ']), + ' ' + ]), + ' ' + ]) + ]), + production + ) + ), + '
a
b
c
', + 'should ignore whitespace in `table`, `thead`, `tbody`, `tfoot`, and `tr`' + ) +})