From 5c42185322c654f51bf98e58270d9847e4ef3bec Mon Sep 17 00:00:00 2001 From: Monica Dinculescu Date: Wed, 3 Jun 2015 11:59:04 -0700 Subject: [PATCH] preserve caret position when editing --- gold-phone-input.html | 11 ++++++----- test/basic.html | 22 +++++++++++----------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/gold-phone-input.html b/gold-phone-input.html index 6b3e56e..ef6bfa1 100644 --- a/gold-phone-input.html +++ b/gold-phone-input.html @@ -89,7 +89,7 @@ required$="[[required]]" bind-value="{{value}}" name$="[[name]]" - allowed-pattern="[0-9]" + allowed-pattern="[0-9\-]" autocomplete="tel" type="tel" prevent-invalid-input @@ -192,13 +192,14 @@ formattedValue += value[i]; } - - this.value = formattedValue.trim(); + this.updateValueAndPreserveCaret(formattedValue.trim()); // If the character right before the selection is a newly inserted // dash, we need to advance the selection to maintain the caret position. - if (!previousCharADash && this.value.charAt(start - 1) == '-') - this.$.input.selectionStart++; + if (!previousCharADash && this.value.charAt(start - 1) == '-') { + this.$.input.selectionStart = start + 1; + this.$.input.selectionEnd = start + 1; + } } }) diff --git a/test/basic.html b/test/basic.html index 387066d..6016863 100644 --- a/test/basic.html +++ b/test/basic.html @@ -80,17 +80,17 @@ assert.notEqual(getComputedStyle(error).display, 'none', 'error is not display:none'); }); - // TODO: re-enable when PolymerElements/iron-input/issues/24 is fixed. - // test('caret position is preserved', function() { - // var input = fixture('required'); - // var ironInput = input.querySelector('input[is="iron-input"]'); - // input.value='111-111-1'; - // ironInput.selectionStart = (2,2); - // input.value='112-111-11'; - // - // assert.equal(ironInput.selectionStart, 2, 'selectionStart is preserved'); - // assert.equal(ironInput.selectionEnd, 2, 'selectionEnd is preserved'); - // }); + test('caret position is preserved', function() { + var input = fixture('required'); + var ironInput = Polymer.dom(input.root).querySelector('input[is="iron-input"]'); + input.value='111-111-1'; + ironInput.selectionStart = 2; + ironInput.selectionEnd = 2; + input._computeValue('112-111-11'); + + assert.equal(ironInput.selectionStart, 2, 'selectionStart is preserved'); + assert.equal(ironInput.selectionEnd, 2, 'selectionEnd is preserved'); + }); suite('a11y', function() {