(bug 40850) jquery.byteLimit: Always update prevSafeVal.
authorMatmaRex <matma.rex@gmail.com>
Thu, 15 Nov 2012 12:23:44 +0000 (13:23 +0100)
committerTimo Tijhof <ttijhof@wikimedia.org>
Fri, 16 Nov 2012 17:17:44 +0000 (18:17 +0100)
Not doing this sometimes caused trimValForByteLength to compare
the new value to an empty string instead of the old value,
resulting in trimming always at the end instead of at the position
of insertion.

Change-Id: I2e46961efa4f82732d577f7e5f98fc80719c88bb

resources/jquery/jquery.byteLimit.js
tests/qunit/suites/resources/jquery/jquery.byteLimit.test.js

index 75dc2b9..f2b98f0 100644 (file)
                                // This is a side-effect of limiting after the fact.
                                if ( res.trimmed === true ) {
                                        this.value = res.newVal;
-                                       prevSafeVal = res.newVal;
                                }
+                               // Always adjust prevSafeVal to reflect the input value. Not doing this could cause
+                               // trimValForByteLength to compare the new value to an empty string instead of the
+                               // old value, resulting in trimming always from the end (bug 40850).
+                               prevSafeVal = res.newVal;
                        } );
                } );
        };
index 4fe6770..2990de2 100644 (file)
                $el.byteLimit();
        });
 
+       QUnit.test( 'Trim from insertion when limit exceeded', 2, function ( assert ) {
+               var $el;
+
+               // Use a new <input /> because the bug only occurs on the first time
+               // the limit it reached (bug 40850)
+               $el = $( '<input type="text"/>' )
+                       .appendTo( '#qunit-fixture' )
+                       .byteLimit( 3 )
+                       .val( 'abc' ).trigger( 'change' )
+                       .val( 'zabc' ).trigger( 'change' );
+
+               assert.strictEqual( $el.val(), 'abc', 'Trim from the insertion point (at 0), not the end' );
+
+               $el = $( '<input type="text"/>' )
+                       .appendTo( '#qunit-fixture' )
+                       .byteLimit( 3 )
+                       .val( 'abc' ).trigger( 'change' )
+                       .val( 'azbc' ).trigger( 'change' );
+
+               assert.strictEqual( $el.val(), 'abc', 'Trim from the insertion point (at 1), not the end' );
+       });
+
 }( jQuery, mediaWiki ) );