Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@ From

`user-event` tries to simulate the real events that would happen in the browser
as the user interacts with it. For example `userEvent.click(checkbox)` would
change the state of the checkbox.
change the state of the checkbox. On a focused `<input type="range">`,
`await user.keyboard('{ArrowRight}')` moves the slider one step and fires
`input` and `change` when the value changes.

> [The more your tests resemble the way your software is used, the more
> confidence they can give you.][guiding-principle]
Expand Down
10 changes: 10 additions & 0 deletions src/event/behavior/keydown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,20 @@ import {focusElement} from '../focus'
import {input} from '../input'
import {moveSelection, selectAll, setSelectionRange} from '../selection'
import {walkRadio} from '../radio'
import {stepRange} from '../range'
import {BehaviorPlugin} from '.'
import {behavior} from './registry'

const rangeArrowKeys = ['ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowUp']

behavior.keydown = (event, target, instance) => {
if (
rangeArrowKeys.includes(event.key) &&
isElementType(target, 'input', {type: 'range'} as const)
) {
return () => stepRange(instance, target, event.key)
}

return (
keydownBehavior[event.key]?.(event, target, instance) ??
combinationBehavior(event, target, instance)
Expand Down
79 changes: 79 additions & 0 deletions src/event/range.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import {type Instance} from '../setup'
import {getWindow, isDisabled} from '../utils'

export function stepRange(
instance: Instance,
input: HTMLInputElement,
key: string,
) {
if (input.type !== 'range' || isDisabled(input)) {
return
}

const window = getWindow(input)
const direction = getInheritedStyle(input, 'direction')
const vertical = getInheritedStyle(input, 'writing-mode').startsWith('vertical')
const increaseX = !vertical && direction === 'rtl' ? 'ArrowLeft' : 'ArrowRight'
const increaseY = vertical && direction !== 'rtl' ? 'ArrowDown' : 'ArrowUp'
const increase = key === increaseX || key === increaseY
const previous = input.valueAsNumber
const step = increase ? 'stepUp' : 'stepDown'

if (input.step.toLowerCase() === 'any') {
stepAny(input, step)
} else {
input[step]()
}

if (input.valueAsNumber !== previous) {
instance.dispatchEvent(
input,
new window.Event('input', {bubbles: true, composed: true}),
)
instance.dispatchUIEvent(input, 'change')
}
}

function getInheritedStyle(
input: HTMLInputElement,
property: 'direction' | 'writing-mode',
) {
const window = getWindow(input)
// Some DOM implementations omit inherited values from the computed style.
for (let el: HTMLElement | null = input; el; el = el.parentElement) {
const value = window.getComputedStyle(el).getPropertyValue(property)
if (value === 'inherit' || value === 'unset') {
continue
}
if (value) {
return value
}
if (property === 'direction' && el.dir) {
return el.dir
}
}
return ''
}

function stepAny(input: HTMLInputElement, step: 'stepUp' | 'stepDown') {
// stepUp/stepDown reject step="any". Chromium and WebKit use one percent
// of the range, starting at the current value.
const number = input.ownerDocument.createElement('input')
number.type = 'number'
number.value = input.min
const min = number.value === '' ? 0 : number.valueAsNumber
number.value = input.max
const max = number.value === '' ? 100 : number.valueAsNumber
if (max <= min) {
return
}
const span = max - min
const increment = Number.isFinite(span) ? span / 100 : max / 100 - min / 100
if (increment > 0) {
number.step = String(increment)
number.defaultValue = input.value
number.value = input.value
number[step]()
input.valueAsNumber = Math.min(max, Math.max(min, number.valueAsNumber))
}
}
135 changes: 135 additions & 0 deletions tests/event/behavior/range.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import {setup} from '#testHelpers'

test.each([
['ArrowUp', 55],
['ArrowDown', 45],
['ArrowRight', 55],
['ArrowLeft', 45],
] as const)('step a range input with %s', async (key, value) => {
const {element, user} = setup<HTMLInputElement>(
'<input type="range" value="50" step="5">',
)

await user.keyboard(`{${key}}`)

expect(element.valueAsNumber).toBe(value)
})

test('dispatch range input and change after the value has changed', async () => {
const {element, user, getEvents, getEventSnapshot} = setup(
'<input type="range" value="4">',
)

await user.keyboard('{ArrowRight}')

expect(getEventSnapshot()).toMatchInlineSnapshot(`
Events fired on: input[value="5"]

input[value="4"] - keydown: ArrowRight
input[value="5"] - input
input[value="5"] - change
input[value="5"] - keyup: ArrowRight
`)
for (const type of ['input', 'change'] as const) {
expect(getEvents(type)[0].constructor).toBe(
element.ownerDocument.defaultView?.Event,
)
expect(getEvents(type)[0]).toMatchObject({
bubbles: true,
cancelable: false,
composed: type === 'input',
})
}
})

test('respect fractional steps and stop at the range limits', async () => {
const {element, user, getEvents} = setup<HTMLInputElement>(
'<input type="range" min="-0.3" max="0.2" step="0.2" value="-0.1">',
)

await user.keyboard('{ArrowRight}{ArrowRight}')
expect(element.valueAsNumber).toBe(0.1)

await user.keyboard('{ArrowLeft>3/}')
expect(element.valueAsNumber).toBe(-0.3)
expect(getEvents('input')).toHaveLength(3)
expect(getEvents('change')).toHaveLength(3)
})

test.each([
['min="20" max="45"', 40, 40.25],
['', 50, 51],
['min="0" max="1"', 0.999, 1],
['min="5" max="5"', 5, 5],
['min="20x" max="45"', 40, 40.45],
['min="20" max="45x"', 40, 40.8],
['min="999999999999900" max="1000000000000100"', 1e15, 1e15 + 2],
] as const)(
'step with step="any" and bounds %s',
async (bounds, start, end) => {
const {element, user} = setup<HTMLInputElement>(
`<input type="range" ${bounds} step="any" value="${start}">`,
)

await user.keyboard('{ArrowUp}')
expect(element.valueAsNumber).toBe(end)
},
)

test.each([
['direction: rtl', 'ArrowRight', 4],
['writing-mode: vertical-lr', 'ArrowDown', 6],
['writing-mode: vertical-rl; direction: rtl', 'ArrowDown', 4],
] as const)('respect %s for %s', async (style, key, value) => {
const {element, user} = setup<HTMLInputElement>(
`<input type="range" style="${style}" value="5">`,
)

await user.keyboard(`{${key}}`)

expect(element.valueAsNumber).toBe(value)
})

test('leave the range value unchanged when keydown is canceled', async () => {
const {element, user, getEvents} = setup<HTMLInputElement>(
'<input type="range" value="5">',
{eventHandlers: {keydown: e => e.preventDefault()}},
)

await user.keyboard('{ArrowUp}')

expect(element.valueAsNumber).toBe(5)
expect(getEvents().map(e => e.type)).toEqual(['keydown', 'keyup'])
})

test.each([
['dir="rtl"', 'ArrowLeft'],
['style="direction: rtl"', 'ArrowLeft'],
['style="writing-mode: vertical-lr"', 'ArrowDown'],
] as const)('inherit %s from an ancestor', async (attribute, key) => {
const {user, xpathNode} = setup(
`<div ${attribute}><input type="range" value="5"></div>`,
)

await user.keyboard(`{${key}}`)

expect(xpathNode<HTMLInputElement>('div/input').valueAsNumber).toBe(6)
})

test.each(['disabled', 'type'] as const)(
'honor a change to %s in a range keydown handler',
async attribute => {
const {element, user, getEvents} = setup<HTMLInputElement>(
'<input type="range" value="5">',
)
element.addEventListener('keydown', () => {
element.setAttribute(attribute, attribute === 'type' ? 'text' : '')
})

await user.keyboard('{ArrowUp}')

expect(element.value).toBe('5')
expect(getEvents('input')).toHaveLength(0)
expect(getEvents('change')).toHaveLength(0)
},
)