Skip to content

Commit

Permalink
fix(type): ignore maxlength based on input type (#420)
Browse files Browse the repository at this point in the history
Closes #418

Co-authored-by: Maxwell Newlands <maxwelln@spotify.com>
  • Loading branch information
maxnewlands and maxnewlands committed Jul 28, 2020
1 parent 448046c commit a96db77
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
39 changes: 39 additions & 0 deletions src/__tests__/type.js
Expand Up @@ -322,6 +322,45 @@ test('honors maxlength with existing text', () => {
`)
})

test('honors maxlength on textarea', () => {
const {element, getEventSnapshot} = setup(
'<textarea maxlength="2">12</textarea>',
)

userEvent.type(element, '3')

expect(getEventSnapshot()).toMatchInlineSnapshot(`
Events fired on: textarea[value="12"]
textarea[value="12"] - pointerover
textarea[value="12"] - pointerenter
textarea[value="12"] - mouseover: Left (0)
textarea[value="12"] - mouseenter: Left (0)
textarea[value="12"] - pointermove
textarea[value="12"] - mousemove: Left (0)
textarea[value="12"] - pointerdown
textarea[value="12"] - mousedown: Left (0)
textarea[value="12"] - focus
textarea[value="12"] - focusin
textarea[value="12"] - pointerup
textarea[value="12"] - mouseup: Left (0)
textarea[value="12"] - click: Left (0)
textarea[value="12"] - select
textarea[value="12"] - keydown: 3 (51)
textarea[value="12"] - keypress: 3 (51)
textarea[value="12"] - keyup: 3 (51)
`)
})

// https://github.com/testing-library/user-event/issues/418
test('ignores maxlength on input[type=number]', () => {
const {element} = setup(`<input maxlength="2" type="number" value="12" />`)

userEvent.type(element, '3')

expect(element).toHaveValue(123)
})

test('should fire events on the currently focused element', () => {
const {element} = setup(`<div><input /><input /></div>`, {
eventHandlers: {keyDown: handleKeyDown},
Expand Down
18 changes: 17 additions & 1 deletion src/utils.js
Expand Up @@ -94,6 +94,22 @@ function getActiveElement(document) {
}
}

function supportsMaxLength(element) {
if (element.tagName === 'TEXTAREA') return true

if (element.tagName === 'INPUT') {
const type = element.getAttribute('type')

// Missing value default is "text"
if (!type) return true

// https://html.spec.whatwg.org/multipage/input.html#concept-input-apply
if (type.match(/email|password|search|telephone|text|url/)) return true
}

return false
}

function calculateNewValue(newEntry, element) {
const {selectionStart, selectionEnd, value} = element

Expand Down Expand Up @@ -126,7 +142,7 @@ function calculateNewValue(newEntry, element) {
newSelectionStart = firstPart.length
}

if (maxLength < 0) {
if (!supportsMaxLength(element) || maxLength < 0) {
return {newValue, newSelectionStart}
} else {
return {
Expand Down

0 comments on commit a96db77

Please sign in to comment.