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

[field controls] Respect validationMode #1053

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
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
23 changes: 23 additions & 0 deletions docs/src/app/(private)/experiments/field.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as React from 'react';
import { Field } from '@base-ui-components/react/field';
import { Checkbox } from '@base-ui-components/react/checkbox';

function CheckboxDemo() {
return (
<Field.Root style={{ display: 'flex', gap: 10 }}>
<Field.Label>Checkbox</Field.Label>
<Checkbox.Root required style={{ width: 20, height: 20, padding: 0 }}>
<Checkbox.Indicator>+</Checkbox.Indicator>
</Checkbox.Root>
<Field.Error style={{ color: 'red' }} />
</Field.Root>
);
}

export default function FieldControls() {
return (
<div>
<CheckboxDemo />
</div>
);
}
18 changes: 15 additions & 3 deletions packages/react/src/checkbox/root/useCheckboxRoot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ export function useCheckboxRoot(params: UseCheckboxRoot.Parameters): UseCheckbox
state: 'checked',
});

const { labelId, setControlId, setTouched, setDirty, validityData } = useFieldRootContext();
const { labelId, setControlId, setTouched, setDirty, validityData, validationMode } =
useFieldRootContext();

const buttonRef = React.useRef<HTMLButtonElement>(null);

Expand Down Expand Up @@ -92,8 +93,12 @@ export function useCheckboxRoot(params: UseCheckboxRoot.Parameters): UseCheckbox
if (!element) {
return;
}

setTouched(true);
commitValidation(element.checked);

if (validationMode === 'onBlur') {
commitValidation(element.checked);
}
},
onClick(event) {
if (event.defaultPrevented || readOnly) {
Expand All @@ -107,12 +112,13 @@ export function useCheckboxRoot(params: UseCheckboxRoot.Parameters): UseCheckbox
}),
[
getValidationProps,
disabled,
indeterminate,
checked,
disabled,
readOnly,
labelId,
setTouched,
validationMode,
commitValidation,
],
);
Expand Down Expand Up @@ -143,6 +149,10 @@ export function useCheckboxRoot(params: UseCheckboxRoot.Parameters): UseCheckbox
setCheckedState(nextChecked);
onCheckedChange?.(nextChecked, event.nativeEvent);

if (validationMode === 'onChange') {
commitValidation(nextChecked);
}

if (name && groupValue && setGroupValue) {
const nextGroupValue = nextChecked
? [...groupValue, name]
Expand All @@ -164,8 +174,10 @@ export function useCheckboxRoot(params: UseCheckboxRoot.Parameters): UseCheckbox
validityData.initialValue,
setCheckedState,
onCheckedChange,
validationMode,
groupValue,
setGroupValue,
commitValidation,
],
);

Expand Down
11 changes: 8 additions & 3 deletions packages/react/src/field/control/useFieldControl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import { useEventCallback } from '../../utils/useEventCallback';
export function useFieldControl(params: useFieldControl.Parameters) {
const { id: idProp, name, value: valueProp, defaultValue, onValueChange, disabled } = params;

const { setControlId, labelId, setTouched, setDirty, validityData } = useFieldRootContext();
const { setControlId, labelId, setTouched, setDirty, validityData, validationMode } =
useFieldRootContext();

const { errors, onClearErrors } = useFormContext();

Expand Down Expand Up @@ -73,7 +74,10 @@ export function useFieldControl(params: useFieldControl.Parameters) {
},
onBlur(event) {
setTouched(true);
commitValidation(event.currentTarget.value);

if (validationMode === 'onBlur') {
commitValidation(event.currentTarget.value);
}
},
onKeyDown(event) {
if (event.currentTarget.tagName === 'INPUT' && event.key === 'Enter') {
Expand All @@ -91,12 +95,13 @@ export function useFieldControl(params: useFieldControl.Parameters) {
inputRef,
labelId,
value,
setValue,
setDirty,
validityData.initialValue,
errors,
setValue,
onClearErrors,
setTouched,
validationMode,
commitValidation,
],
);
Expand Down
71 changes: 52 additions & 19 deletions packages/react/src/field/root/FieldRoot.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -278,29 +278,62 @@ describe('<Field.Root />', () => {
});

describe('prop: validationMode', () => {
it('should validate the field on change', async () => {
await render(
<Field.Root
validationMode="onChange"
validate={(value) => {
const str = value as string;
return str.length < 3 ? 'error' : null;
}}
>
<Field.Control />
<Field.Error />
</Field.Root>,
);
describe('onChange', () => {
it('should validate the field on change', async () => {
await render(
<Field.Root
validationMode="onChange"
validate={(value) => {
const str = value as string;
return str.length < 3 ? 'error' : null;
}}
>
<Field.Control />
<Field.Error />
</Field.Root>,
);

const control = screen.getByRole<HTMLInputElement>('textbox');
const message = screen.queryByText('error');
const control = screen.getByRole<HTMLInputElement>('textbox');
const message = screen.queryByText('error');

expect(message).to.equal(null);
expect(message).to.equal(null);

fireEvent.change(control, { target: { value: 't' } });
fireEvent.change(control, { target: { value: 't' } });

expect(control).to.have.attribute('data-invalid', '');
expect(control).to.have.attribute('aria-invalid', 'true');
expect(control).to.have.attribute('data-invalid', '');
expect(control).to.have.attribute('aria-invalid', 'true');
});
});

describe('onBlur', () => {
it('should validate the field on blur', async () => {
await render(
<Field.Root
validationMode="onBlur"
validate={(value) => {
const str = value as string;
return str.length < 3 ? 'error' : null;
}}
>
<Field.Control />
<Field.Error />
</Field.Root>,
);

const control = screen.getByRole<HTMLInputElement>('textbox');
const message = screen.queryByText('error');

expect(message).to.equal(null);

fireEvent.change(control, { target: { value: 't' } });

expect(control).not.to.have.attribute('data-invalid');

fireEvent.blur(control);

expect(control).to.have.attribute('data-invalid', '');
expect(control).to.have.attribute('aria-invalid', 'true');
});
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,10 @@ export function useNumberFieldRoot(
}

setTouched(true);
commitValidation(valueRef.current);

if (validationMode === 'onBlur') {
commitValidation(valueRef.current);
}

allowInputSyncRef.current = true;

Expand Down Expand Up @@ -729,6 +732,7 @@ export function useNumberFieldRoot(
invalid,
labelId,
setTouched,
validationMode,
formatOptionsRef,
commitValidation,
valueRef,
Expand Down
13 changes: 11 additions & 2 deletions packages/react/src/radio-group/useRadioGroup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ import { useField } from '../field/useField';
export function useRadioGroup(params: useRadioGroup.Parameters) {
const { disabled = false, name, defaultValue, readOnly, value: externalValue } = params;

const { labelId, setControlId, setTouched: setFieldTouched } = useFieldRootContext();
const {
labelId,
setControlId,
setTouched: setFieldTouched,
validationMode,
} = useFieldRootContext();

const {
getValidationProps,
Expand Down Expand Up @@ -62,7 +67,10 @@ export function useRadioGroup(params: useRadioGroup.Parameters) {
onBlur(event) {
if (!contains(event.currentTarget, event.relatedTarget)) {
setFieldTouched(true);
commitValidation(checkedValue);

if (validationMode === 'onBlur') {
commitValidation(checkedValue);
}
}
},
onKeyDownCapture(event) {
Expand All @@ -80,6 +88,7 @@ export function useRadioGroup(params: useRadioGroup.Parameters) {
labelId,
readOnly,
setFieldTouched,
validationMode,
],
);

Expand Down
1 change: 1 addition & 0 deletions packages/react/src/select/root/SelectRoot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ const SelectRoot: SelectRoot = function SelectRoot<Value>(
if (exactValue != null) {
setDirty(exactValue !== validityData.initialValue);
rootContext.setValue?.(exactValue, event.nativeEvent);
selectRoot.rootContext.fieldControlValidation.commitValidation(exactValue);
}
},
id: rootContext.id,
Expand Down
8 changes: 6 additions & 2 deletions packages/react/src/select/trigger/useSelectTrigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function useSelectTrigger(
readOnly,
} = useSelectRootContext();

const { labelId, setTouched } = useFieldRootContext();
const { labelId, setTouched, validationMode } = useFieldRootContext();

const triggerRef = React.useRef<HTMLElement | null>(null);
const timeoutRef = React.useRef(-1);
Expand Down Expand Up @@ -91,7 +91,10 @@ export function useSelectTrigger(
},
onBlur() {
setTouched(true);
fieldControlValidation.commitValidation(value);

if (validationMode === 'onBlur') {
fieldControlValidation.commitValidation(value);
}
},
onPointerMove({ pointerType }) {
setTouchModality(pointerType === 'touch');
Expand Down Expand Up @@ -154,6 +157,7 @@ export function useSelectTrigger(
value,
setTouchModality,
positionerElement,
validationMode,
],
);

Expand Down
19 changes: 2 additions & 17 deletions packages/react/src/slider/root/useSliderRoot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { percentToValue, roundValueToStep, valueToPercent } from '../utils';
import { asc } from '../utils/asc';
import { setValueIndex } from '../utils/setValueIndex';
import { getSliderValue } from '../utils/getSliderValue';
import { useEventCallback } from '../../utils/useEventCallback';

function findClosest(values: number[], currentValue: number) {
const { index: closestIndex } =
Expand Down Expand Up @@ -254,7 +255,7 @@ export function useSliderRoot(parameters: useSliderRoot.Parameters): useSliderRo
[valueState],
);

const changeValue = React.useCallback(
const changeValue = useEventCallback(
(valueInput: number, index: number, event: React.KeyboardEvent | React.ChangeEvent) => {
const newValue = getSliderValue({
valueInput,
Expand Down Expand Up @@ -285,22 +286,6 @@ export function useSliderRoot(parameters: useSliderRoot.Parameters): useSliderRo
}
}
},
[
min,
max,
range,
step,
minStepsBetweenValues,
values,
setValueState,
setDirty,
validityData.initialValue,
handleValueChange,
areValuesEqual,
onValueCommitted,
setTouched,
commitValidation,
],
);

const previousIndexRef = React.useRef<number | null>(null);
Expand Down
27 changes: 16 additions & 11 deletions packages/react/src/slider/thumb/useSliderThumb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export function useSliderThumb(parameters: useSliderThumb.Parameters): useSlider
values: sliderValues,
} = parameters;

const { setTouched } = useFieldRootContext();
const { setTouched, validationMode } = useFieldRootContext();
const {
getInputValidationProps,
inputRef: inputValidationRef,
Expand Down Expand Up @@ -129,17 +129,21 @@ export function useSliderThumb(parameters: useSliderThumb.Parameters): useSlider
if (!thumbRef.current) {
return;
}

setTouched(true);
commitValidation(
getSliderValue({
valueInput: thumbValue,
min,
max,
index,
range: sliderValues.length > 1,
values: sliderValues,
}),
);

if (validationMode === 'onBlur') {
commitValidation(
getSliderValue({
valueInput: thumbValue,
min,
max,
index,
range: sliderValues.length > 1,
values: sliderValues,
}),
);
}
},
onKeyDown(event: React.KeyboardEvent) {
let newValue = null;
Expand Down Expand Up @@ -227,6 +231,7 @@ export function useSliderThumb(parameters: useSliderThumb.Parameters): useSlider
tabIndex,
thumbId,
thumbValue,
validationMode,
],
);

Expand Down
Loading
Loading