Skip to content

Commit ffe5d0d

Browse files
authored
fix: link form-item label to field via aria-labelledby (#3088)
1 parent 7956973 commit ffe5d0d

7 files changed

Lines changed: 486 additions & 51 deletions

File tree

‎packages/field-base/src/utils.d.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* @license
3+
* Copyright (c) 2021 Vaadin Ltd.
4+
* This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
5+
*/
6+
7+
/**
8+
* Adds a value to an attribute containing space-delimited values.
9+
*/
10+
export declare function addValueToAttribute(element: HTMLElement, attr: string, value: string): void;
11+
12+
/**
13+
* Removes a value from an attribute containing space-delimited values.
14+
* If the value is the last one, the whole attribute is removed.
15+
*/
16+
export declare function removeValueFromAttribute(element: HTMLElement, attr: string, value: string): void;

‎packages/field-base/src/utils.js‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* @license
3+
* Copyright (c) 2021 Vaadin Ltd.
4+
* This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
5+
*/
6+
7+
/**
8+
* @param {string} value
9+
* @return {Set<string>}
10+
*/
11+
function deserializeAttributeValue(value) {
12+
if (!value) {
13+
return new Set();
14+
}
15+
16+
return new Set(value.split(' '));
17+
}
18+
19+
/**
20+
* @param {Set<string>} values
21+
* @return {string}
22+
*/
23+
function serializeAttributeValue(values) {
24+
return [...values].join(' ');
25+
}
26+
27+
/**
28+
* Adds a value to an attribute containing space-delimited values.
29+
*
30+
* @param {HTMLElement} element
31+
* @param {string} attr
32+
* @param {string} value
33+
*/
34+
export function addValueToAttribute(element, attr, value) {
35+
const values = deserializeAttributeValue(element.getAttribute(attr));
36+
values.add(value);
37+
element.setAttribute(attr, serializeAttributeValue(values));
38+
}
39+
40+
/**
41+
* Removes a value from an attribute containing space-delimited values.
42+
* If the value is the last one, the whole attribute is removed.
43+
*
44+
* @param {HTMLElement} element
45+
* @param {string} attr
46+
* @param {string} value
47+
*/
48+
export function removeValueFromAttribute(element, attr, value) {
49+
const values = deserializeAttributeValue(element.getAttribute(attr));
50+
values.delete(value);
51+
if (values.size === 0) {
52+
element.removeAttribute(attr);
53+
return;
54+
}
55+
element.setAttribute(attr, serializeAttributeValue(values));
56+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { expect } from '@esm-bundle/chai';
2+
import { addValueToAttribute, removeValueFromAttribute } from '../src/utils.js';
3+
4+
describe('utils', () => {
5+
describe('addValueToAttribute', () => {
6+
let element;
7+
8+
beforeEach(() => {
9+
element = document.createElement('div');
10+
});
11+
12+
it('should add a value to an attribute', () => {
13+
addValueToAttribute(element, 'aria-labelledby', 'label-id');
14+
expect(element.getAttribute('aria-labelledby')).to.equal('label-id');
15+
16+
addValueToAttribute(element, 'aria-labelledby', 'error-id');
17+
expect(element.getAttribute('aria-labelledby')).to.equal('label-id error-id');
18+
});
19+
20+
it('should not duplicate values in the attribute', () => {
21+
addValueToAttribute(element, 'aria-labelledby', 'label-id');
22+
addValueToAttribute(element, 'aria-labelledby', 'label-id');
23+
expect(element.getAttribute('aria-labelledby')).to.equal('label-id');
24+
});
25+
});
26+
27+
describe('removeValueFromAttribute', () => {
28+
let element;
29+
30+
beforeEach(() => {
31+
element = document.createElement('div');
32+
element.setAttribute('aria-labelledby', 'label-id error-id');
33+
});
34+
35+
it('should remove a value from an attribute', () => {
36+
removeValueFromAttribute(element, 'aria-labelledby', 'error-id');
37+
expect(element.getAttribute('aria-labelledby')).to.equal('label-id');
38+
39+
removeValueFromAttribute(element, 'aria-labelledby', 'label-id');
40+
expect(element.hasAttribute('aria-labelledby')).to.be.false;
41+
});
42+
});
43+
});

‎packages/form-layout/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
},
4242
"devDependencies": {
4343
"@esm-bundle/chai": "^4.3.4",
44+
"@vaadin/custom-field": "23.0.0-alpha1",
4445
"@vaadin/testing-helpers": "^0.3.2",
4546
"@vaadin/text-field": "23.0.0-alpha1",
4647
"sinon": "^9.2.1"

‎packages/form-layout/src/vaadin-form-item.d.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,16 @@ import { ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mix
9797
*
9898
* See [Styling Components](https://vaadin.com/docs/latest/ds/customization/styling-components) documentation.
9999
*/
100-
declare class FormItem extends ThemableMixin(HTMLElement) {}
100+
declare class FormItem extends ThemableMixin(HTMLElement) {
101+
/**
102+
* Returns a target element to add ARIA attributes to for a field.
103+
*
104+
* - For Vaadin field components, the method returns an element
105+
* obtained through the `ariaTarget` property defined in `FieldMixin`.
106+
* - In other cases, the method returns the field element itself.
107+
*/
108+
protected _getFieldAriaTarget(field: HTMLElement): HTMLElement;
109+
}
101110

102111
declare global {
103112
interface HTMLElementTagNameMap {

‎packages/form-layout/src/vaadin-form-item.js‎

Lines changed: 135 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
55
*/
66
import { html, PolymerElement } from '@polymer/polymer/polymer-element.js';
7+
import { addValueToAttribute, removeValueFromAttribute } from '@vaadin/field-base/src/utils.js';
78
import { ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';
89

910
/**
@@ -145,8 +146,8 @@ class FormItem extends ThemableMixin(PolymerElement) {
145146
min-width: 0;
146147
}
147148
</style>
148-
<div id="label" part="label" on-click="_onLabelClick">
149-
<slot name="label" id="labelSlot"></slot>
149+
<div id="label" part="label" on-click="__onLabelClick">
150+
<slot name="label" id="labelSlot" on-slotchange="__onLabelSlotChange"></slot>
150151
<span part="required-indicator" aria-hidden="true"></span>
151152
</div>
152153
<div id="spacing"></div>
@@ -163,15 +164,80 @@ class FormItem extends ThemableMixin(PolymerElement) {
163164
constructor() {
164165
super();
165166
this.__updateInvalidState = this.__updateInvalidState.bind(this);
166-
this.__contentFieldObserver = new MutationObserver(() => this.__updateRequiredState(this.__contentField.required));
167+
168+
/**
169+
* An observer for a field node to reflect its `required` and `invalid` attributes to the component.
170+
*
171+
* @type {MutationObserver}
172+
* @private
173+
*/
174+
this.__fieldNodeObserver = new MutationObserver(() => this.__updateRequiredState(this.__fieldNode.required));
175+
176+
/**
177+
* The first label node in the label slot.
178+
*
179+
* @type {HTMLElement | null}
180+
* @private
181+
*/
182+
this.__labelNode = null;
183+
184+
/**
185+
* The first field node in the content slot.
186+
*
187+
* An element is considered a field when it has the `checkValidity` or `validate` method.
188+
*
189+
* @type {HTMLElement | null}
190+
* @private
191+
*/
192+
this.__fieldNode = null;
193+
194+
// Ensure every instance has unique ID
195+
const uniqueId = (FormItem._uniqueLabelId = 1 + FormItem._uniqueLabelId || 0);
196+
this.__labelId = `label-${this.localName}-${uniqueId}`;
197+
}
198+
199+
/**
200+
* Returns a target element to add ARIA attributes to for a field.
201+
*
202+
* - For Vaadin field components, the method returns an element
203+
* obtained through the `ariaTarget` property defined in `FieldMixin`.
204+
* - In other cases, the method returns the field element itself.
205+
*
206+
* @param {HTMLElement} field
207+
* @protected
208+
*/
209+
_getFieldAriaTarget(field) {
210+
return field.ariaTarget || field;
211+
}
212+
213+
/**
214+
* Links the label to a field by adding the label id to
215+
* the `aria-labelledby` attribute of the field's ARIA target element.
216+
*
217+
* @param {HTMLElement} field
218+
* @private
219+
*/
220+
__linkLabelToField(field) {
221+
addValueToAttribute(this._getFieldAriaTarget(field), 'aria-labelledby', this.__labelId);
222+
}
223+
224+
/**
225+
* Unlinks the label from a field by removing the label id from
226+
* the `aria-labelledby` attribute of the field's ARIA target element.
227+
*
228+
* @param {HTMLElement} field
229+
* @private
230+
*/
231+
__unlinkLabelFromField(field) {
232+
removeValueFromAttribute(this._getFieldAriaTarget(field), 'aria-labelledby', this.__labelId);
167233
}
168234

169235
/** @private */
170-
_onLabelClick() {
171-
const firstContentElementChild = this.$.contentSlot.assignedElements()[0];
172-
if (firstContentElementChild) {
173-
firstContentElementChild.focus();
174-
firstContentElementChild.click();
236+
__onLabelClick() {
237+
const fieldNode = this.__fieldNode;
238+
if (fieldNode) {
239+
fieldNode.focus();
240+
fieldNode.click();
175241
}
176242
}
177243

@@ -180,44 +246,87 @@ class FormItem extends ThemableMixin(PolymerElement) {
180246
return field.validate || field.checkValidity;
181247
}
182248

183-
/** @private */
249+
/**
250+
* A `slotchange` event handler for the label slot.
251+
*
252+
* - Ensures the label id is only assigned to the first label node.
253+
* - Ensures the label node is linked to the first field node via the `aria-labelledby` attribute
254+
* if both nodes are provided, and unlinked otherwise.
255+
*
256+
* @private
257+
*/
258+
__onLabelSlotChange() {
259+
if (this.__labelNode) {
260+
this.__labelNode.id = '';
261+
this.__labelNode = null;
262+
263+
if (this.__fieldNode) {
264+
this.__unlinkLabelFromField(this.__fieldNode);
265+
}
266+
}
267+
268+
const newLabelNode = this.$.labelSlot.assignedElements()[0];
269+
if (newLabelNode) {
270+
this.__labelNode = newLabelNode;
271+
this.__labelNode.id = this.__labelId;
272+
273+
if (this.__fieldNode) {
274+
this.__linkLabelToField(this.__fieldNode);
275+
}
276+
}
277+
}
278+
279+
/**
280+
* A `slotchange` event handler for the content slot.
281+
*
282+
* - Ensures the label node is only linked to the first field node via the `aria-labelledby` attribute.
283+
* - Sets up an observer for the `required` attribute changes on the first field
284+
* to reflect the attribute on the component. Ensures the observer is disconnected from the field
285+
* as soon as it is removed or replaced by another one.
286+
*
287+
* @private
288+
*/
184289
__onContentSlotChange() {
185-
if (this.__contentField) {
290+
if (this.__fieldNode) {
186291
// Discard the old field
292+
this.__unlinkLabelFromField(this.__fieldNode);
187293
this.__updateRequiredState(false);
188-
this.__contentFieldObserver.disconnect();
189-
delete this.__contentField;
294+
this.__fieldNodeObserver.disconnect();
295+
this.__fieldNode = null;
190296
}
191297

192-
const contentFields = this.$.contentSlot.assignedElements().filter((node) => !!this.__getValidateFunction(node));
193-
if (contentFields.length === 1) {
194-
// There's only one child field
195-
this.__contentField = contentFields[0];
196-
this.__updateRequiredState(this.__contentField.required);
197-
this.__contentFieldObserver.observe(this.__contentField, { attributes: true, attributeFilter: ['required'] });
298+
const newFieldNode = this.$.contentSlot.assignedElements().find((field) => {
299+
return !!this.__getValidateFunction(field);
300+
});
301+
if (newFieldNode) {
302+
this.__fieldNode = newFieldNode;
303+
this.__updateRequiredState(this.__fieldNode.required);
304+
this.__fieldNodeObserver.observe(this.__fieldNode, { attributes: true, attributeFilter: ['required'] });
305+
306+
if (this.__labelNode) {
307+
this.__linkLabelToField(this.__fieldNode);
308+
}
198309
}
199310
}
200311

201312
/** @private */
202313
__updateRequiredState(required) {
203314
if (required) {
204315
this.setAttribute('required', '');
205-
this.__contentField.addEventListener('blur', this.__updateInvalidState);
206-
this.__contentField.addEventListener('change', this.__updateInvalidState);
316+
this.__fieldNode.addEventListener('blur', this.__updateInvalidState);
317+
this.__fieldNode.addEventListener('change', this.__updateInvalidState);
207318
} else {
208319
this.removeAttribute('invalid');
209320
this.removeAttribute('required');
210-
this.__contentField.removeEventListener('blur', this.__updateInvalidState);
211-
this.__contentField.removeEventListener('change', this.__updateInvalidState);
321+
this.__fieldNode.removeEventListener('blur', this.__updateInvalidState);
322+
this.__fieldNode.removeEventListener('change', this.__updateInvalidState);
212323
}
213324
}
214325

215326
/** @private */
216327
__updateInvalidState() {
217-
this.toggleAttribute(
218-
'invalid',
219-
this.__getValidateFunction(this.__contentField).call(this.__contentField) === false
220-
);
328+
const isValid = this.__getValidateFunction(this.__fieldNode).call(this.__fieldNode);
329+
this.toggleAttribute('invalid', isValid === false);
221330
}
222331
}
223332

0 commit comments

Comments
 (0)