-
Notifications
You must be signed in to change notification settings - Fork 1.3k
fix(accessibility): Field announce error message for focused field #8329
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
Open
majornista
wants to merge
5
commits into
main
Choose a base branch
from
Issue-8328-field-error-announcement
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
88de236
fix(accessibility): Field announce error message for focused field
majornista a11cd41
fix(accessibility): refactor announcement into useFormValidation
majornista 758c44e
Update packages/@react-aria/form/src/useFormValidation.ts
majornista 9fb96f1
fix(accessibility): add announcement of error message for a just blur…
majornista 2fb28d7
fix(accessibility): improve announcement of error message for a just …
majornista File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
{ | ||
"invalidValue": "Invalid value.", | ||
"reviewField": "Please review {accessibleName} field: {validationMessage}" | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -10,25 +10,57 @@ | |||||
* governing permissions and limitations under the License. | ||||||
*/ | ||||||
|
||||||
import {announce} from '@react-aria/live-announcer'; | ||||||
import {computeAccessibleName} from 'dom-accessibility-api'; | ||||||
import {FormValidationState} from '@react-stately/form'; | ||||||
import {getActiveElement, getOwnerDocument, useEffectEvent, useLayoutEffect} from '@react-aria/utils'; | ||||||
// @ts-ignore | ||||||
import intlMessages from '../intl/*.json'; | ||||||
import {RefObject, Validation, ValidationResult} from '@react-types/shared'; | ||||||
import {setInteractionModality} from '@react-aria/interactions'; | ||||||
import {useEffect} from 'react'; | ||||||
import {useEffectEvent, useLayoutEffect} from '@react-aria/utils'; | ||||||
import {useEffect, useRef} from 'react'; | ||||||
import {useLocalizedStringFormatter} from '@react-aria/i18n'; | ||||||
|
||||||
type ValidatableElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement; | ||||||
|
||||||
function isValidatableElement(element: Element): boolean { | ||||||
return element instanceof HTMLInputElement || | ||||||
element instanceof HTMLTextAreaElement || | ||||||
element instanceof HTMLSelectElement; | ||||||
} | ||||||
|
||||||
interface FormValidationProps<T> extends Validation<T> { | ||||||
focus?: () => void | ||||||
} | ||||||
|
||||||
export function useFormValidation<T>(props: FormValidationProps<T>, state: FormValidationState, ref: RefObject<ValidatableElement | null> | undefined): void { | ||||||
let {validationBehavior, focus} = props; | ||||||
|
||||||
let justBlurredRef = useRef(false); | ||||||
let timeoutIdRef = useRef<ReturnType<typeof setTimeout> | null>(null); | ||||||
function announceErrorMessage(errorMessage: string = ''): void { | ||||||
if (timeoutIdRef.current != null) { | ||||||
clearTimeout(timeoutIdRef.current); | ||||||
timeoutIdRef.current = null; | ||||||
} | ||||||
if (ref && ref.current && errorMessage !== '' && ( | ||||||
ref.current.contains(getActiveElement(getOwnerDocument(ref.current))) || | ||||||
justBlurredRef.current | ||||||
) | ||||||
) { | ||||||
timeoutIdRef.current = setTimeout(() => announce(errorMessage, 'polite'), 250); | ||||||
} | ||||||
} | ||||||
|
||||||
let stringFormatter = useLocalizedStringFormatter(intlMessages, '@react-aria/form'); | ||||||
|
||||||
// This is a useLayoutEffect so that it runs before the useEffect in useFormValidationState, which commits the validation change. | ||||||
useLayoutEffect(() => { | ||||||
if (validationBehavior === 'native' && ref?.current && !ref.current.disabled) { | ||||||
let errorMessage = state.realtimeValidation.isInvalid ? state.realtimeValidation.validationErrors.join(' ') || 'Invalid value.' : ''; | ||||||
let errorMessage = | ||||||
state.realtimeValidation.isInvalid ? | ||||||
(state.realtimeValidation.validationErrors?.join(' ') || stringFormatter.format('invalidValue') || '') : | ||||||
''; | ||||||
ref.current.setCustomValidity(errorMessage); | ||||||
|
||||||
// Prevent default tooltip for validation message. | ||||||
|
@@ -56,11 +88,17 @@ export function useFormValidation<T>(props: FormValidationProps<T>, state: FormV | |||||
|
||||||
// Auto focus the first invalid input in a form, unless the error already had its default prevented. | ||||||
let form = ref?.current?.form; | ||||||
if (!e.defaultPrevented && ref && form && getFirstInvalidInput(form) === ref.current) { | ||||||
if (focus) { | ||||||
focus(); | ||||||
} else { | ||||||
ref.current?.focus(); | ||||||
if (!e.defaultPrevented && ref && form) { | ||||||
|
||||||
// Announce the current error message | ||||||
announceErrorMessage(ref?.current?.validationMessage || ''); | ||||||
|
||||||
if (getFirstInvalidInput(form) === ref.current) { | ||||||
if (focus) { | ||||||
focus(); | ||||||
} else { | ||||||
ref.current?.focus(); | ||||||
} | ||||||
} | ||||||
|
||||||
// Always show focus ring. | ||||||
|
@@ -75,25 +113,64 @@ export function useFormValidation<T>(props: FormValidationProps<T>, state: FormV | |||||
state.commitValidation(); | ||||||
}); | ||||||
|
||||||
let onBlur = useEffectEvent((event: Event) => { | ||||||
const input = ref?.current; | ||||||
const relatedTarget = (event as FocusEvent).relatedTarget as Element | null; | ||||||
if ( | ||||||
(!input || !input.validationMessage) || | ||||||
(relatedTarget && isValidatableElement(relatedTarget) && (relatedTarget as ValidatableElement).validationMessage) | ||||||
) { | ||||||
// If the input has no validation message, | ||||||
// or the relatedTarget has a validation message, don't announce the error message. | ||||||
// This prevents announcing the error message when the user is navigating | ||||||
// between inputs that may already have an error message. | ||||||
return; | ||||||
} | ||||||
justBlurredRef.current = true; | ||||||
const isRadioOrCheckbox = input.type === 'radio' || input.type === 'checkbox'; | ||||||
const groupElement = isRadioOrCheckbox ? input.closest('[role="group"][aria-labelledby], [role=\'group\'][aria-label], fieldset') : undefined; | ||||||
// Announce the current error message | ||||||
const accessibleName = computeAccessibleName(groupElement || input); | ||||||
const validationMessage = input.validationMessage; | ||||||
announceErrorMessage( | ||||||
accessibleName && validationMessage ? | ||||||
stringFormatter.format( | ||||||
'reviewField', | ||||||
{ | ||||||
accessibleName, | ||||||
validationMessage | ||||||
}) : | ||||||
validationMessage | ||||||
); | ||||||
justBlurredRef.current = false; | ||||||
}); | ||||||
|
||||||
useEffect(() => { | ||||||
let input = ref?.current; | ||||||
if (!input) { | ||||||
return; | ||||||
} | ||||||
|
||||||
let form = input.form; | ||||||
input.addEventListener('blur', onBlur); | ||||||
input.addEventListener('invalid', onInvalid); | ||||||
input.addEventListener('change', onChange); | ||||||
form?.addEventListener('reset', onReset); | ||||||
return () => { | ||||||
if (timeoutIdRef.current != null) { | ||||||
clearTimeout(timeoutIdRef.current); | ||||||
timeoutIdRef.current = null; | ||||||
} | ||||||
justBlurredRef.current = false; | ||||||
input!.removeEventListener('blur', onBlur); | ||||||
input!.removeEventListener('invalid', onInvalid); | ||||||
input!.removeEventListener('change', onChange); | ||||||
form?.removeEventListener('reset', onReset); | ||||||
}; | ||||||
}, [ref, onInvalid, onChange, onReset, validationBehavior]); | ||||||
}, [justBlurredRef, onBlur, onChange, onInvalid, onReset, ref, validationBehavior]); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [nitpick] Since ref objects are stable, including justBlurredRef and ref in the dependency array may be unnecessary; consider removing them to simplify the dependencies.
Suggested change
Copilot uses AI. Check for mistakes. Positive FeedbackNegative Feedback |
||||||
} | ||||||
|
||||||
function getValidity(input: ValidatableElement) { | ||||||
function getValidity(input: ValidatableElement): ValidityState { | ||||||
// The native ValidityState object is live, meaning each property is a getter that returns the current state. | ||||||
// We need to create a snapshot of the validity state at the time this function is called to avoid unpredictable React renders. | ||||||
let validity = input.validity; | ||||||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
{ | ||
"time": "Time", | ||
"startTime": "Start time", | ||
"endTime": "End time" | ||
"endTime": "End time", | ||
"valid": "(valid)" | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
{ | ||
"valid": "(valid)" | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider extracting the hardcoded 250ms delay into a named constant to improve clarity and ease future adjustments.
Copilot uses AI. Check for mistakes.