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

Commit c5ec316

Browse files
jonbcardtinayuangao
authored andcommitted
fix(input): prevent md-select-on-focus from refocusing blurred input (#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.
1 parent 60e2393 commit c5ec316

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

src/components/input/input.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -776,7 +776,7 @@ function placeholderDirective($compile) {
776776
*
777777
* </hljs>
778778
*/
779-
function mdSelectOnFocusDirective($timeout) {
779+
function mdSelectOnFocusDirective($document, $timeout) {
780780

781781
return {
782782
restrict: 'A',
@@ -802,9 +802,14 @@ function mdSelectOnFocusDirective($timeout) {
802802
preventMouseUp = true;
803803

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

809814
// This should be reset from inside the `focus`, because the event might
810815
// have originated from something different than a click, e.g. a keyboard event.

src/components/input/input.spec.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,23 @@ describe('md-input-container directive', function() {
659659
}
660660
}));
661661

662+
it('should not refocus the input after focus is lost', inject(function($document, $timeout) {
663+
var wrapper = $compile('<div><input md-select-on-focus value="Text"><input></div>')($rootScope),
664+
input1 = angular.element(wrapper[0].childNodes[0]),
665+
input2 = angular.element(wrapper[0].childNodes[1]);
666+
$document[0].body.appendChild(wrapper[0]);
667+
668+
input1.focus();
669+
input1.triggerHandler('focus');
670+
input2.focus();
671+
input2.triggerHandler('focus');
672+
673+
$timeout.flush();
674+
expect(input2).toBeFocused();
675+
676+
wrapper.remove();
677+
}));
678+
662679
describe('Textarea auto-sizing', function() {
663680
var ngElement, element, ngTextarea, textarea, scope, parentElement;
664681

0 commit comments

Comments
 (0)