diff options
| author | Michael Williamson <mike@zwobble.org> | 2014-04-10 14:26:32 +0100 |
|---|---|---|
| committer | Michael Williamson <mike@zwobble.org> | 2014-04-10 14:26:32 +0100 |
| commit | 8fcdf02810e5880fe58d1308c80142cbc936c9e3 (patch) | |
| tree | 85e19a1f3985b21661c8af657e2d1c7521ad4891 | |
| parent | dee75b1261646edb99ae01a231036fd9c468fe83 (diff) | |
Indent text with newlines inside indented elements
| -rw-r--r-- | lib/html-writer.js | 11 | ||||
| -rw-r--r-- | tests/html-writer.tests.js | 8 |
2 files changed, 15 insertions, 4 deletions
diff --git a/lib/html-writer.js b/lib/html-writer.js index 233e5dd..1b551ed 100644 --- a/lib/html-writer.js +++ b/lib/html-writer.js @@ -22,7 +22,9 @@ var indentedElements = { function prettyWriter() { var indentationLevel = 0; + var indentation = " "; var stack = []; + var start = true; var writer = simpleWriter(); @@ -33,6 +35,7 @@ function prettyWriter() { if (indentedElements[tagName]) { indentationLevel++; } + start = false; } function close(tagName) { @@ -46,18 +49,18 @@ function prettyWriter() { function text(value) { indent(); - writer.text(value); + writer.text(value.replace("\n", "\n" + indentation)); } function insideIndentedElement() { - return stack.length > 0 && indentedElements[stack[stack.length - 1]]; + return stack.length === 0 || indentedElements[stack[stack.length - 1]]; } function indent() { - if (insideIndentedElement()) { + if (!start && insideIndentedElement()) { writer.append("\n"); for (var i = 0; i < indentationLevel; i++) { - writer.append(" "); + writer.append(indentation); } } } diff --git a/tests/html-writer.tests.js b/tests/html-writer.tests.js index 2a22caf..dc6cb1c 100644 --- a/tests/html-writer.tests.js +++ b/tests/html-writer.tests.js @@ -50,4 +50,12 @@ describe('html-writer', function() { writer.close("div"); return assert.equal(writer.asString(), "<div>\n <div>\n <div>\n Hello\n </div>\n </div>\n</div>"); }); + + test('newlines in text are indented', function() { + var writer = htmlWriter.writer({prettyPrint: true}); + writer.open("p"); + writer.text("One\nTwo"); + writer.close("p"); + return assert.equal(writer.asString(), "<p>\n One\n Two\n</p>"); + }); }) |
