From b832c2023dffd038443e843b52ba7250b36136f3 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Mon, 15 Jul 2019 14:39:56 +0200 Subject: [PATCH] Join adjacent text nodes (#109) * Join adjacent text nodes in pretty mode * Refactor pretty printing of adjacent text nodes --- server/src/index.js | 26 ++++++++++++- server/test/jsx.js | 2 +- server/test/pretty.js | 88 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 114 insertions(+), 2 deletions(-) diff --git a/server/src/index.js b/server/src/index.js index c284ee97b4..23c59d2f06 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -200,13 +200,37 @@ function renderToString(vnode, context, opts, inner, isSvgMode, selectValue) { } else if (props && getChildren(children = [], props.children).length) { let hasLarge = pretty && ~s.indexOf('\n'); + let lastWasText = false; + for (let i=0; i 0 && ret[0]!='<'; + + // We merge adjacent text nodes, otherwise each piece would be printed + // on a new line. + if (lastWasText && isText) { + pieces[pieces.length -1] += ret; + } + else { + pieces.push(ret); + } + + lastWasText = isText; + } + else { + pieces.push(ret); + } + } } } if (pretty && hasLarge) { diff --git a/server/test/jsx.js b/server/test/jsx.js index f5164289d1..a197081931 100644 --- a/server/test/jsx.js +++ b/server/test/jsx.js @@ -5,7 +5,7 @@ import sinonChai from 'sinon-chai'; chai.use(sinonChai); // tag to remove leading whitespace from tagged template literal -function dedent([str]) { +export function dedent([str]) { return str.split( '\n'+str.match(/^\n*(\s+)/)[1] ).join('\n').replace(/(^\n+|\n+\s*$)/g, ''); } diff --git a/server/test/pretty.js b/server/test/pretty.js index 7089f15879..ba85c5568a 100644 --- a/server/test/pretty.js +++ b/server/test/pretty.js @@ -3,6 +3,7 @@ import { render } from '../src/jsx'; import { h, Fragment } from 'preact'; import chai, { expect } from 'chai'; import sinonChai from 'sinon-chai'; +import { dedent } from './jsx'; chai.use(sinonChai); describe('pretty', () => { @@ -96,4 +97,91 @@ describe('pretty', () => { )).to.equal(`
\n\t
A
\n\t
B
\n
`); }); + + it('should join adjacent text nodes', () => { + expect(prettyRender( +
hello{' '}
+ )).to.equal(dedent` +
+ hello + +
+ `); + + expect(prettyRender( +
hello{' '} {'a'}{'b'}
+ )).to.equal(dedent` +
+ hello + + ab +
+ `); + }); + + it('should join adjacent text nodeswith Fragments', () => { + expect(prettyRender( +
foobar{' '}
+ )).to.equal(dedent` +
+ foobar + +
+ `); + }); + + it('should collapse whitespace', () => { + expect(prettyRender( +

ab

+ )).to.equal(dedent` +

+ a + b +

+ `); + + expect(prettyRender( +

+ a{' '} + b +

+ )).to.equal(dedent` +

+ a + b +

+ `); + + expect(prettyRender( +

+ a{''} + b +

+ )).to.equal(dedent` +

+ a + b +

+ `); + + expect(prettyRender( +

a b

+ )).to.equal(dedent` +

+ a\ + b +

+ `); + + expect(prettyRender( b )).to.equal(dedent` + b + `); + + expect(prettyRender(

a

)).to.equal(dedent` +

+ + \ a\ +

+ `); + }); });