Skip to content

Commit cc7ab24

Browse files
authored
Upgrade React Aria and validate number fields without clamping (#3377)
This is on top of #3376, which made `NumberField` validate `min` and `max` itself so we could stop relying on react-aria's clamping. This PR upgrades react-aria 3.44 → 3.52.1 and react-stately 3.32 → 3.50.0 and turns off clamping with the new `commitBehavior: 'validate'` option from adobe/react-spectrum#9679 (merged March 2026). It also adds whole-number validation to `NumberField`, which fixes a pre-existing bug: nothing client-side stopped you from submitting `2.5` CPUs. ### What changes for the user Before, typing an out-of-range value and leaving the field rewrote it to the nearest bound. Now, if a value is out of range, or fractional in a field that requires a whole number, submit is blocked and the field shows an error. The validation trigger is still react-hook-form's default: no errors until the first submit attempt, and after that it revalidates on change events. Form state updates on every keystroke that parses to a number, as long as the text is already in canonical form. react-aria's commit would rewrite `007` or `1.0` to `7` or `1`, so those wait for blur or Enter, as they did before. Out-of-range values no longer wait: they used to sit in the input until blur while form state kept the old value, and now they reach form state immediately, which is what lets the error clear as soon as you fix the number. Disk size, min 6 GiB from the selected image: | Step | Before | After | | --- | --- | --- | | Type `5` | `5` | `5` | | Tab away | Box becomes `6`, no message | Box stays `5`, no message | | Click submit | Creates a 6 GiB disk | Blocked, "Must be at least 6 GiB" | | Change to `20` | n/a | Error clears as soon as `20` is in the box | Prefix length on the external subnet form, where the max depends on the selected pool (32 for v4, 128 for v6): | Step | Before | After | | --- | --- | --- | | v6 pool, type `64` | `64` | `64` | | Switch to v4 pool | Box shows `32`, form still holds `64` | Box shows `64` | | Click submit | Sends `prefix_length: 64` (main). On #3376, blocked with "Can be at most 32" under a box that says 32 | Blocked, "Can be at most 32" | | Switch back to v6 | `64` reappears | Error clears, `64` | | Switch to v4 again | Box shows `32`, form holds `64` | Box shows `64`, "Can be at most 32" | The middle row is the bug that motivated this. `useNumberFieldState` clamps the `value` prop we pass in before storing it, so the text in the box was derived from the clamped 32 while the value react-hook-form held (and would submit) was still 64. The validation from #3376 at least prevents submission, but the input still showed the wrong value. With `commitBehavior: 'validate'`, the incoming value is used as-is. ### What stays the same - **Steppers still stop at the bounds.** `commitBehavior` only affects the typed value and the incoming `value` prop. Increment and decrement still go through `snapValueToStep(prev, minValue, maxValue, step)` and the buttons still disable at min and max. Pressing an arrow while the box holds an out-of-range value snaps it to the nearest bound (type `2` with min 10, press up, get `10`). - **Blur and Enter still canonicalize.** `007` becomes `7` and `1.0` becomes `1`, as before. ### Whole-number validation No form passes `step`, so react-aria never snapped typed values to integers. On main, `2.5` in the CPU field is accepted as-is and sent to the API as `ncpus: 2.5`, which Nexus 400s on. This is independent of clamping, but it is fixed here. `NumberField` now checks `Number.isInteger` by default. Typing `2.5` CPUs leaves `2.5` in the box, but submit is blocked with "Must be a whole number". Correcting it to `3` clears the error. This covers CPU counts and CPU quotas, prefix lengths, firewall rule priority, disk sizes, and instance memory, including resize. Memory and storage quotas on silo create and quota edit opt into `allowDecimals`. Those fields are entered in GiB and converted to bytes, so values like `1.5 GiB` are allowed. Instance memory and disk sizes still require whole GiB because the API enforces [1 GiB alignment for memory](https://github.com/oxidecomputer/omicron/blob/17e6fee5320ad8f1fb4cbfd3d6328b808fca7124/nexus/src/app/instance.rs#L2894-L2908) and [disk sizes](https://github.com/oxidecomputer/omicron/blob/17e6fee5320ad8f1fb4cbfd3d6328b808fca7124/nexus/src/app/disk.rs#L230-L244). Allowing decimals there exposed a pre-existing bug: the quota forms multiplied GiB by 2^30 without rounding, so `1.1 GiB` sent a fractional byte count that the API rejects at deserialization. The last commit rounds to whole bytes in both submit handlers. One thing left for a follow-up: the mock API accepts fractional CPU counts and unaligned sizes that Nexus would reject. The fix is in the next PR in the stack: #3380. ### Tests Every existing assertion that a value got clamped, in the `NumberInput` browser spec and in the e2e specs for disks, instance create, and external subnets, is rewritten to assert the value stays put and the error appears. New `NumberInput` cases cover the steppers stopping at the bounds and snapping an out-of-range typed value back into range. A new `NumberField` browser spec covers the whole-number rule and `allowDecimals`. The external subnet test is the regression test for the faux-clamping bug: type `64` on a v4 pool, submit, switch to v6 and back. It fails on main and on #3376, where the box shows 32. ### React Aria packaging change The lockfile got 1700 lines shorter because react-aria and react-stately now ship as single packages instead of dozens of `@react-aria/*` and `@react-stately/*` deps, which also forced two imports in `Popover.tsx` and `DateField.tsx` to move to the top-level package.
1 parent c187b75 commit cc7ab24

13 files changed

Lines changed: 442 additions & 1986 deletions
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
* This Source Code Form is subject to the terms of the Mozilla Public
3+
* License, v. 2.0. If a copy of the MPL was not distributed with this
4+
* file, you can obtain one at https://mozilla.org/MPL/2.0/.
5+
*
6+
* Copyright Oxide Computer Company
7+
*/
8+
import { useState } from 'react'
9+
import { useForm } from 'react-hook-form'
10+
import { expect, test } from 'vitest'
11+
import { render } from 'vitest-browser-react'
12+
13+
import { NumberField } from './NumberField'
14+
15+
function Harness({
16+
defaultValue = 2,
17+
allowDecimals = false,
18+
required = true,
19+
}: {
20+
defaultValue?: number
21+
allowDecimals?: boolean
22+
required?: boolean
23+
}) {
24+
const form = useForm({ defaultValues: { count: defaultValue } })
25+
const [submitted, setSubmitted] = useState<number>()
26+
return (
27+
<form onSubmit={form.handleSubmit(({ count }) => setSubmitted(count))}>
28+
<NumberField
29+
name="count"
30+
label="Count"
31+
control={form.control}
32+
required={required}
33+
allowDecimals={allowDecimals}
34+
/>
35+
<button type="submit">Save</button>
36+
<output>Submitted: {submitted ?? 'none'}</output>
37+
</form>
38+
)
39+
}
40+
41+
test('rejects a fractional value already in form state', async () => {
42+
const screen = await render(<Harness defaultValue={2.5} />)
43+
await screen.getByRole('button', { name: 'Save' }).click()
44+
await expect.element(screen.getByText('Must be a whole number')).toBeVisible()
45+
await expect.element(screen.getByText('Submitted: none')).toBeVisible()
46+
})
47+
48+
test('keeps a typed fraction, blocks submit, and clears the error when corrected', async () => {
49+
const screen = await render(<Harness />)
50+
const input = screen.getByRole('textbox', { name: 'Count' })
51+
await input.fill('2.5')
52+
await screen.getByRole('button', { name: 'Save' }).click()
53+
await expect.element(input).toHaveValue('2.5')
54+
await expect.element(screen.getByText('Must be a whole number')).toBeVisible()
55+
await expect.element(screen.getByText('Submitted: none')).toBeVisible()
56+
await input.fill('3')
57+
await expect.element(screen.getByText('Must be a whole number')).not.toBeInTheDocument()
58+
await screen.getByRole('button', { name: 'Save' }).click()
59+
await expect.element(screen.getByText('Submitted: 3')).toBeVisible()
60+
})
61+
62+
test('allows fractional quota values when decimals are enabled', async () => {
63+
const screen = await render(<Harness allowDecimals />)
64+
const input = screen.getByRole('textbox', { name: 'Count' })
65+
await input.fill('1.5')
66+
await screen.getByRole('button', { name: 'Save' }).click()
67+
await expect.element(input).toHaveValue('1.5')
68+
await expect.element(screen.getByText('Submitted: 1.5')).toBeVisible()
69+
})
70+
71+
test('still accepts an empty optional field', async () => {
72+
const screen = await render(<Harness required={false} />)
73+
await screen.getByRole('textbox', { name: 'Count' }).clear()
74+
await screen.getByRole('button', { name: 'Save' }).click()
75+
await expect.element(screen.getByText('Submitted: NaN')).toBeVisible()
76+
})

‎app/components/form/fields/NumberField.tsx‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,14 @@ import { capitalize } from '~/util/str'
1717
import { ErrorMessage } from './ErrorMessage'
1818
import type { TextFieldProps } from './TextField'
1919

20+
type NumberFieldProps<
21+
T extends FieldValues,
22+
N extends FieldPathByValue<T, number>,
23+
> = TextFieldProps<T, N> & {
24+
/** Counts and resource sizes require whole numbers; byte quotas can use fractional GiB. */
25+
allowDecimals?: boolean
26+
}
27+
2028
export function NumberField<
2129
TFieldValues extends FieldValues,
2230
// can only be used on fields with number values
@@ -28,7 +36,7 @@ export function NumberField<
2836
description,
2937
required,
3038
...props
31-
}: Omit<TextFieldProps<TFieldValues, TName>, 'id'>) {
39+
}: Omit<NumberFieldProps<TFieldValues, TName>, 'id'>) {
3240
// id is omitted from props because we generate it here
3341
const id = useId()
3442
return (
@@ -79,8 +87,9 @@ export const NumberFieldInner = <
7987
disabled,
8088
max,
8189
min = 0,
90+
allowDecimals = false,
8291
units,
83-
}: TextFieldProps<TFieldValues, TName>) => {
92+
}: NumberFieldProps<TFieldValues, TName>) => {
8493
const generatedId = useId()
8594
const id = idProp || generatedId
8695

@@ -98,6 +107,7 @@ export const NumberFieldInner = <
98107
// clamps, so this is what stops out-of-range values.
99108
validate(value, values) {
100109
if (Number.isNaN(value)) return required ? `${label} is required` : undefined
110+
if (!allowDecimals && !Number.isInteger(value)) return 'Must be a whole number'
101111
const suffix = units ? ` ${units}` : ''
102112
if (min !== undefined && value < Number(min))
103113
return `Must be at least ${min}${suffix}`

‎app/forms/silo-create.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,10 @@ export default function CreateSiloSideModalForm() {
106106
mappedFleetRoles,
107107
quotas: {
108108
cpus: quotas.cpus,
109-
memory: quotas.memory * GiB,
110-
storage: quotas.storage * GiB,
109+
// fractional GiB can produce a fractional byte count, which the API rejects.
110+
// Ceil rather than round so the quota is never less than what was asked for
111+
memory: Math.ceil(quotas.memory * GiB),
112+
storage: Math.ceil(quotas.storage * GiB),
111113
},
112114
...rest,
113115
},
@@ -134,13 +136,15 @@ export default function CreateSiloSideModalForm() {
134136
control={form.control}
135137
label="Memory quota"
136138
name="quotas.memory"
139+
allowDecimals
137140
required
138141
units="GiB"
139142
/>
140143
<NumberField
141144
control={form.control}
142145
label="Storage quota"
143146
name="quotas.storage"
147+
allowDecimals
144148
required
145149
units="GiB"
146150
/>

‎app/forms/silo-quotas-edit.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,9 +77,11 @@ export function EditQuotasSideModalForm({ silo, quotas, provisioned, onDismiss }
7777
updateQuotas.mutate({
7878
body: {
7979
cpus,
80-
memory: memory * GiB,
80+
// fractional GiB can produce a fractional byte count, which the API rejects.
81+
// Ceil rather than round so the quota is never less than what was asked for
82+
memory: Math.ceil(memory * GiB),
8183
// TODO: we use GiB on instance create but TiB on utilization. HM
82-
storage: storage * GiB,
84+
storage: Math.ceil(storage * GiB),
8385
},
8486
path: { silo },
8587
})
@@ -105,6 +107,7 @@ export function EditQuotasSideModalForm({ silo, quotas, provisioned, onDismiss }
105107
<div>
106108
<NumberField
107109
name="memory"
110+
allowDecimals
108111
label="Memory"
109112
units="GiB"
110113
required
@@ -115,6 +118,7 @@ export function EditQuotasSideModalForm({ silo, quotas, provisioned, onDismiss }
115118
<div>
116119
<NumberField
117120
name="storage"
121+
allowDecimals
118122
label="Storage"
119123
units="GiB"
120124
required

‎app/ui/lib/DateField.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@
66
* Copyright Oxide Computer Company
77
*/
88
import { createCalendar, type DateValue } from '@internationalized/date'
9-
import type { TimeValue } from '@react-types/datepicker'
109
import cn from 'classnames'
1110
import { useRef } from 'react'
11+
import type { TimeValue } from 'react-aria'
1212
import {
1313
useDateField,
1414
useDateSegment,

‎app/ui/lib/NumberInput.browser.spec.tsx‎

Lines changed: 43 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -57,29 +57,54 @@ test('fires onChange with NaN when the input is cleared', async () => {
5757
await expect.element(screen.getByText('Changes: NaN')).toBeVisible()
5858
})
5959

60-
test('clamps typed values above maxValue on blur', async () => {
61-
const screen = await render(<NumberInputHarness value={5} maxValue={100} />)
60+
test('does not clamp typed values to minValue or maxValue', async () => {
61+
const screen = await render(
62+
<NumberInputHarness value={15} minValue={10} maxValue={100} />
63+
)
6264
const input = screen.getByRole('textbox', { name: 'Test number' })
6365

64-
// out-of-range values are left alone while editing, not clamped mid-keystroke
66+
// over max: the text stays as typed and the parent sees the typed value
67+
// right away, not only on blur
6568
await input.fill('150')
6669
await expect.element(input).toHaveValue('150')
67-
70+
await expect.element(screen.getByText('Changes: 150')).toBeVisible()
6871
await userEvent.tab()
69-
await expect.element(screen.getByText('Changes: 100')).toBeVisible()
70-
await expect.element(input).toHaveValue('100')
72+
await expect.element(input).toHaveValue('150')
73+
74+
// under min
75+
await input.fill('2')
76+
await userEvent.keyboard('{Enter}')
77+
await expect.element(input).toHaveValue('2')
78+
await expect.element(screen.getByText('Changes: 150, 2')).toBeVisible()
7179
})
7280

73-
test('clamps typed values below minValue on blur', async () => {
74-
const screen = await render(<NumberInputHarness minValue={1} value={5} />)
81+
test('steppers stop at minValue and maxValue', async () => {
82+
const screen = await render(<NumberInputHarness value={9} minValue={8} maxValue={10} />)
7583
const input = screen.getByRole('textbox', { name: 'Test number' })
84+
const increase = screen.getByRole('button', { name: 'Increase Test number' })
85+
const decrease = screen.getByRole('button', { name: 'Decrease Test number' })
7686

77-
await input.fill('0')
78-
await expect.element(input).toHaveValue('0')
87+
await increase.click()
88+
await expect.element(input).toHaveValue('10')
89+
await expect.element(increase).toBeDisabled()
7990

80-
await userEvent.tab()
81-
await expect.element(screen.getByText('Changes: 1')).toBeVisible()
82-
await expect.element(input).toHaveValue('1')
91+
await decrease.click()
92+
await decrease.click()
93+
await expect.element(input).toHaveValue('8')
94+
await expect.element(decrease).toBeDisabled()
95+
})
96+
97+
test('stepping an out-of-range typed value lands in range', async () => {
98+
const screen = await render(<NumberInputHarness minValue={10} maxValue={20} />)
99+
const input = screen.getByRole('textbox', { name: 'Test number' })
100+
101+
await input.fill('2')
102+
await screen.getByRole('button', { name: 'Increase Test number' }).click()
103+
await expect.element(input).toHaveValue('10')
104+
105+
await input.fill('50')
106+
await screen.getByRole('button', { name: 'Decrease Test number' }).click()
107+
await expect.element(input).toHaveValue('20')
83108
})
84109

85110
test('does not clamp intermediate input while typing', async () => {
@@ -95,7 +120,7 @@ test('does not clamp intermediate input while typing', async () => {
95120
await expect.element(input).toHaveValue('20')
96121
})
97122

98-
test('does not step intermediate input while typing', async () => {
123+
test('does not snap typed values to step', async () => {
99124
const screen = await render(<NumberInputHarness step={1} minValue={10} />)
100125
const input = screen.getByRole('textbox', { name: 'Test number' })
101126

@@ -106,7 +131,7 @@ test('does not step intermediate input while typing', async () => {
106131
await expect.element(input).toHaveValue('20.1')
107132

108133
await userEvent.tab()
109-
await expect.element(input).toHaveValue('20')
134+
await expect.element(input).toHaveValue('20.1')
110135
})
111136

112137
test('only simplifies numbers on blur', async () => {
@@ -135,9 +160,9 @@ test('still controls the displayed value when onChange causes no re-render', asy
135160

136161
await input.fill('1099')
137162
await userEvent.tab()
138-
await expect.element(input).toHaveValue('1023')
163+
await expect.element(input).toHaveValue('1099')
139164

140-
await input.fill('10239')
165+
await input.fill('007')
141166
await userEvent.tab()
142-
await expect.element(input).toHaveValue('1023')
167+
await expect.element(input).toHaveValue('7')
143168
})

‎app/ui/lib/NumberInput.tsx‎

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,12 @@ type NumberInputProps = AriaNumberFieldProps & {
2424
ref?: Ref<HTMLInputElement>
2525
}
2626

27-
export function NumberInput(props: NumberInputProps) {
27+
export function NumberInput(rawProps: NumberInputProps) {
28+
// 'validate' turns off clamping on commit and on the incoming value. A typed
29+
// value outside min/max stays as typed and it is the form's job to reject it
30+
// with a validation message. The steppers still stop at the bounds.
31+
// https://github.com/adobe/react-spectrum/pull/9679
32+
const props = { ...rawProps, commitBehavior: 'validate' as const }
2833
const { locale } = useLocale()
2934
const state = useNumberFieldState({ ...props, locale })
3035

@@ -33,31 +38,22 @@ export function NumberInput(props: NumberInputProps) {
3338
useNumberField(props, state, inputRef)
3439

3540
// react-aria only fires props.onChange on commit (blur / Enter / stepper),
36-
// but we want form state to update as soon as it would produce a different
37-
// field value. Committing whenever state.inputValue changes to an
41+
// but we want form state to update on every keystroke that produces a
42+
// different number. Committing whenever state.inputValue changes to an
3843
// unambiguous number lets react-aria keep control, but forces it to be more
39-
// eager.
44+
// eager. https://github.com/adobe/react-spectrum/issues/7984
4045
//
41-
// Context: https://github.com/adobe/react-spectrum/issues/7984
42-
//
43-
// HOWEVER! This eagerness should only apply if it doesn't get in the user's
44-
// way, and so we check whether the bounds/stepping/formatting would rewrite
45-
// the field post-commit before going ahead.
46-
//
47-
// Context: https://github.com/adobe/react-spectrum/blob/4682b6d6eee6f2d5d0b63c5e340c21a27f4d5ec1/packages/react-stately/src/numberfield/useNumberFieldState.ts#L88
46+
// Commit would still reformat the text (e.g. "1.0" -> "1", "007" -> "7"),
47+
// which would fight the user mid-edit, so hold off until the text is already
48+
// in canonical form.
4849
const formatter = useNumberFormatter(props.formatOptions)
4950
useEffect(() => {
5051
if (state.inputValue === '') {
5152
state.commit()
5253
return
5354
}
54-
55-
const { numberValue } = state
56-
if (Number.isNaN(numberValue)) return
57-
if (state.minValue != null && numberValue < state.minValue) return
58-
if (state.maxValue != null && numberValue > state.maxValue) return
59-
if (props.step && (numberValue - (state.minValue ?? 0)) % props.step !== 0) return
60-
if (formatter.format(numberValue) !== state.inputValue) return
55+
if (Number.isNaN(state.numberValue)) return
56+
if (formatter.format(state.numberValue) !== state.inputValue) return
6157
state.commit()
6258
// eslint-disable-next-line exhaustive-deps
6359
}, [state.inputValue])

‎app/ui/lib/Popover.tsx‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,12 @@
1+
import { useRef, type ReactNode } from 'react'
12
/*
23
* This Source Code Form is subject to the terms of the Mozilla Public
34
* License, v. 2.0. If a copy of the MPL was not distributed with this
45
* file, you can obtain one at https://mozilla.org/MPL/2.0/.
56
*
67
* Copyright Oxide Computer Company
78
*/
8-
import {
9-
DismissButton,
10-
Overlay,
11-
usePopover,
12-
type AriaPopoverProps,
13-
} from '@react-aria/overlays'
14-
import { useRef, type ReactNode } from 'react'
9+
import { DismissButton, Overlay, usePopover, type AriaPopoverProps } from 'react-aria'
1510
import type { OverlayTriggerState } from 'react-stately'
1611

1712
interface PopoverProps extends Omit<AriaPopoverProps, 'popoverRef'> {

0 commit comments

Comments
 (0)