From d4e6defd5a5f0bb6fd7e248e4e21ca838a461910 Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Thu, 10 Apr 2014 15:19:24 +0100 Subject: Handle consecutive runs of text --- lib/html-writer.js | 13 +++++++++++-- tests/html-writer.tests.js | 29 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/lib/html-writer.js b/lib/html-writer.js index c144261..f1761c9 100644 --- a/lib/html-writer.js +++ b/lib/html-writer.js @@ -25,6 +25,7 @@ function prettyWriter() { var indentation = " "; var stack = []; var start = true; + var inText = false; var writer = simpleWriter(); @@ -48,7 +49,7 @@ function prettyWriter() { } function text(value) { - indent(); + startText(); writer.text(value.replace("\n", "\n" + indentation)); } @@ -58,7 +59,7 @@ function prettyWriter() { } function append(html) { - indent(); + startText(); writer.append(html.replace("\n", "\n" + indentation)); } @@ -66,7 +67,15 @@ function prettyWriter() { return stack.length === 0 || indentedElements[stack[stack.length - 1]]; } + function startText() { + if (!inText) { + indent(); + inText = true; + } + } + function indent() { + inText = false; if (!start && insideIndentedElement()) { writer.append("\n"); for (var i = 0; i < indentationLevel; i++) { diff --git a/tests/html-writer.tests.js b/tests/html-writer.tests.js index c40cda4..c317544 100644 --- a/tests/html-writer.tests.js +++ b/tests/html-writer.tests.js @@ -26,6 +26,17 @@ describe('html-writer', function() { return assert.equal(writer.asString(), ""); }); + test('indents text if prettyPrint is true', function() { + var writer = htmlWriter.writer({prettyPrint: true}); + writer.open("p"); + writer.text("One"); + writer.close("p"); + writer.open("p"); + writer.text("Two"); + writer.close("p"); + return assert.equal(writer.asString(), "

\n One\n

\n

\n Two\n

"); + }); + test('indents element if prettyPrint is true', function() { var writer = htmlWriter.writer({prettyPrint: true}); writer.open("ul"); @@ -59,6 +70,24 @@ describe('html-writer', function() { return assert.equal(writer.asString(), "

\n One\n Two\n

"); }); + test('run of text has only one new line', function() { + var writer = htmlWriter.writer({prettyPrint: true}); + writer.open("p"); + writer.text("One"); + writer.text("Two"); + writer.close("p"); + return assert.equal(writer.asString(), "

\n OneTwo\n

"); + }); + + test('run of html has only one new line', function() { + var writer = htmlWriter.writer({prettyPrint: true}); + writer.open("p"); + writer.append("One"); + writer.append("Two"); + writer.close("p"); + return assert.equal(writer.asString(), "

\n OneTwo\n

"); + }); + test('self closing elements are indented', function() { var writer = htmlWriter.writer({prettyPrint: true}); writer.open("p"); -- cgit v1.2.3