Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bugix/fire type events on active element #299

31 changes: 17 additions & 14 deletions src/index.js
Expand Up @@ -337,24 +337,27 @@ async function typeImpl(element, text, {allAtOnce = false, delay} = {}) {

element.focus()

// The focussed element could change between each event, so get the currently active element each time
const currentElement = () => element.ownerDocument.activeElement
const currentValue = () => element.ownerDocument.activeElement.value

const computeText = () =>
currentElement().maxLength > 0
? text.slice(
0,
Math.max(currentElement().maxLength - currentValue().length, 0),
)
: text

if (allAtOnce) {
if (!element.readOnly) {
const previousText = element.value

const computedText =
element.maxLength > 0
? text.slice(0, Math.max(element.maxLength - previousText.length, 0))
: text

fireEvent.input(element, {
target: {value: previousText + computedText},
target: {value: previousText + computeText()},
})
}
} else {
// The focussed element could change between each event, so get the currently active element each time
const currentElement = () => element.ownerDocument.activeElement
const actuallyTyped = () => element.ownerDocument.activeElement.value

for (let index = 0; index < text.length; index++) {
const char = text[index]
const key = char // TODO: check if this also valid for characters with diacritic markers e.g. úé etc
Expand All @@ -363,6 +366,8 @@ async function typeImpl(element, text, {allAtOnce = false, delay} = {}) {
// eslint-disable-next-line no-await-in-loop
if (delay > 0) await wait(delay)

if (currentElement.disabled) return
kayleighridd marked this conversation as resolved.
Show resolved Hide resolved

const downEvent = fireEvent.keyDown(currentElement(), {
key,
keyCode,
Expand All @@ -376,15 +381,13 @@ async function typeImpl(element, text, {allAtOnce = false, delay} = {}) {
charCode: keyCode,
})

const isTextPastThreshold =
(actuallyTyped() + key).length >
(currentElement().maxLength || text.length)
const isTextPastThreshold = !computeText().length

if (pressEvent && !isTextPastThreshold) {
if (!element.readOnly) {
fireEvent.input(currentElement(), {
target: {
value: actuallyTyped() + key,
value: currentValue() + key,
},
bubbles: true,
cancelable: true,
Expand Down