Skip to content

Commit

Permalink
fix: do not exceed upper limit on number field when steps are too large
Browse files Browse the repository at this point in the history
  • Loading branch information
Haberkamp committed Feb 6, 2025
1 parent 1ce7ef2 commit f2822df
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/event/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,15 +224,26 @@ function calculateNewValue(
isElementType(node, 'input', {type: 'number'} as const) &&
inputType === 'changeNumberInput'
) {
const reachedMax = value === node.max
const step = node.step ? Number(node.step) : 1

const reachedMax = value === node.max
if (inputData === 'ArrowUp' && !reachedMax) {
newValue = (Number(value) + step).toString()
const exceedsMax = Number(value) + step > Number(node.max)
if (exceedsMax && !!node.max) {
newValue = node.max
} else {
newValue = (Number(value) + step).toString()
}
}

const reachedMin = value === node.min
if (inputData === 'ArrowDown' && !reachedMin) {
newValue = (Number(value) - step).toString()
const exceedsMin = Number(value) - step < Number(node.min)
if (exceedsMin) {
newValue = node.min
} else {
newValue = (Number(value) - step).toString()
}
}
}

Expand Down
24 changes: 24 additions & 0 deletions tests/event/behavior/keydown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -455,3 +455,27 @@ test("decrements number input's value by the defined steps when pressing the arr

expect(element).toHaveValue(0)
})

test('decrements only to the min value when pressing the arrow down key and steps are too large', async () => {
const {element} = render<HTMLInputElement>(
`<input value="5" type="number" min="0" step="10"/>`,
)

const instance = setupInstance()

instance.dispatchUIEvent(element, 'keydown', {key: 'ArrowDown'})

expect(element).toHaveValue(0)
})

test('increments only to the max value when pressing the arrow up key and steps are too large', async () => {
const {element} = render<HTMLInputElement>(
`<input value="5" type="number" max="10" step="10"/>`,
)

const instance = setupInstance()

instance.dispatchUIEvent(element, 'keydown', {key: 'ArrowUp'})

expect(element).toHaveValue(10)
})

0 comments on commit f2822df

Please sign in to comment.