Skip to content

Commit f2822df

Browse files
committed
fix: do not exceed upper limit on number field when steps are too large
1 parent 1ce7ef2 commit f2822df

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

src/event/input.ts

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -224,15 +224,26 @@ function calculateNewValue(
224224
isElementType(node, 'input', {type: 'number'} as const) &&
225225
inputType === 'changeNumberInput'
226226
) {
227-
const reachedMax = value === node.max
228227
const step = node.step ? Number(node.step) : 1
228+
229+
const reachedMax = value === node.max
229230
if (inputData === 'ArrowUp' && !reachedMax) {
230-
newValue = (Number(value) + step).toString()
231+
const exceedsMax = Number(value) + step > Number(node.max)
232+
if (exceedsMax && !!node.max) {
233+
newValue = node.max
234+
} else {
235+
newValue = (Number(value) + step).toString()
236+
}
231237
}
232238

233239
const reachedMin = value === node.min
234240
if (inputData === 'ArrowDown' && !reachedMin) {
235-
newValue = (Number(value) - step).toString()
241+
const exceedsMin = Number(value) - step < Number(node.min)
242+
if (exceedsMin) {
243+
newValue = node.min
244+
} else {
245+
newValue = (Number(value) - step).toString()
246+
}
236247
}
237248
}
238249

tests/event/behavior/keydown.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,3 +455,27 @@ test("decrements number input's value by the defined steps when pressing the arr
455455

456456
expect(element).toHaveValue(0)
457457
})
458+
459+
test('decrements only to the min value when pressing the arrow down key and steps are too large', async () => {
460+
const {element} = render<HTMLInputElement>(
461+
`<input value="5" type="number" min="0" step="10"/>`,
462+
)
463+
464+
const instance = setupInstance()
465+
466+
instance.dispatchUIEvent(element, 'keydown', {key: 'ArrowDown'})
467+
468+
expect(element).toHaveValue(0)
469+
})
470+
471+
test('increments only to the max value when pressing the arrow up key and steps are too large', async () => {
472+
const {element} = render<HTMLInputElement>(
473+
`<input value="5" type="number" max="10" step="10"/>`,
474+
)
475+
476+
const instance = setupInstance()
477+
478+
instance.dispatchUIEvent(element, 'keydown', {key: 'ArrowUp'})
479+
480+
expect(element).toHaveValue(10)
481+
})

0 commit comments

Comments
 (0)