diff --git a/src/js/parsers/dom.js b/src/js/parsers/dom.js index 247b4bae2..df439aa74 100644 --- a/src/js/parsers/dom.js +++ b/src/js/parsers/dom.js @@ -36,6 +36,14 @@ export function transformHTMLText(textContent) { return text; } +export function trimSectionText(section) { + if (section.isMarkerable && section.markers.length) { + let { head, tail } = section.markers; + head.value = head.value.replace(/^\s+/, ''); + tail.value = tail.value.replace(/\s+$/, ''); + } +} + function isGoogleDocsContainer(element) { return !isTextNode(element) && !isCommentNode(element) && @@ -108,6 +116,10 @@ class DOMParser { this.appendSections(post, sections); }); + // trim leading/trailing whitespace of markerable sections to avoid + // unnessary whitespace from indented HTML input + forEach(post.sections, section => trimSectionText(section)); + return post; } diff --git a/src/js/parsers/section.js b/src/js/parsers/section.js index 0112b1ded..c919ada7f 100644 --- a/src/js/parsers/section.js +++ b/src/js/parsers/section.js @@ -35,7 +35,8 @@ import { } from 'mobiledoc-kit/utils/array-utils'; import { - transformHTMLText + transformHTMLText, + trimSectionText } from '../parsers/dom'; import assert from '../utils/assert'; @@ -283,6 +284,7 @@ class SectionParser { // push listItems onto the listSection or add a new section if (state.section.isListItem && lastSection && lastSection.isListSection) { + trimSectionText(state.section); lastSection.items.append(state.section); } else { // remove empty list sections before creating a new section diff --git a/tests/unit/parsers/dom-test.js b/tests/unit/parsers/dom-test.js index 86346ed41..0d885863e 100644 --- a/tests/unit/parsers/dom-test.js +++ b/tests/unit/parsers/dom-test.js @@ -361,6 +361,24 @@ test('singly-nested ol lis are parsed correctly', (assert) => { assert.equal(section.items.objectAt(1).text, 'second element'); }); +test('nested html doesn\'t create unneccessary whitespace', (assert) => { + let element = buildDOM(` +
+

+ One +

+

+ Two +

+
+ `); + const post = parser.parse(element); + + assert.equal(post.sections.length, 2, '2 sections'); + assert.equal(post.sections.objectAt(0).text, 'One'); + assert.equal(post.sections.objectAt(1).text, 'Two'); +}); + /* * FIXME: Google docs nests uls like this test('lis in nested uls are flattened (when ul is child of ul)', (assert) => { diff --git a/tests/unit/parsers/section-test.js b/tests/unit/parsers/section-test.js index 5573af11b..4127385b8 100644 --- a/tests/unit/parsers/section-test.js +++ b/tests/unit/parsers/section-test.js @@ -322,7 +322,7 @@ test('#parse handles insignificant whitespace', (assert) => { let [list] = sections; assert.equal(list.type, 'list-section'); assert.equal(list.items.length, 1, '1 list item'); - assert.equal(list.items.objectAt(0).text, ' One '); + assert.equal(list.items.objectAt(0).text, 'One'); }); test('#parse avoids empty paragraph around wrapped list', (assert) => {