Skip to content
This repository has been archived by the owner on Sep 5, 2024. It is now read-only.

Commit

Permalink
fix(input): prevent md-select-on-focus from refocusing blurred input (#…
Browse files Browse the repository at this point in the history
…11129)

Eliminate race condition that causes a blurred input with md-select-on-focus from being re-selected.
When there are two inputs with md-select-on-focus this can result in an infinite loop where focus
moves back and forth between the two elements.
  • Loading branch information
jonbcard authored and tinayuangao committed Feb 27, 2018
1 parent 60e2393 commit c5ec316
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/components/input/input.js
Original file line number Diff line number Diff line change
Expand Up @@ -776,7 +776,7 @@ function placeholderDirective($compile) {
*
* </hljs>
*/
function mdSelectOnFocusDirective($timeout) {
function mdSelectOnFocusDirective($document, $timeout) {

return {
restrict: 'A',
Expand All @@ -802,9 +802,14 @@ function mdSelectOnFocusDirective($timeout) {
preventMouseUp = true;

$timeout(function() {

// Use HTMLInputElement#select to fix firefox select issues.
// The debounce is here for Edge's sake, otherwise the selection doesn't work.
element[0].select();
// Since focus may already have been lost on the input (and because `select()`
// will re-focus), make sure the element is still active before applying.
if($document[0].activeElement === element[0]) {
element[0].select();
}

// This should be reset from inside the `focus`, because the event might
// have originated from something different than a click, e.g. a keyboard event.
Expand Down
17 changes: 17 additions & 0 deletions src/components/input/input.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,23 @@ describe('md-input-container directive', function() {
}
}));

it('should not refocus the input after focus is lost', inject(function($document, $timeout) {
var wrapper = $compile('<div><input md-select-on-focus value="Text"><input></div>')($rootScope),
input1 = angular.element(wrapper[0].childNodes[0]),
input2 = angular.element(wrapper[0].childNodes[1]);
$document[0].body.appendChild(wrapper[0]);

input1.focus();
input1.triggerHandler('focus');
input2.focus();
input2.triggerHandler('focus');

$timeout.flush();
expect(input2).toBeFocused();

wrapper.remove();
}));

describe('Textarea auto-sizing', function() {
var ngElement, element, ngTextarea, textarea, scope, parentElement;

Expand Down

0 comments on commit c5ec316

Please sign in to comment.