Skip to content

Commit

Permalink
Render multiple spaces with nbsps to preserve whitespaces
Browse files Browse the repository at this point in the history
fixes #8
  • Loading branch information
bantic committed Nov 16, 2015
1 parent 5651e94 commit 95c1719
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 3 deletions.
5 changes: 3 additions & 2 deletions lib/dom-renderer.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import {
createElement,
appendChild,
createTextNode
createTextNode,
setAttribute
} from "./utils";
import ImageCard from "./cards/image";

Expand All @@ -20,7 +21,7 @@ function createElementFromMarkerType([tagName, attributes]=['', []]){
for (let i=0,l=attributes.length; i<l; i=i+2) {
let propName = attributes[i],
propValue = attributes[i+1];
element.setAttribute(propName, propValue);
setAttribute(element, propName, propValue);
}
return element;
}
Expand Down
11 changes: 10 additions & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ export function appendChild(target, child) {
target.appendChild(child);
}

function addHTMLSpaces(text) {
let nbsp = '\u00A0';
return text.replace(/ /g, ' ' + nbsp);
}

export function createTextNode(text) {
return document.createTextNode(text);
return document.createTextNode(addHTMLSpaces(text));
}

export function setAttribute(node, propName, value) {
node.setAttribute(propName, value);
}
38 changes: 38 additions & 0 deletions tests/unit/dom-renderer-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -277,3 +277,41 @@ test('renders mobiledoc with lists', (assert) => {
assert.equal(items[1].childNodes[0].textContent, 'second item',
'correct text node for item 2');
});

test('multiple spaces should preserve whitespace with nbsps', (assert) => {
let space = ' ';
let repeat = (str, count) => {
let result = '';
while (count--) {
result += str;
}
return result;
};
let text = [
repeat(space, 4), 'some',
repeat(space, 5), 'text',
repeat(space, 6)
].join('');
let mobiledoc = {
version: MOBILEDOC_VERSION,
sections: [
[], // markers
[ // sections
[1, 'P', [
[[], 0, text]]
]
]
]
};

let nbsp = '\u00A0';
let sn = ' ' + nbsp;
let expectedText = [
repeat(sn, 2), 'some',
repeat(sn, 2), ' ', 'text',
repeat(sn, 3)
].join('');
let rendered = renderer.render(mobiledoc);
let textNode = rendered.firstChild.firstChild;
assert.equal(textNode.textContent, expectedText, 'renders the text');
});

0 comments on commit 95c1719

Please sign in to comment.