Skip to content

Commit

Permalink
Add some comments and tests for selectionContainsContent() helper
Browse files Browse the repository at this point in the history
  • Loading branch information
nmielnik committed Dec 7, 2015
1 parent b8e03cd commit 79ca97d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
23 changes: 23 additions & 0 deletions spec/selection.spec.js
Expand Up @@ -532,4 +532,27 @@ describe('MediumEditor.selection TestCase', function () {
expect(element).toBe(document);
});
});

describe('selectionContainsContent', function () {
it('should return true for non-empty text', function () {
this.el.innerHTML = '<p>this is<span> </span>text</p>';
selectElementContents(this.el.querySelector('p'));

expect(MediumEditor.selection.selectionContainsContent(document)).toBe(true);
});

it('should return false for white-space only selections', function () {
this.el.innerHTML = '<p>this is<span> </span>text</p>';
selectElementContents(this.el.querySelector('span'));

expect(MediumEditor.selection.selectionContainsContent(document)).toBe(false);
});

it('should return true for image with link selections', function () {
this.el.innerHTML = '<p>this is <a href="#"><img src="../demo/img/medium-editor.jpg" /></a> image test</p>';
selectElementContents(this.el.querySelector('a'));

expect(MediumEditor.selection.selectionContainsContent(document)).toBe(true);
});
});
});
8 changes: 7 additions & 1 deletion src/js/selection.js
Expand Up @@ -55,7 +55,7 @@
end: start + range.toString().length
};

if (selectionState.start === selectionState.end && MediumEditor.selection.selectionContainsContent(doc)) {
if (selectionState.start === selectionState.end && this.selectionContainsContent(doc)) {
selectionState.emptyContentSelection = true;
}

Expand Down Expand Up @@ -268,17 +268,23 @@
return emptyBlocksCount;
},

// determine if the current selection contains any 'content'
// content being and non-white space text or an image
selectionContainsContent: function (doc) {
var sel = doc.getSelection();

// collapsed selection or selection withour range doesn't contain content
if (!sel || sel.isCollapsed || !sel.rangeCount) {
return false;
}

// if toString() contains any text, the selection contains some content
if (sel.toString().trim() !== '') {
return true;
}

// if selection contains only image(s), it will return empty for toString()
// so check for an image manually
var selectionNode = this.getSelectedParentElement(sel.getRangeAt(0));
if (selectionNode) {
if (selectionNode.nodeName.toLowerCase() === 'img' ||
Expand Down

0 comments on commit 79ca97d

Please sign in to comment.