Skip to content

Commit 8ab5e84

Browse files
committed
fix(material/datepicker): calendar aria-descriptions start/end date
For date ranges, add aria-descriptions to the cell of the current start date and also for end date. Popuplate aria descriptions with the expected value of the ARIA accessible name of the `matStartDate` and `matEndDate` inputs. Introduces `_computeAriaAccessibleName` function to implement ARIA acc-name-1.2 specificiation. Fixes #23442 and #23445
1 parent 31a754c commit 8ab5e84

15 files changed

+501
-19
lines changed
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
import {_computeAriaAccessibleName} from './aria-accessible-name';
2+
3+
describe('_computeAriaAccessibleName', () => {
4+
let rootElement: HTMLSpanElement;
5+
6+
beforeEach(() => {
7+
rootElement = document.createElement('span');
8+
document.body.appendChild(rootElement);
9+
});
10+
11+
afterEach(() => {
12+
rootElement.remove();
13+
});
14+
15+
it('uses aria-labelledby over aria-label', () => {
16+
rootElement.innerHTML = `
17+
<label id='test-label'>Aria Labelledby</label>
18+
<input id='test-el' aria-labelledby='test-label' aria-label='Aria Label'/>
19+
`;
20+
21+
const input = rootElement.querySelector('#test-el')!;
22+
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Aria Labelledby');
23+
});
24+
25+
it('uses aria-label over for/id', () => {
26+
rootElement.innerHTML = `
27+
<label for='test-el'>For</label>
28+
<input id='test-el' aria-label='Aria Label'/>
29+
`;
30+
31+
const input = rootElement.querySelector('#test-el')!;
32+
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Aria Label');
33+
});
34+
35+
it('uses a label with for/id over a title attribute', () => {
36+
rootElement.innerHTML = `
37+
<label for='test-el'>For</label>
38+
<input id='test-el' title='Title'/>
39+
`;
40+
41+
const input = rootElement.querySelector('#test-el')!;
42+
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('For');
43+
});
44+
45+
it('returns title when argument has a specified title', () => {
46+
rootElement.innerHTML = `<input id="test-el" title='Title'/>`;
47+
48+
const input = rootElement.querySelector('#test-el')!;
49+
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Title');
50+
});
51+
52+
// match browser behavior of giving placeholder attribute preference over title attribute
53+
it('uses placeholder over title', () => {
54+
rootElement.innerHTML = `<input id="test-el" title='Title' placeholder='Placeholder'/>`;
55+
56+
const input = rootElement.querySelector('#test-el')!;
57+
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Placeholder');
58+
});
59+
60+
it('uses aria-label over title and placeholder', () => {
61+
rootElement.innerHTML = `<input id="test-el" title='Title' placeholder='Placeholder'
62+
aria-label="Aria Label"/>`;
63+
64+
const input = rootElement.querySelector('#test-el')!;
65+
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Aria Label');
66+
});
67+
68+
it('includes both textnode and element children of label with for/id', () => {
69+
rootElement.innerHTML = `
70+
<label for="test-el">
71+
Hello
72+
<span>
73+
Wo
74+
<span><span>r</span></span>
75+
<span> ld </span>
76+
</span>
77+
!
78+
</label>
79+
<input id='test-el'/>
80+
`;
81+
82+
const input = rootElement.querySelector('#test-el')!;
83+
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Hello Wo r ld !');
84+
});
85+
86+
it('return computed name of hidden label which has for/id', () => {
87+
rootElement.innerHTML = `
88+
<label for="test-el" aria-hidden="true" style="display: none;">For</label>
89+
<input id='test-el'/>
90+
`;
91+
92+
const input = rootElement.querySelector('#test-el')!;
93+
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('For');
94+
});
95+
96+
it('returns computed names of existing elements when 2 of 3 targets of aria-labelledby exist', () => {
97+
rootElement.innerHTML = `
98+
<label id="label-1-of-2" aria-hidden="true" style="display: none;">Label1</label>
99+
<label id="label-2-of-2" aria-hidden="true" style="display: none;">Label2</label>
100+
<input id="test-el" aria-labelledby="label-1-of-2 label-2-of-2 non-existant-label"/>
101+
`;
102+
103+
const input = rootElement.querySelector('#test-el')!;
104+
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Label1 Label2');
105+
});
106+
107+
it('returns repeated label when there are duplicate ids in aria-labelledby', () => {
108+
rootElement.innerHTML = `
109+
<label id="label-1-of-1" aria-hidden="true" style="display: none;">Label1</label>
110+
<input id="test-el" aria-labelledby="label-1-of-1 label-1-of-1"/>
111+
`;
112+
113+
const input = rootElement.querySelector('#test-el')!;
114+
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Label1 Label1');
115+
});
116+
117+
it('returns empty string when passed `<input id="test-el"/>`', () => {
118+
rootElement.innerHTML = `<input id="test-el"/>`;
119+
120+
const input = rootElement.querySelector('#test-el')!;
121+
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('');
122+
});
123+
124+
it('ignores the aria-labelledby of an aria-labelledby', () => {
125+
rootElement.innerHTML = `
126+
<label id="label" aria-labelledby="transitive-label">Label</label>
127+
<label id="transitive-label" aria-labelled-by="transitive-label">Transitive Label</div>
128+
<input id="test-el" aria-labelledby="label"/>
129+
`;
130+
131+
const input = rootElement.querySelector('#test-el')!;
132+
const label = rootElement.querySelector('#label')!;
133+
expect(_computeAriaAccessibleName(label as any)).toBe('Transitive Label');
134+
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Label');
135+
});
136+
137+
it('ignores the aria-labelledby on a label with for/id', () => {
138+
rootElement.innerHTML = `
139+
<label for="transitive2-label" aria-labelledby="transitive2-div"></label>
140+
<div id="transitive2-div">Div</div>
141+
<input id="test-el" aria-labelled-by="transitive2-label"/>
142+
`;
143+
144+
const input = rootElement.querySelector('#test-el')!;
145+
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('');
146+
});
147+
148+
it('returns empty string when argument input is aria-labelledby itself', () => {
149+
rootElement.innerHTML = `
150+
<input id="test-el" aria-labelled-by="test-el"/>
151+
`;
152+
153+
const input = rootElement.querySelector('#test-el')!;
154+
const computedName = _computeAriaAccessibleName(input as HTMLInputElement);
155+
expect(typeof computedName)
156+
.withContext('should return value of type string')
157+
.toBe('string');
158+
});
159+
});
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
// This file contains the `_computeAriaAccessibleName` function, which computes what the *expected*
10+
// ARIA accessible name would be for a given element. Implements a subset of ARIA specification
11+
// [Accessible Name and Description Computation 1.2](https://www.w3.org/TR/accname-1.2/).
12+
//
13+
// Specification accname-1.2 can be summarized by returning the result of the first method
14+
// available.
15+
//
16+
// 1. `aria-labelledby` attribute
17+
// ```
18+
// <!-- example using aria-labelledby-->
19+
// <label id='label-id'>Start Date</label>
20+
// <input aria-labelledby='label-id'/>
21+
// ```
22+
// 2. `aria-label` attribute (e.g. `<input aria-label="Departure"/>`)
23+
// 3. Label with `for`/`id`
24+
// ```
25+
// <!-- example using for/id -->
26+
// <label for="current-node">Label</label>
27+
// <input id="current-node"/>
28+
// ```
29+
// 4. `placeholder` attribute (e.g. `<input placeholder="06/03/1990"/>`)
30+
// 5. `title` attribute (e.g. `<input title="Check-In"/>`)
31+
// 6. text content
32+
// ```
33+
// <!-- example using text content -->
34+
// <label for="current-node"><span>Departure</span> Date</label>
35+
// <input id="current-node"/>
36+
// ```
37+
38+
/**
39+
* Computes the *expected* ARIA accessible name for argument element based on [accname-1.2
40+
* specification](https://www.w3.org/TR/accname-1.2/). Implements a subset of accname-1.2,
41+
* and should only be used for the Datepicker's specific use case.
42+
*
43+
* Intended use:
44+
* This is not a general use implementation. Only implements the parts of accname-1.2 that are
45+
* required for the Datepicker's specific use case. This function is not intended for any other
46+
* use.
47+
*
48+
* Limitations:
49+
* - Only covers the needs of `matStartDate` and `matEndDate`. Does not support other use cases.
50+
* - See NOTES's in implementation for specific details on what parts of the accname-1.2
51+
* specification are not implemented.
52+
*
53+
* @param element {HTMLInputElement} native &lt;input/> element of `matStartDate` or `matEndDate` component. Corresponds to the 'Root Element' from accname-1.2
54+
*
55+
* @return expected ARIA accessible name of argument &lt;input/>
56+
*/
57+
export function _computeAriaAccessibleName(element: HTMLInputElement): string {
58+
return _computeAriaAccessibleNameInternal(element, true);
59+
}
60+
61+
/**
62+
* Calculate the expected ARIA accessible name for given DOM Node. Given DOM Node may be either the
63+
* "Root node" passed to `_computeAriaAccessibleName` or "Current node" as result of recursion.
64+
*
65+
* @return the accessible name of argument DOM Node
66+
*
67+
* @param currentNode node to determine accessible name of
68+
* @param isDirectlyReferenced true if `currentNode` is the root node to calculate ARIA accessible
69+
* name of. False if it is a result of recursion.
70+
*/
71+
function _computeAriaAccessibleNameInternal(
72+
currentNode: Node,
73+
isDirectlyReferenced: boolean,
74+
): string {
75+
// NOTE: this differs from accname-1.2 specification.
76+
// - Does not implement Step 1. of accname-1.2: '''If `currentNode`'s role prohibits naming,
77+
// return the empty string ("")'''.
78+
// - Does not implement Step 2.A. of accname-1.2: '''if current node is hidden and not directly
79+
// referenced by aria-labelledby... return the empty string.'''
80+
81+
// acc-name-1.2 Step 2.B.: aria-labelledby
82+
if (currentNode instanceof Element && isDirectlyReferenced) {
83+
const labelledbyIds: string[] =
84+
currentNode.getAttribute?.('aria-labelledby')?.split(/\s+/g) || [];
85+
const validIdRefs: HTMLElement[] = labelledbyIds.reduce((validIds, id) => {
86+
const elem = document.getElementById(id);
87+
if (elem) {
88+
validIds.push(elem);
89+
}
90+
return validIds;
91+
}, [] as HTMLElement[]);
92+
93+
if (validIdRefs.length) {
94+
return validIdRefs
95+
.map(idRef => {
96+
return _computeAriaAccessibleNameInternal(idRef, false);
97+
})
98+
.join(' ');
99+
}
100+
}
101+
102+
// acc-name-1.2 Step 2.C.: aria-label
103+
if (currentNode instanceof Element) {
104+
const ariaLabel = currentNode.getAttribute('aria-label')?.trim();
105+
106+
if (ariaLabel) {
107+
return ariaLabel;
108+
}
109+
}
110+
111+
// acc-name-1.2 Step 2.D. attribute or element that defines a text alternative
112+
//
113+
// NOTE: this differs from accname-1.2 specification.
114+
// Only implements acc-name-1.2 for `<label>` and `<input/>` element. Does not implement all
115+
// other elements that have an attribute or element that defines a text alternative.
116+
if (currentNode instanceof HTMLInputElement) {
117+
// use label with a `for` attribute referencing the current node
118+
const labels = document.querySelectorAll(`[for="${currentNode.id}"]`);
119+
if (labels.length) {
120+
return Array.from(labels)
121+
.map(x => _computeAriaAccessibleNameInternal(x, false))
122+
.join(' ');
123+
}
124+
125+
// use placeholder if available
126+
const placeholder = currentNode.getAttribute('placeholder')?.trim();
127+
if (placeholder) {
128+
return placeholder;
129+
}
130+
131+
// use title if available
132+
const title = currentNode.getAttribute('title')?.trim();
133+
if (title) {
134+
return title;
135+
}
136+
}
137+
138+
// NOTE: this differs from accname-1.2 specification.
139+
// - does not implement acc-name-1.2 Step 2.E.: '''if the current node is a control embedded
140+
// within the label... then include the embedded control as part of the text alternative in
141+
// the following manner...'''. Step 2E applies to embedded controls such as textbox, listbox,
142+
// range, etc.
143+
// - does not implement acc-name-1.2 step 2.F.: check that '''role allows name from content''',
144+
// which applies to `currentNode` and its children.
145+
// - does not implement acc-name-1.2 Step 2.F.ii.: '''Check for CSS generated textual content'''
146+
// (e.g. :before and :after).
147+
// - does not implement acc-name-1.2 Step 2.I.: '''if the current node has a Tooltip attribute,
148+
// return its value'''
149+
150+
// Return text content with whitespace collapsed into a single space character. Accomplish
151+
// acc-name-1.2 steps 2F, 2G, and 2H.
152+
return (currentNode.textContent || '').replace(/\s+/g, ' ').trim();
153+
}

src/material/datepicker/calendar-body.html

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
[attr.aria-disabled]="!item.enabled || null"
6464
[attr.aria-pressed]="_isSelected(item.compareValue)"
6565
[attr.aria-current]="todayValue === item.compareValue ? 'date' : null"
66+
[attr.aria-describedby]="_getDescribedby(item.compareValue)"
6667
(click)="_cellClicked(item, $event)"
6768
(focus)="_emitActiveDateChange(item, $event)">
6869
<div class="mat-calendar-body-cell-content mat-focus-indicator"
@@ -75,3 +76,10 @@
7576
</button>
7677
</td>
7778
</tr>
79+
80+
<label [id]="_startDateLabelId" class="cdk-visually-hidden" aria-hidden="true">
81+
{{startDateAccessibleName}}
82+
</label>
83+
<label [id]="_endDateLabelId" class="cdk-visually-hidden" aria-hidden="true">
84+
{{endDateAccessibleName}}
85+
</label>

src/material/datepicker/calendar-body.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ export interface MatCalendarUserEvent<D> {
5353
event: Event;
5454
}
5555

56+
let calendarBodyId = 1;
57+
5658
/**
5759
* An internal component used to display calendar data in a table.
5860
* @docs-private
@@ -132,6 +134,12 @@ export class MatCalendarBody implements OnChanges, OnDestroy, AfterViewChecked {
132134
/** End of the preview range. */
133135
@Input() previewEnd: number | null = null;
134136

137+
/** ARIA Accessible name of the `<input matStartDate/>` */
138+
@Input() startDateAccessibleName: string | null;
139+
140+
/** ARIA Accessible name of the `<input matEndDate/>` */
141+
@Input() endDateAccessibleName: string | null;
142+
135143
/** Emits when a new value is selected. */
136144
@Output() readonly selectedValueChange = new EventEmitter<MatCalendarUserEvent<number>>();
137145

@@ -356,6 +364,26 @@ export class MatCalendarBody implements OnChanges, OnDestroy, AfterViewChecked {
356364
return isInRange(value, this.previewStart, this.previewEnd, this.isRange);
357365
}
358366

367+
/** Gets ids of aria descriptions for the start and end of a date range. */
368+
_getDescribedby(value: number): string | null {
369+
if (!this.isRange) {
370+
return null;
371+
}
372+
const ids: string[] = [];
373+
374+
if (this.startValue === value) {
375+
ids.push(this._startDateLabelId);
376+
}
377+
if (this.endValue === value) {
378+
ids.push(this._endDateLabelId);
379+
}
380+
381+
if (ids.length) {
382+
return ids.join(' ');
383+
}
384+
return null;
385+
}
386+
359387
/**
360388
* Event handler for when the user enters an element
361389
* inside the calendar body (e.g. by hovering in or focus).
@@ -413,6 +441,12 @@ export class MatCalendarBody implements OnChanges, OnDestroy, AfterViewChecked {
413441

414442
return null;
415443
}
444+
445+
private _id = `mat-calendar-body-${calendarBodyId++}`;
446+
447+
_startDateLabelId = `${this._id}-start-date`;
448+
449+
_endDateLabelId = `${this._id}-end-date`;
416450
}
417451

418452
/** Checks whether a node is a table cell element. */

0 commit comments

Comments
 (0)