mirror of
https://github.com/ionic-team/ionic-framework.git
synced 2025-11-02 02:35:20 +08:00
fix(select): improve screen reader announcement timing for validation errors (#30723)
Issue number: internal --------- <!-- Please do not submit updates to dependencies unless it fixes an issue. --> <!-- Please try to limit your pull request to one type (bugfix, feature, etc). Submit multiple pull requests if needed. --> ## What is the current behavior? <!-- Please describe the current behavior that you are modifying. --> Currently, when an error text is shown, it may not announce itself to voice assistants. This is because the way error text currently works is by always existing in the DOM, but being hidden when there is no error. When the error state changes, the error text is shown, but as far as the voice assistant can tell it's always been there and nothing has changed. ## What is the new behavior? <!-- Please describe the behavior or changes that are being added by this PR. --> - Updated aria attributes - Added observer with an observer We had to do this with a mutation observer and state because it's important in some frameworks, like Angular, that state changes to cause a re-render. This, combined with some minor aria changes, makes it so that when a field is declared invalid, it immediately announces the invalid state instead of waiting for the user to go back to the invalid field. ## Does this introduce a breaking change? - [ ] Yes - [x] No <!-- If this introduces a breaking change: 1. Describe the impact and migration path for existing applications below. 2. Update the BREAKING.md file with the breaking change. 3. Add "BREAKING CHANGE: [...]" to the commit description when merging. See https://github.com/ionic-team/ionic-framework/blob/main/docs/CONTRIBUTING.md#footer for more information. --> ## Other information <!-- Any other information that is important to this PR such as screenshots of how the component looks before and after the change. --> [Preview](https://ionic-framework-git-fw-6797-ionic1.vercel.app/src/components/select/test/validation/)
This commit is contained in:
@ -14,7 +14,7 @@ import {
|
||||
h,
|
||||
} from '@stencil/core';
|
||||
import type { NotchController } from '@utils/forms';
|
||||
import { createNotchController } from '@utils/forms';
|
||||
import { createNotchController, checkInvalidState } from '@utils/forms';
|
||||
import type { Attributes } from '@utils/helpers';
|
||||
import { inheritAriaAttributes, debounceEvent, inheritAttributes, componentOnReady } from '@utils/helpers';
|
||||
import { createSlotMutationController } from '@utils/slot-mutation-controller';
|
||||
@ -403,16 +403,6 @@ export class Input implements ComponentInterface {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the input is in an invalid state based on Ionic validation classes
|
||||
*/
|
||||
private checkInvalidState(): boolean {
|
||||
const hasIonTouched = this.el.classList.contains('ion-touched');
|
||||
const hasIonInvalid = this.el.classList.contains('ion-invalid');
|
||||
|
||||
return hasIonTouched && hasIonInvalid;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
const { el } = this;
|
||||
|
||||
@ -426,7 +416,7 @@ export class Input implements ComponentInterface {
|
||||
// Watch for class changes to update validation state
|
||||
if (Build.isBrowser && typeof MutationObserver !== 'undefined') {
|
||||
this.validationObserver = new MutationObserver(() => {
|
||||
const newIsInvalid = this.checkInvalidState();
|
||||
const newIsInvalid = checkInvalidState(el);
|
||||
if (this.isInvalid !== newIsInvalid) {
|
||||
this.isInvalid = newIsInvalid;
|
||||
// Force a re-render to update aria-describedby immediately
|
||||
@ -441,7 +431,7 @@ export class Input implements ComponentInterface {
|
||||
}
|
||||
|
||||
// Always set initial state
|
||||
this.isInvalid = this.checkInvalidState();
|
||||
this.isInvalid = checkInvalidState(el);
|
||||
|
||||
this.debounceChanged();
|
||||
if (Build.isBrowser) {
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import type { ComponentInterface, EventEmitter } from '@stencil/core';
|
||||
import { Component, Element, Event, Host, Method, Prop, State, Watch, h, forceUpdate } from '@stencil/core';
|
||||
import { Build, Component, Element, Event, Host, Method, Prop, State, Watch, h, forceUpdate } from '@stencil/core';
|
||||
import type { NotchController } from '@utils/forms';
|
||||
import { compareOptions, createNotchController, isOptionSelected } from '@utils/forms';
|
||||
import { compareOptions, createNotchController, isOptionSelected, checkInvalidState } from '@utils/forms';
|
||||
import { focusVisibleElement, renderHiddenInput, inheritAttributes } from '@utils/helpers';
|
||||
import type { Attributes } from '@utils/helpers';
|
||||
import { printIonWarning } from '@utils/logging';
|
||||
@ -64,6 +64,7 @@ export class Select implements ComponentInterface {
|
||||
private inheritedAttributes: Attributes = {};
|
||||
private nativeWrapperEl: HTMLElement | undefined;
|
||||
private notchSpacerEl: HTMLElement | undefined;
|
||||
private validationObserver?: MutationObserver;
|
||||
|
||||
private notchController?: NotchController;
|
||||
|
||||
@ -81,6 +82,13 @@ export class Select implements ComponentInterface {
|
||||
*/
|
||||
@State() hasFocus = false;
|
||||
|
||||
/**
|
||||
* Track validation state for proper aria-live announcements.
|
||||
*/
|
||||
@State() isInvalid = false;
|
||||
|
||||
@State() private hintTextID?: string;
|
||||
|
||||
/**
|
||||
* The text to display on the cancel button.
|
||||
*/
|
||||
@ -298,10 +306,51 @@ export class Select implements ComponentInterface {
|
||||
*/
|
||||
forceUpdate(this);
|
||||
});
|
||||
|
||||
// Watch for class changes to update validation state.
|
||||
if (Build.isBrowser && typeof MutationObserver !== 'undefined') {
|
||||
this.validationObserver = new MutationObserver(() => {
|
||||
const newIsInvalid = checkInvalidState(this.el);
|
||||
if (this.isInvalid !== newIsInvalid) {
|
||||
this.isInvalid = newIsInvalid;
|
||||
/**
|
||||
* Screen readers tend to announce changes
|
||||
* to `aria-describedby` when the attribute
|
||||
* is changed during a blur event for a
|
||||
* native form control.
|
||||
* However, the announcement can be spotty
|
||||
* when using a non-native form control
|
||||
* and `forceUpdate()`.
|
||||
* This is due to `forceUpdate()` internally
|
||||
* rescheduling the DOM update to a lower
|
||||
* priority queue regardless if it's called
|
||||
* inside a Promise or not, thus causing
|
||||
* the screen reader to potentially miss the
|
||||
* change.
|
||||
* By using a State variable inside a Promise,
|
||||
* it guarantees a re-render immediately at
|
||||
* a higher priority.
|
||||
*/
|
||||
Promise.resolve().then(() => {
|
||||
this.hintTextID = this.getHintTextID();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
this.validationObserver.observe(el, {
|
||||
attributes: true,
|
||||
attributeFilter: ['class'],
|
||||
});
|
||||
}
|
||||
|
||||
// Always set initial state
|
||||
this.isInvalid = checkInvalidState(this.el);
|
||||
}
|
||||
|
||||
componentWillLoad() {
|
||||
this.inheritedAttributes = inheritAttributes(this.el, ['aria-label']);
|
||||
|
||||
this.hintTextID = this.getHintTextID();
|
||||
}
|
||||
|
||||
componentDidLoad() {
|
||||
@ -328,6 +377,12 @@ export class Select implements ComponentInterface {
|
||||
this.notchController.destroy();
|
||||
this.notchController = undefined;
|
||||
}
|
||||
|
||||
// Clean up validation observer to prevent memory leaks.
|
||||
if (this.validationObserver) {
|
||||
this.validationObserver.disconnect();
|
||||
this.validationObserver = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1056,8 +1111,8 @@ export class Select implements ComponentInterface {
|
||||
aria-label={this.ariaLabel}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={`${isExpanded}`}
|
||||
aria-describedby={this.getHintTextID()}
|
||||
aria-invalid={this.getHintTextID() === this.errorTextId}
|
||||
aria-describedby={this.hintTextID}
|
||||
aria-invalid={this.isInvalid ? 'true' : undefined}
|
||||
aria-required={`${required}`}
|
||||
onFocus={this.onFocus}
|
||||
onBlur={this.onBlur}
|
||||
@ -1067,9 +1122,9 @@ export class Select implements ComponentInterface {
|
||||
}
|
||||
|
||||
private getHintTextID(): string | undefined {
|
||||
const { el, helperText, errorText, helperTextId, errorTextId } = this;
|
||||
const { helperText, errorText, helperTextId, errorTextId, isInvalid } = this;
|
||||
|
||||
if (el.classList.contains('ion-touched') && el.classList.contains('ion-invalid') && errorText) {
|
||||
if (isInvalid && errorText) {
|
||||
return errorTextId;
|
||||
}
|
||||
|
||||
@ -1084,14 +1139,14 @@ export class Select implements ComponentInterface {
|
||||
* Renders the helper text or error text values
|
||||
*/
|
||||
private renderHintText() {
|
||||
const { helperText, errorText, helperTextId, errorTextId } = this;
|
||||
const { helperText, errorText, helperTextId, errorTextId, isInvalid } = this;
|
||||
|
||||
return [
|
||||
<div id={helperTextId} class="helper-text" part="supporting-text helper-text">
|
||||
{helperText}
|
||||
<div id={helperTextId} class="helper-text" part="supporting-text helper-text" aria-live="polite">
|
||||
{!isInvalid ? helperText : null}
|
||||
</div>,
|
||||
<div id={errorTextId} class="error-text" part="supporting-text error-text">
|
||||
{errorText}
|
||||
<div id={errorTextId} class="error-text" part="supporting-text error-text" role="alert">
|
||||
{isInvalid ? errorText : null}
|
||||
</div>,
|
||||
];
|
||||
}
|
||||
|
||||
200
core/src/components/select/test/validation/index.html
Normal file
200
core/src/components/select/test/validation/index.html
Normal file
@ -0,0 +1,200 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" dir="ltr">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Select - Validation</title>
|
||||
<meta
|
||||
name="viewport"
|
||||
content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
|
||||
/>
|
||||
<link href="../../../../../css/ionic.bundle.css" rel="stylesheet" />
|
||||
<link href="../../../../../scripts/testing/styles.css" rel="stylesheet" />
|
||||
<script src="../../../../../scripts/testing/scripts.js"></script>
|
||||
<script nomodule src="../../../../../dist/ionic/ionic.js"></script>
|
||||
<script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script>
|
||||
<style>
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
||||
grid-row-gap: 30px;
|
||||
grid-column-gap: 30px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 12px;
|
||||
font-weight: normal;
|
||||
|
||||
color: var(--ion-color-step-600);
|
||||
|
||||
margin-top: 10px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.validation-info {
|
||||
margin: 20px;
|
||||
padding: 10px;
|
||||
background: var(--ion-color-light);
|
||||
border-radius: 4px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<ion-app>
|
||||
<ion-header>
|
||||
<ion-toolbar>
|
||||
<ion-title>Select - Validation Test</ion-title>
|
||||
</ion-toolbar>
|
||||
</ion-header>
|
||||
|
||||
<ion-content class="ion-padding">
|
||||
<div class="validation-info">
|
||||
<h2>Screen Reader Testing Instructions:</h2>
|
||||
<ol>
|
||||
<li>Enable your screen reader (VoiceOver, NVDA, JAWS, etc.)</li>
|
||||
<li>Tab through the form fields</li>
|
||||
<li>When you tab away from an empty required field, the error should be announced immediately</li>
|
||||
<li>The error text should be announced BEFORE the next field is announced</li>
|
||||
<li>Test in Chrome, Safari, and Firefox to verify consistent behavior</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<div>
|
||||
<h2>Required Field</h2>
|
||||
<ion-select
|
||||
id="fruits-select"
|
||||
label="Fruits"
|
||||
placeholder="Select one"
|
||||
interface="alert"
|
||||
helper-text="You must select an option to continue"
|
||||
error-text="This field is required"
|
||||
required
|
||||
>
|
||||
<ion-select-option value="apples">Apples</ion-select-option>
|
||||
<ion-select-option value="oranges">Oranges</ion-select-option>
|
||||
<ion-select-option value="pears">Pears</ion-select-option>
|
||||
</ion-select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2>Optional Field (No Validation)</h2>
|
||||
<ion-select
|
||||
id="optional-select"
|
||||
label="Colors"
|
||||
placeholder="Select one"
|
||||
interface="alert"
|
||||
helper-text="You can skip this field"
|
||||
>
|
||||
<ion-select-option value="red">Red</ion-select-option>
|
||||
<ion-select-option value="blue">Blue</ion-select-option>
|
||||
<ion-select-option value="green">Green</ion-select-option>
|
||||
</ion-select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="ion-padding">
|
||||
<ion-button id="submit-btn" expand="block" disabled>Submit Form</ion-button>
|
||||
<ion-button id="reset-btn" expand="block" fill="outline">Reset Form</ion-button>
|
||||
</div>
|
||||
</ion-content>
|
||||
</ion-app>
|
||||
|
||||
<script>
|
||||
// Simple validation logic
|
||||
const selects = document.querySelectorAll('ion-select');
|
||||
const submitBtn = document.getElementById('submit-btn');
|
||||
const resetBtn = document.getElementById('reset-btn');
|
||||
|
||||
// Track which fields have been touched
|
||||
const touchedFields = new Set();
|
||||
|
||||
// Validation functions
|
||||
const validators = {
|
||||
'fruits-select': (value) => {
|
||||
return value !== '' && value !== undefined;
|
||||
},
|
||||
'optional-select': () => true, // Always valid
|
||||
};
|
||||
|
||||
function validateField(select) {
|
||||
const selectId = select.id;
|
||||
const value = select.value;
|
||||
const isValid = validators[selectId] ? validators[selectId](value) : true;
|
||||
|
||||
// Only show validation state if field has been touched
|
||||
if (touchedFields.has(selectId)) {
|
||||
if (isValid) {
|
||||
select.classList.remove('ion-invalid');
|
||||
select.classList.add('ion-valid');
|
||||
} else {
|
||||
select.classList.remove('ion-valid');
|
||||
select.classList.add('ion-invalid');
|
||||
}
|
||||
select.classList.add('ion-touched');
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
|
||||
function validateForm() {
|
||||
let allValid = true;
|
||||
selects.forEach((select) => {
|
||||
if (select.id !== 'optional-select') {
|
||||
const isValid = validateField(select);
|
||||
if (!isValid) {
|
||||
allValid = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
submitBtn.disabled = !allValid;
|
||||
return allValid;
|
||||
}
|
||||
|
||||
// Add event listeners
|
||||
selects.forEach((select) => {
|
||||
// Mark as touched on blur
|
||||
select.addEventListener('ionBlur', (e) => {
|
||||
console.log('Blur event on:', select.id);
|
||||
touchedFields.add(select.id);
|
||||
validateField(select);
|
||||
validateForm();
|
||||
|
||||
const isInvalid = select.classList.contains('ion-invalid');
|
||||
if (isInvalid) {
|
||||
console.log('Field marked invalid:', select.label, select.errorText);
|
||||
}
|
||||
});
|
||||
|
||||
// Validate on change
|
||||
select.addEventListener('ionChange', (e) => {
|
||||
console.log('Change event on:', select.id);
|
||||
if (touchedFields.has(select.id)) {
|
||||
validateField(select);
|
||||
validateForm();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Reset button
|
||||
resetBtn.addEventListener('click', () => {
|
||||
selects.forEach((select) => {
|
||||
select.value = '';
|
||||
select.classList.remove('ion-valid', 'ion-invalid', 'ion-touched');
|
||||
});
|
||||
touchedFields.clear();
|
||||
submitBtn.disabled = true;
|
||||
});
|
||||
|
||||
// Submit button
|
||||
submitBtn.addEventListener('click', () => {
|
||||
if (validateForm()) {
|
||||
alert('Form submitted successfully!');
|
||||
}
|
||||
});
|
||||
|
||||
// Initial setup
|
||||
validateForm();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@ -15,7 +15,7 @@ import {
|
||||
writeTask,
|
||||
} from '@stencil/core';
|
||||
import type { NotchController } from '@utils/forms';
|
||||
import { createNotchController } from '@utils/forms';
|
||||
import { createNotchController, checkInvalidState } from '@utils/forms';
|
||||
import type { Attributes } from '@utils/helpers';
|
||||
import { inheritAriaAttributes, debounceEvent, inheritAttributes, componentOnReady } from '@utils/helpers';
|
||||
import { createSlotMutationController } from '@utils/slot-mutation-controller';
|
||||
@ -335,16 +335,6 @@ export class Textarea implements ComponentInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the textarea is in an invalid state based on Ionic validation classes
|
||||
*/
|
||||
private checkValidationState(): boolean {
|
||||
const hasIonTouched = this.el.classList.contains('ion-touched');
|
||||
const hasIonInvalid = this.el.classList.contains('ion-invalid');
|
||||
|
||||
return hasIonTouched && hasIonInvalid;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
const { el } = this;
|
||||
this.slotMutationController = createSlotMutationController(el, ['label', 'start', 'end'], () => forceUpdate(this));
|
||||
@ -357,7 +347,7 @@ export class Textarea implements ComponentInterface {
|
||||
// Watch for class changes to update validation state
|
||||
if (Build.isBrowser && typeof MutationObserver !== 'undefined') {
|
||||
this.validationObserver = new MutationObserver(() => {
|
||||
const newIsInvalid = this.checkValidationState();
|
||||
const newIsInvalid = checkInvalidState(this.el);
|
||||
if (this.isInvalid !== newIsInvalid) {
|
||||
this.isInvalid = newIsInvalid;
|
||||
// Force a re-render to update aria-describedby immediately
|
||||
@ -372,7 +362,7 @@ export class Textarea implements ComponentInterface {
|
||||
}
|
||||
|
||||
// Always set initial state
|
||||
this.isInvalid = this.checkValidationState();
|
||||
this.isInvalid = checkInvalidState(this.el);
|
||||
|
||||
this.debounceChanged();
|
||||
if (Build.isBrowser) {
|
||||
|
||||
@ -1,2 +1,3 @@
|
||||
export * from './notch-controller';
|
||||
export * from './compare-with-utils';
|
||||
export * from './validity';
|
||||
|
||||
15
core/src/utils/forms/validity.ts
Normal file
15
core/src/utils/forms/validity.ts
Normal file
@ -0,0 +1,15 @@
|
||||
type FormElement = HTMLIonInputElement | HTMLIonTextareaElement | HTMLIonSelectElement;
|
||||
|
||||
/**
|
||||
* Checks if the form element is in an invalid state based on
|
||||
* Ionic validation classes.
|
||||
*
|
||||
* @param el The form element to check.
|
||||
* @returns `true` if the element is invalid, `false` otherwise.
|
||||
*/
|
||||
export const checkInvalidState = (el: FormElement): boolean => {
|
||||
const hasIonTouched = el.classList.contains('ion-touched');
|
||||
const hasIonInvalid = el.classList.contains('ion-invalid');
|
||||
|
||||
return hasIonTouched && hasIonInvalid;
|
||||
};
|
||||
Reference in New Issue
Block a user