Skip to content

Commit

Permalink
fix(material/select): fix VoiceOver confused by ARIA semantics
Browse files Browse the repository at this point in the history
For Select component, fix issues where VoiceOver was confused by the
ARIA semantics of the combobox. Fix multiple behaviors:

 - Fix VoiceOver focus ring stuck on the combobox while navigating
   options.
 - Fix VoiceOver would sometimes reading option as a TextNode and not
   communicating the selected state and position in set.
 - Fix VoiceOver "flickering" behavior where VoiceOver would display one
   announcement then quickly change to another annoucement.

Also fix the same issues for Autocomplete component.

Implement fix by doing two things.

First, move the aria-owns reference to the overlay from the child of the
combobox to the parent modal of the comobobx. Having an aria-owns
reference inside the combobox element seemed to confuse VoiceOver.

Second, apply `aria-hidden="true"` to the ripple element and pseudo
checkboxes on mat-option. These DOM nodes are only used for visual
purposes, so it is most appropriate to remove them from the
accessibility tree. This seemed to make VoiceOver's behavior more
consistent.

Fix #23202, #19798
  • Loading branch information
zarend committed Mar 30, 2023
1 parent 3aaabbd commit 7033c3c
Show file tree
Hide file tree
Showing 15 changed files with 249 additions and 57 deletions.
5 changes: 2 additions & 3 deletions src/cdk/a11y/live-announcer/live-announcer.ts
Expand Up @@ -190,9 +190,8 @@ export class LiveAnnouncer implements OnDestroy {
* pointing the `aria-owns` of all modals to the live announcer element.
*/
private _exposeAnnouncerToModals(id: string) {
// Note that the selector here is limited to CDK overlays at the moment in order to reduce the
// section of the DOM we need to look through. This should cover all the cases we support, but
// the selector can be expanded if it turns out to be too narrow.
// TODO(http://github.com/angular/components/issues/26853): consider de-duplicating this with
// the `SnakBarContainer` and any other usages.
const modals = this._document.querySelectorAll(
'body > .cdk-overlay-container [aria-modal="true"]',
);
Expand Down
1 change: 1 addition & 0 deletions src/dev-app/autocomplete/BUILD.bazel
Expand Up @@ -14,6 +14,7 @@ ng_module(
"//src/material/button",
"//src/material/card",
"//src/material/checkbox",
"//src/material/dialog",
"//src/material/form-field",
"//src/material/input",
"@npm//@angular/forms",
Expand Down
9 changes: 8 additions & 1 deletion src/dev-app/autocomplete/autocomplete-demo.html
Expand Up @@ -112,11 +112,18 @@
(ngModelChange)="filteredGroupedStates = filterStateGroups(currentGroupedState)">
</mat-form-field>
</mat-card>

<mat-card>
<mat-card-subtitle>Dialog integration</mat-card-subtitle>
<mat-card-content>
<button mat-button (click)="openDialog()">Open modal dialog</button>
</mat-card-content>
</mat-card>
</div>

<mat-autocomplete #groupedAuto="matAutocomplete">
<mat-optgroup *ngFor="let group of filteredGroupedStates"
[label]="'States starting with ' + group.letter">
<mat-option *ngFor="let state of group.states" [value]="state.name">{{ state.name }}</mat-option>
</mat-optgroup>
</mat-autocomplete>
</mat-autocomplete>
64 changes: 63 additions & 1 deletion src/dev-app/autocomplete/autocomplete-demo.ts
Expand Up @@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/

import {Component, ViewChild} from '@angular/core';
import {Component, inject, ViewChild} from '@angular/core';
import {FormControl, NgModel, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {CommonModule} from '@angular/common';
import {MatAutocompleteModule} from '@angular/material/autocomplete';
Expand All @@ -17,6 +17,7 @@ import {MatInputModule} from '@angular/material/input';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
import {ThemePalette} from '@angular/material/core';
import {MatDialog, MatDialogModule, MatDialogRef} from '@angular/material/dialog';

export interface State {
code: string;
Expand All @@ -43,6 +44,7 @@ type DisableStateOption = 'none' | 'first-middle-last' | 'all';
MatButtonModule,
MatCardModule,
MatCheckboxModule,
MatDialogModule,
MatInputModule,
ReactiveFormsModule,
],
Expand Down Expand Up @@ -202,4 +204,64 @@ export class AutocompleteDemo {
}
return false;
}

dialog = inject(MatDialog);
dialogRef: MatDialogRef<any> | null;

openDialog() {
this.dialogRef = this.dialog.open(AutocompleteDemoExampleDialog, {width: '400px'});
}
}

@Component({
selector: 'autocomplete-demo-example-dialog',
template: `
<form (submit)="close()">
<p>Choose a t-shirt size.</p>
<mat-form-field>
<mat-label>T-Shirt Size</mat-label>
<input matInput [matAutocomplete]="tdAuto" [(ngModel)]="currentSize" name="size">
<mat-autocomplete #tdAuto="matAutocomplete">
<mat-option *ngFor="let size of sizes" [value]="size">
{{size}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<button type="submit" mat-button>Close</button>
</form>
`,
styles: [
`
:host {
display: block;
padding: 20px;
}
form {
display: flex;
flex-direction: column;
align-items: flex-start;
}
`,
],
standalone: true,
imports: [
CommonModule,
FormsModule,
MatAutocompleteModule,
MatButtonModule,
MatDialogModule,
MatInputModule,
],
})
export class AutocompleteDemoExampleDialog {
constructor(public dialogRef: MatDialogRef<AutocompleteDemoExampleDialog>) {}

currentSize = '';
sizes = ['S', 'M', 'L'];

close() {
this.dialogRef.close();
}
}
24 changes: 18 additions & 6 deletions src/dev-app/dialog/dialog-demo.html
Expand Up @@ -116,18 +116,30 @@ <h2>Other options</h2>
<p>Last beforeClose result: {{lastBeforeCloseResult}}</p>

<ng-template let-data let-dialogRef="dialogRef">
I'm a template dialog. I've been opened {{numTemplateOpens}} times!

<p>It's Jazz!</p>
<p>Order printer ink refills.</p>

<mat-form-field>
<mat-label>How much?</mat-label>
<mat-label>How many?</mat-label>
<input matInput #howMuch>
</mat-form-field>

<mat-form-field>
<mat-label>What color?</mat-label>
<mat-select #whatColor>
<mat-option></mat-option>
<mat-option value="black">Black</mat-option>
<mat-option value="cyan">Cyan</mat-option>
<mat-option value="magenta">Magenta</mat-option>
<mat-option value="yellow">Yellow</mat-option>
</mat-select>
</mat-form-field>

<p> {{ data.message }} </p>
<button type="button" (click)="dialogRef.close(howMuch.value)" class="demo-dialog-button"
cdkFocusInitial>

I'm a template dialog. I've been opened {{numTemplateOpens}} times!

<button type="button" class="demo-dialog-button" cdkFocusInitial
(click)="dialogRef.close({ quantity: howMuch.value, color: whatColor.value })">
Close dialog
</button>
<button (click)="dialogRef.updateSize('500px', '500px').updatePosition({top: '25px', left: '25px'});"
Expand Down
23 changes: 19 additions & 4 deletions src/dev-app/dialog/dialog-demo.ts
Expand Up @@ -125,23 +125,38 @@ export class DialogDemo {
selector: 'demo-jazz-dialog',
template: `
<div cdkDrag cdkDragRootElement=".cdk-overlay-pane">
<p>It's Jazz!</p>
<p>Order printer ink refills.</p>
<mat-form-field>
<mat-label>How much?</mat-label>
<mat-label>How many?</mat-label>
<input matInput #howMuch>
</mat-form-field>
<mat-form-field>
<mat-label>What color?</mat-label>
<mat-select #whatColor>
<mat-option></mat-option>
<mat-option value="black">Black</mat-option>
<mat-option value="cyan">Cyan</mat-option>
<mat-option value="magenta">Magenta</mat-option>
<mat-option value="yellow">Yellow</mat-option>
</mat-select>
</mat-form-field>
<p cdkDragHandle> {{ data.message }} </p>
<button type="button" (click)="dialogRef.close(howMuch.value)">Close dialog</button>
<button type="button" class="demo-dialog-button"
(click)="dialogRef.close({ quantity: howMuch.value, color: whatColor.value })">
Close dialog
</button>
<button (click)="togglePosition()">Change dimensions</button>
<button (click)="temporarilyHide()">Hide for 2 seconds</button>
</div>
`,
encapsulation: ViewEncapsulation.None,
styles: [`.hidden-dialog { opacity: 0; }`],
standalone: true,
imports: [MatInputModule, DragDropModule],
imports: [DragDropModule, MatInputModule, MatSelectModule],
})
export class JazzDialog {
private _dimensionToggle = false;
Expand Down
58 changes: 57 additions & 1 deletion src/material/autocomplete/autocomplete-trigger.ts
Expand Up @@ -244,6 +244,7 @@ export abstract class _MatAutocompleteTriggerBase
this._componentDestroyed = true;
this._destroyPanel();
this._closeKeyEventStream.complete();
this._clearFromModals();
}

/** Whether or not the autocomplete panel is open. */
Expand Down Expand Up @@ -670,6 +671,8 @@ export abstract class _MatAutocompleteTriggerBase
this.autocomplete._isOpen = this._overlayAttached = true;
this.autocomplete._setColor(this._formField?.color);

this._exposeToModals();

// We need to do an extra `panelOpen` check in here, because the
// autocomplete won't be shown if there are no options.
if (this.panelOpen && wasOpen !== this.panelOpen) {
Expand Down Expand Up @@ -858,6 +861,59 @@ export abstract class _MatAutocompleteTriggerBase
// but the behvior isn't exactly the same and it ends up breaking some internal tests.
overlayRef.outsidePointerEvents().subscribe();
}

private _trackedModals = new Set<Element>();

/**
* Some browsers won't expose the accessibility node of the listbox overlay if there is an
* `aria-modal` and the live element is outside of it. This method works around the issue by
* pointing the `aria-owns` of all modals to the live element.
*
* While aria-owns is not required for the ARIA 1.2 `role="combobox"` interaction pattern,
* it fixes an issue with VoiceOver when the autocomplete appears inside of an `aria-model="true"`
* element (e.g. a dialog). Without this `aria-owns`, the `aria-modal` on a dialog prevents
* VoiceOver from "seeing" the autocomplete's listbox overlay for aria-activedescendant.
* Using `aria-owns` re-parents the autocomplete overlay so that it works again.
* See https://github.com/angular/components/issues/20694
*/
private _exposeToModals() {
// TODO(http://github.com/angular/components/issues/26853): consider de-duplicating this with
// the `LiveAnnouncer` and any other usages.
const id = this.autocomplete.id;
const modals = this._document.querySelectorAll(
'body > .cdk-overlay-container [aria-modal="true"]',
);

for (let i = 0; i < modals.length; i++) {
const modal = modals[i];
const ariaOwns = modal.getAttribute('aria-owns');
this._trackedModals.add(modal);

if (!ariaOwns) {
modal.setAttribute('aria-owns', id);
} else if (ariaOwns.indexOf(id) === -1) {
modal.setAttribute('aria-owns', ariaOwns + ' ' + id);
}
}
}

/** Clears the references to the listbox overlay element from any modals it was added to. */
private _clearFromModals() {
this._trackedModals.forEach(modal => {
const ariaOwns = modal.getAttribute('aria-owns');

if (ariaOwns) {
const newValue = ariaOwns.replace(`${this.autocomplete.id}-panel`, '').trim();

if (newValue.length > 0) {
modal.setAttribute('aria-owns', newValue);
} else {
modal.removeAttribute('aria-owns');
}
}
});
this._trackedModals.clear();
}
}

@Directive({
Expand All @@ -869,7 +925,7 @@ export abstract class _MatAutocompleteTriggerBase
'[attr.aria-autocomplete]': 'autocompleteDisabled ? null : "list"',
'[attr.aria-activedescendant]': '(panelOpen && activeOption) ? activeOption.id : null',
'[attr.aria-expanded]': 'autocompleteDisabled ? null : panelOpen.toString()',
'[attr.aria-owns]': '(autocompleteDisabled || !panelOpen) ? null : autocomplete?.id',
'[attr.aria-controls]': '(autocompleteDisabled || !panelOpen) ? null : autocomplete?.id',
'[attr.aria-haspopup]': 'autocompleteDisabled ? null : "listbox"',
// Note: we use `focusin`, as opposed to `focus`, in order to open the panel
// a little earlier. This avoids issues where IE delays the focusing of the input.
Expand Down
12 changes: 6 additions & 6 deletions src/material/autocomplete/autocomplete.spec.ts
Expand Up @@ -1863,26 +1863,26 @@ describe('MDC-based MatAutocomplete', () => {
.toBe('false');
}));

it('should set aria-owns based on the attached autocomplete', () => {
it('should set aria-controls based on the attached autocomplete', () => {
fixture.componentInstance.trigger.openPanel();
fixture.detectChanges();

const panel = fixture.debugElement.query(
By.css('.mat-mdc-autocomplete-panel'),
)!.nativeElement;

expect(input.getAttribute('aria-owns'))
.withContext('Expected aria-owns to match attached autocomplete.')
expect(input.getAttribute('aria-controls'))
.withContext('Expected aria-controls to match attached autocomplete.')
.toBe(panel.getAttribute('id'));
});

it('should not set aria-owns while the autocomplete is closed', () => {
expect(input.getAttribute('aria-owns')).toBeFalsy();
it('should not set aria-controls while the autocomplete is closed', () => {
expect(input.getAttribute('aria-controls')).toBeFalsy();

fixture.componentInstance.trigger.openPanel();
fixture.detectChanges();

expect(input.getAttribute('aria-owns')).toBeTruthy();
expect(input.getAttribute('aria-controls')).toBeTruthy();
});

it('should restore focus to the input when clicking to select a value', fakeAsync(() => {
Expand Down
7 changes: 6 additions & 1 deletion src/material/autocomplete/testing/autocomplete-harness.ts
Expand Up @@ -129,7 +129,7 @@ export abstract class _MatAutocompleteHarnessBase<
}

/** Gets the selector that can be used to find the autocomplete trigger's panel. */
private async _getPanelSelector(): Promise<string> {
protected async _getPanelSelector(): Promise<string> {
return `#${await (await this.host()).getAttribute('aria-owns')}`;
}
}
Expand Down Expand Up @@ -168,4 +168,9 @@ export class MatAutocompleteHarness extends _MatAutocompleteHarnessBase<
return (await harness.isDisabled()) === disabled;
});
}

/** Gets the selector that can be used to find the autocomplete trigger's panel. */
protected override async _getPanelSelector(): Promise<string> {
return `#${await (await this.host()).getAttribute('aria-controls')}`;
}
}
13 changes: 6 additions & 7 deletions src/material/core/option/option.html
@@ -1,19 +1,18 @@
<mat-pseudo-checkbox *ngIf="multiple" class="mat-mdc-option-pseudo-checkbox"
[state]="selected ? 'checked' : 'unchecked'" [disabled]="disabled"></mat-pseudo-checkbox>
<mat-pseudo-checkbox *ngIf="multiple" class="mat-mdc-option-pseudo-checkbox" [disabled]="disabled"
[state]="selected ? 'checked' : 'unchecked'" [attr.aria-hidden]="'true'"></mat-pseudo-checkbox>

<ng-content select="mat-icon"></ng-content>

<span class="mdc-list-item__primary-text" #text><ng-content></ng-content></span>

<!-- Render checkmark at the end for single-selection. -->
<mat-pseudo-checkbox *ngIf="!multiple && selected && !hideSingleSelectionIndicator"
class="mat-mdc-option-pseudo-checkbox" state="checked" [disabled]="disabled"
appearance="minimal"></mat-pseudo-checkbox>
class="mat-mdc-option-pseudo-checkbox" [disabled]="disabled" state="checked"
[attr.aria-hidden]="'true'" appearance="minimal"></mat-pseudo-checkbox>

<!-- See a11y notes inside optgroup.ts for context behind this element. -->
<span class="cdk-visually-hidden" *ngIf="group && group._inert">({{ group.label }})</span>

<div class="mat-mdc-option-ripple mat-mdc-focus-indicator" mat-ripple
[matRippleTrigger]="_getHostElement()"
[matRippleDisabled]="disabled || disableRipple">
<div class="mat-mdc-option-ripple mat-mdc-focus-indicator" [attr.aria-hidden]="'true'" mat-ripple
[matRippleTrigger]="_getHostElement()" [matRippleDisabled]="disabled || disableRipple">
</div>
10 changes: 0 additions & 10 deletions src/material/select/select.html
@@ -1,14 +1,4 @@
<!--
Note that the select trigger element specifies `aria-owns` pointing to the listbox overlay.
While aria-owns is not required for the ARIA 1.2 `role="combobox"` interaction pattern,
it fixes an issue with VoiceOver when the select appears inside of an `aria-model="true"`
element (e.g. a dialog). Without this `aria-owns`, the `aria-modal` on a dialog prevents
VoiceOver from "seeing" the select's listbox overlay for aria-activedescendant.
Using `aria-owns` re-parents the select overlay so that it works again.
See https://github.com/angular/components/issues/20694
-->
<div cdk-overlay-origin
[attr.aria-owns]="panelOpen ? id + '-panel' : null"
class="mat-mdc-select-trigger"
(click)="toggle()"
#fallbackOverlayOrigin="cdkOverlayOrigin"
Expand Down

0 comments on commit 7033c3c

Please sign in to comment.