Skip to content

Commit

Permalink
Merge pull request #1018 from dggriffin/clear-selection
Browse files Browse the repository at this point in the history
Adding clearSelection method to selection.js
  • Loading branch information
nmielnik committed Mar 24, 2016
2 parents 3882d84 + e4b2cbe commit 00d868a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
26 changes: 26 additions & 0 deletions spec/selection.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -483,4 +483,30 @@ describe('MediumEditor.selection TestCase', function () {
expect(MediumEditor.selection.selectionContainsContent(document)).toBe(true);
});
});

describe('clearSelection', function () {
it('should clear the selection and set the caret to the start of the prior range when specified', function () {
this.el.innerHTML = '<p>this is<span> </span>text</p>';
selectElementContents(this.el.querySelector('p'));
var selectionStart = document.getSelection().anchorOffset;

MediumEditor.selection.clearSelection(document, true);
expect(document.getSelection().focusOffset).toBe(selectionStart);

var newSelectionEnd = document.getSelection().focusOffset;
expect(newSelectionEnd).toBe(selectionStart);
});

it('should clear the selection and set the caret to the end of the prior range by default', function () {
this.el.innerHTML = '<p>this is<span> </span>text</p>';
selectElementContents(this.el.querySelector('p'));
var selectionEnd = document.getSelection().focusOffset;

MediumEditor.selection.clearSelection(document);
expect(document.getSelection().anchorOffset).toBe(selectionEnd);

var newSelectionStart = document.getSelection().anchorOffset;
expect(newSelectionStart).toBe(selectionEnd);
});
});
});
14 changes: 14 additions & 0 deletions src/js/selection.js
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,20 @@
return range;
},

/**
* Clear the current highlighted selection and set the caret to the start or the end of that prior selection, defaults to end.
*
* @param {DomDocument} doc Current document
* @param {boolean} moveCursorToStart A boolean representing whether or not to set the caret to the beginning of the prior selection.
*/
clearSelection: function (doc, moveCursorToStart) {
if (moveCursorToStart) {
doc.getSelection().collapseToStart();
} else {
doc.getSelection().collapseToEnd();
}
},

/**
* Move cursor to the given node with the given offset.
*
Expand Down

0 comments on commit 00d868a

Please sign in to comment.