diff --git a/src/index.js b/src/index.js index 31fe52fa..41025a69 100644 --- a/src/index.js +++ b/src/index.js @@ -20,6 +20,7 @@ const noop = () => {}; * @param {Boolean} [options.shallow=false] If `true`, renders nested Components as HTML elements (``). * @param {Boolean} [options.xml=false] If `true`, uses self-closing tags for elements without children. * @param {Boolean} [options.pretty=false] If `true`, adds whitespace for readability + * @param {Boolean} [options.preserveWhitespace=['pre']] Array of HTML tags for which to preserve indentation. */ renderToString.render = renderToString; @@ -51,7 +52,7 @@ function renderToString(vnode, context, opts, inner, isSvgMode, selectValue) { context = context || {}; opts = opts || {}; - let pretty = opts.pretty, + let pretty = (opts.preserveWhitespace || ['pre']).indexOf(nodeName) === -1 && opts.pretty, indentChar = pretty && typeof pretty==='string' ? pretty : '\t'; // #text nodes @@ -73,7 +74,7 @@ function renderToString(vnode, context, opts, inner, isSvgMode, selectValue) { for (let i = 0; i < children.length; i++) { rendered += (i > 0 && pretty ? '\n' : '') + renderToString(children[i], context, opts, opts.shallowHighOrder!==false, isSvgMode, selectValue); } - return rendered; + return pretty ? indent(rendered, indentChar) : rendered; } else { let rendered; @@ -269,7 +270,7 @@ function renderToString(vnode, context, opts, inner, isSvgMode, selectValue) { } if (pretty && hasLarge) { for (let i=pieces.length; i--; ) { - pieces[i] = '\n' + indentChar + indent(pieces[i], indentChar); + pieces[i] = '\n' + indentChar + pieces[i]; } } } diff --git a/test/pretty.js b/test/pretty.js index ba85c556..65e524d0 100644 --- a/test/pretty.js +++ b/test/pretty.js @@ -21,6 +21,19 @@ describe('pretty', () => { expect(rendered).to.equal(`
foobar

hello

`); }); + it('should preserve indentation of pre content', () => { + let rendered = prettyRender( +
+
+			
+ ); + + expect(rendered).to.equal(`
+
foo
+bar
+
`); + }); + it('should render whitespace when pretty=true', () => { let rendered = prettyRender(
diff --git a/test/render.js b/test/render.js index 3095d66a..2275fd06 100644 --- a/test/render.js +++ b/test/render.js @@ -712,6 +712,17 @@ describe('render', () => { expect(html).to.equal('
\n\t
foo
\n\t
bar
\n\t
\n\t\t
baz
\n\t\t
quux
\n\t
\n
'); }); + it('should preserve indentation of pre content', () => { + let rendered = render( +
+
+				
+ ); + + expect(rendered).to.equal(`
foo
+bar
`); + }); + it('should skip Fragment even if it has props', () => { let html = render(