Skip to content

Commit 3cf834a

Browse files
authored
feat: Fix ARIA roles and setup for fields (experimental) (#9384)
## The basics - [x] I [validated my changes](https://developers.google.com/blockly/guides/contribute/core#making_and_verifying_a_change) ## The details ### Resolves Fixes #8206 Fixes #8210 Fixes #8213 Fixes #8255 Fixes #8211 Fixes #8212 Fixes #8254 Fixes part of #9301 Fixes part of #9304 ### Proposed Changes This PR completes the remaining ARIA roles and properties needed for all core fields. Specifically: - #8206: A better name needed to be used for the checkbox value, plus there was an ARIA property missing for actually representing the checkbox state. The latter needed to be updated upon toggling the checkbox, as well. These changes bring checkbox fields in compliance with the ARIA checkbox pattern documented here: https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/. - #8210: This one required a lot of changes in order to adapt to the ARIA combobox pattern documented here: https://www.w3.org/WAI/ARIA/apg/patterns/combobox/. Specifically: - Menus needed to have a unique ID that's also exposed in order to link the combobox element to its menu when open. - ARIA's `activedescendant` proved very useful in ensuring that the current dropdown selection is correctly read when the combobox has focus but its menu isn't opened. - The default properties available for options (label and value) aren't very good for readout, so a custom ARIA property was added for much clearer option readouts. This is only demonstrated for the math arithmetic block for now. - The text element is normally hidden for ARIA but it's useful in conjunction with `activedescendant` to represent the current value selection. - Images have been handled here as well (partly as part of #8255) by leveraging their alt text for readouts. This actually seems to work quite well both for current value and selection. - #8213: Much of the improvements here come from the combobox (`FieldDropdown`) improvements explained above. However one additional bit was done to provide an explicit 'Variable <name>' readout for the purpose of clarity. This demonstrates some contextualization of the value of the field which may be a generally useful pattern to copy in other field contexts. - #8255: Image fields have been refined since they were redundantly specifying 'image' when an `image` ARIA role is already being used. Now only the alt text is supplied along with the role context. Note that images need special handling since they can sometimes be navigable (such as when they have click handlers). - #8211: Text input fields have had their labeling improved like all other fields, and the field's value is now exposed via its `text` element since this will show up as a `StaticText` node in the accessibility tree and automatically be read as part of the field's value. - #8212: This gets the same benefits as the previous point since those improvements were included for both text and number input. However, existing `valuemin` and `valuemax` ARIA properties have been removed. It seems these are really only useful when introducing a slider mechanism (see https://www.w3.org/WAI/ARIA/apg/patterns/slider/) and from testing seems to not really be utilized for the basic text input that `FieldNumber` currently uses. It may be the case that this is a better pattern to use in the future, but it's more likely that other custom fields could benefit from more specific patterns like slider rather than `FieldNumber` being changed in that way. - #8254 and part of #9304: Field labels have been completely removed from the accessibility node tree since they can never be navigated to (as #8254 explains all labels will be included as part of the block's ARIA label itself for readout parity with navigation options). Note that it doesn't cover external fields (such as those supplied in blockly-samples), nor does it fully set up the infrastructure work for those. Ultimately that work needs to happen as part of #9301. Beyond the role work above, this PR also introduces some fundamental work for #9301. Specifically: - It demonstrates how block definitions could be used to introduce accessibility label customizations (in this case for the options of the arithmetic operator block's drop-down field, plus the block itself). - It sets up some central label computation for all fields, though more thought is needed on whether this is sufficient for custom fields outside of core Blockly and on how to properly contextualize labels for field values. Core Blockly's fields are fairly simple for representing values which is why that aspect of #9301 didn't need to be solved in this PR. Note that the field labeling here is being used to improve all of the fields above, but also it tries to aggressively fall back to the _next best_ label to be used (though it's possible to run out of options which is why fields still need contextually-specific fallbacks). ### Reason for Changes Generally the initial approach for implementing labels is leveraging as specific ARIA roles as exist to directly represent the element. This PR is completing that work for all of core Blockly's built-in fields, and laying some of the groundwork for generalizing this support for custom fields. Having specific roles does potentially introduce inconsistencies across screen readers (though should improve consistency across sites for a single screen reader), and expectations for behaviors (like shortcuts) that may need to be ignored or only partially supported (#9313 is discussing this). ### Test Coverage Only manual testing has been completed since this is experimental work. Video demonstrating most of the changes: [Screen recording 2025-10-01 4.05.35 PM.webm](https://github.com/user-attachments/assets/c7961caa-eae0-4585-8fd9-87d7cbe65988) ### Documentation N/A -- Experimental work. ### Additional Information This has only been tested on ChromeVox.
1 parent 76c7345 commit 3cf834a

19 files changed

+193
-74
lines changed

blocks/math.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,13 @@ export const blocks = createBlockDefinitionsFromJsonArray([
5454
{
5555
'type': 'field_dropdown',
5656
'name': 'OP',
57+
'ariaName': 'Arithmetic operation',
5758
'options': [
58-
['%{BKY_MATH_ADDITION_SYMBOL}', 'ADD'],
59-
['%{BKY_MATH_SUBTRACTION_SYMBOL}', 'MINUS'],
60-
['%{BKY_MATH_MULTIPLICATION_SYMBOL}', 'MULTIPLY'],
61-
['%{BKY_MATH_DIVISION_SYMBOL}', 'DIVIDE'],
62-
['%{BKY_MATH_POWER_SYMBOL}', 'POWER'],
59+
['%{BKY_MATH_ADDITION_SYMBOL}', 'ADD', 'Plus'],
60+
['%{BKY_MATH_SUBTRACTION_SYMBOL}', 'MINUS', 'Minus'],
61+
['%{BKY_MATH_MULTIPLICATION_SYMBOL}', 'MULTIPLY', 'Times'],
62+
['%{BKY_MATH_DIVISION_SYMBOL}', 'DIVIDE', 'Divided by'],
63+
['%{BKY_MATH_POWER_SYMBOL}', 'POWER', 'To the power of'],
6364
],
6465
},
6566
{

core/css.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -509,7 +509,7 @@ input[type=number] {
509509
outline: none;
510510
}
511511
512-
#blocklyAriaAnnounce {
512+
.hiddenForAria {
513513
position: absolute;
514514
left: -9999px;
515515
width: 1px;

core/field.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,8 @@ export abstract class Field<T = any>
199199
/** The unique ID of this field. */
200200
private id_: string | null = null;
201201

202+
private config: FieldConfig | null = null;
203+
202204
/**
203205
* @param value The initial value of the field.
204206
* Also accepts Field.SKIP_SETUP if you wish to skip setup (only used by
@@ -251,6 +253,7 @@ export abstract class Field<T = any>
251253
if (config.tooltip) {
252254
this.setTooltip(parsing.replaceMessageReferences(config.tooltip));
253255
}
256+
this.config = config;
254257
}
255258

256259
/**
@@ -272,6 +275,17 @@ export abstract class Field<T = any>
272275
this.id_ = `${block.id}_field_${idGenerator.getNextUniqueId()}`;
273276
}
274277

278+
getAriaName(): string | null {
279+
return (
280+
this.config?.ariaName ??
281+
this.config?.name ??
282+
this.config?.type ??
283+
this.getSourceBlock()?.type ??
284+
this.name ??
285+
null
286+
);
287+
}
288+
275289
/**
276290
* Get the renderer constant provider.
277291
*
@@ -1418,7 +1432,10 @@ export abstract class Field<T = any>
14181432
* Extra configuration options for the base field.
14191433
*/
14201434
export interface FieldConfig {
1435+
type: string;
1436+
name?: string;
14211437
tooltip?: string;
1438+
ariaName?: string;
14221439
}
14231440

14241441
/**

core/field_checkbox.ts

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -113,13 +113,14 @@ export class FieldCheckbox extends Field<CheckboxBool> {
113113
dom.addClass(this.fieldGroup_!, 'blocklyCheckboxField');
114114
textElement.style.display = this.value_ ? 'block' : 'none';
115115

116+
this.recomputeAria();
117+
}
118+
119+
private recomputeAria() {
116120
const element = this.getFocusableElement();
117121
aria.setRole(element, aria.Role.CHECKBOX);
118-
aria.setState(
119-
element,
120-
aria.State.LABEL,
121-
this.name ? `Checkbox ${this.name}` : 'Checkbox',
122-
);
122+
aria.setState(element, aria.State.LABEL, this.getAriaName() ?? 'Checkbox');
123+
aria.setState(element, aria.State.CHECKED, !!this.value_);
123124
}
124125

125126
override render_() {
@@ -147,6 +148,7 @@ export class FieldCheckbox extends Field<CheckboxBool> {
147148
/** Toggle the state of the checkbox on click. */
148149
protected override showEditor_() {
149150
this.setValue(!this.value_);
151+
this.recomputeAria();
150152
}
151153

152154
/**

core/field_dropdown.ts

Lines changed: 88 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {MenuItem} from './menuitem.js';
2828
import * as aria from './utils/aria.js';
2929
import {Coordinate} from './utils/coordinate.js';
3030
import * as dom from './utils/dom.js';
31+
import * as idGenerator from './utils/idgenerator.js';
3132
import * as parsing from './utils/parsing.js';
3233
import {Size} from './utils/size.js';
3334
import * as utilsString from './utils/string.js';
@@ -198,12 +199,28 @@ export class FieldDropdown extends Field<string> {
198199
dom.addClass(this.fieldGroup_, 'blocklyDropdownField');
199200
}
200201

202+
this.recomputeAria();
203+
}
204+
205+
private recomputeAria() {
206+
if (!this.fieldGroup_) return; // There's no element to set currently.
201207
const element = this.getFocusableElement();
202-
aria.setRole(element, aria.Role.LISTBOX);
208+
aria.setRole(element, aria.Role.COMBOBOX);
209+
aria.setState(element, aria.State.HASPOPUP, aria.Role.LISTBOX);
210+
aria.setState(element, aria.State.EXPANDED, !!this.menu_);
211+
if (this.menu_) {
212+
aria.setState(element, aria.State.CONTROLS, this.menu_.id);
213+
} else {
214+
aria.clearState(element, aria.State.CONTROLS);
215+
}
216+
aria.setState(element, aria.State.LABEL, this.getAriaName() ?? 'Dropdown');
217+
218+
// Ensure the selected item has its correct label presented since it may be
219+
// different than the actual text presented to the user.
203220
aria.setState(
204-
element,
221+
this.getTextElement(),
205222
aria.State.LABEL,
206-
this.name ? `Item ${this.name}` : 'Item',
223+
this.computeLabelForOption(this.selectedOption),
207224
);
208225
}
209226

@@ -335,7 +352,11 @@ export class FieldDropdown extends Field<string> {
335352
}
336353
return label;
337354
})();
338-
const menuItem = new MenuItem(content, value);
355+
const menuItem = new MenuItem(
356+
content,
357+
value,
358+
this.computeLabelForOption(option),
359+
);
339360
menuItem.setRole(aria.Role.OPTION);
340361
menuItem.setRightToLeft(block.RTL);
341362
menuItem.setCheckable(true);
@@ -346,6 +367,24 @@ export class FieldDropdown extends Field<string> {
346367
}
347368
menuItem.onAction(this.handleMenuActionEvent, this);
348369
}
370+
371+
this.recomputeAria();
372+
}
373+
374+
private computeLabelForOption(option: MenuOption): string {
375+
if (option === FieldDropdown.SEPARATOR) {
376+
return ''; // Separators don't need labels.
377+
} else if (!Array.isArray(option)) {
378+
return ''; // Certain dynamic options aren't iterable. TODO: Figure this out. It breaks when opening certain test toolbox categories in the advanced playground.
379+
}
380+
const [label, value, optionalAriaLabel] = option;
381+
const altText = isImageProperties(label) ? label.alt : null;
382+
return (
383+
altText ??
384+
optionalAriaLabel ??
385+
this.computeHumanReadableText(option) ??
386+
String(value)
387+
);
349388
}
350389

351390
/**
@@ -358,6 +397,7 @@ export class FieldDropdown extends Field<string> {
358397
this.menu_ = null;
359398
this.selectedMenuItem = null;
360399
this.applyColour();
400+
this.recomputeAria();
361401
}
362402

363403
/**
@@ -380,6 +420,11 @@ export class FieldDropdown extends Field<string> {
380420
this.setValue(menuItem.getValue());
381421
}
382422

423+
override setValue(newValue: AnyDuringMigration, fireChangeEvent = true) {
424+
super.setValue(newValue, fireChangeEvent);
425+
this.recomputeAria();
426+
}
427+
383428
/**
384429
* @returns True if the option list is generated by a function.
385430
* Otherwise false.
@@ -532,14 +577,11 @@ export class FieldDropdown extends Field<string> {
532577
if (!block) {
533578
throw new UnattachedFieldError();
534579
}
535-
this.imageElement!.style.display = '';
536-
this.imageElement!.setAttributeNS(
537-
dom.XLINK_NS,
538-
'xlink:href',
539-
imageJson.src,
540-
);
541-
this.imageElement!.setAttribute('height', String(imageJson.height));
542-
this.imageElement!.setAttribute('width', String(imageJson.width));
580+
const imageElement = this.imageElement!;
581+
imageElement.style.display = '';
582+
imageElement.setAttributeNS(dom.XLINK_NS, 'xlink:href', imageJson.src);
583+
imageElement.setAttribute('height', String(imageJson.height));
584+
imageElement.setAttribute('width', String(imageJson.width));
543585

544586
const imageHeight = Number(imageJson.height);
545587
const imageWidth = Number(imageJson.width);
@@ -567,15 +609,24 @@ export class FieldDropdown extends Field<string> {
567609
let arrowX = 0;
568610
if (block.RTL) {
569611
const imageX = xPadding + arrowWidth;
570-
this.imageElement!.setAttribute('x', `${imageX}`);
612+
imageElement.setAttribute('x', `${imageX}`);
571613
} else {
572614
arrowX = imageWidth + arrowWidth;
573615
this.getTextElement().setAttribute('text-anchor', 'end');
574-
this.imageElement!.setAttribute('x', `${xPadding}`);
616+
imageElement.setAttribute('x', `${xPadding}`);
575617
}
576-
this.imageElement!.setAttribute('y', String(height / 2 - imageHeight / 2));
618+
imageElement.setAttribute('y', String(height / 2 - imageHeight / 2));
577619

578620
this.positionTextElement_(arrowX + xPadding, imageWidth + arrowWidth);
621+
622+
if (imageElement.id === '') {
623+
imageElement.id = idGenerator.getNextUniqueId();
624+
const element = this.getFocusableElement();
625+
aria.setState(element, aria.State.ACTIVEDESCENDANT, imageElement.id);
626+
}
627+
628+
aria.setRole(imageElement, aria.Role.IMAGE);
629+
aria.setState(imageElement, aria.State.LABEL, imageJson.alt);
579630
}
580631

581632
/** Renders the selected option, which must be text. */
@@ -585,6 +636,14 @@ export class FieldDropdown extends Field<string> {
585636
const textElement = this.getTextElement();
586637
dom.addClass(textElement, 'blocklyDropdownText');
587638
textElement.setAttribute('text-anchor', 'start');
639+
// The field's text should be visible to readers since it will be read out
640+
// as static text as part of the combobox (per the ARIA combobox pattern).
641+
if (textElement.id === '') {
642+
textElement.id = idGenerator.getNextUniqueId();
643+
const element = this.getFocusableElement();
644+
aria.setState(element, aria.State.ACTIVEDESCENDANT, textElement.id);
645+
}
646+
aria.setState(textElement, aria.State.HIDDEN, false);
588647

589648
// Height and width include the border rect.
590649
const hasBorder = !!this.borderRect_;
@@ -654,7 +713,11 @@ export class FieldDropdown extends Field<string> {
654713
if (!this.selectedOption) {
655714
return null;
656715
}
657-
const option = this.selectedOption[0];
716+
return this.computeHumanReadableText(this.selectedOption);
717+
}
718+
719+
private computeHumanReadableText(menuOption: MenuOption): string | null {
720+
const option = menuOption[0];
658721
if (isImageProperties(option)) {
659722
return option.alt;
660723
} else if (
@@ -689,7 +752,7 @@ export class FieldDropdown extends Field<string> {
689752
throw new Error(
690753
'options are required for the dropdown field. The ' +
691754
'options property must be assigned an array of ' +
692-
'[humanReadableValue, languageNeutralValue] tuples.',
755+
'[humanReadableValue, languageNeutralValue, opt_ariaLabel] tuples.',
693756
);
694757
}
695758
// `this` might be a subclass of FieldDropdown if that class doesn't
@@ -713,9 +776,9 @@ export class FieldDropdown extends Field<string> {
713776
return option;
714777
}
715778

716-
const [label, value] = option;
779+
const [label, value, opt_ariaLabel] = option;
717780
if (typeof label === 'string') {
718-
return [parsing.replaceMessageReferences(label), value];
781+
return [parsing.replaceMessageReferences(label), value, opt_ariaLabel];
719782
}
720783

721784
hasNonTextContent = true;
@@ -724,14 +787,14 @@ export class FieldDropdown extends Field<string> {
724787
const imageLabel = isImageProperties(label)
725788
? {...label, alt: parsing.replaceMessageReferences(label.alt)}
726789
: label;
727-
return [imageLabel, value];
790+
return [imageLabel, value, opt_ariaLabel];
728791
});
729792

730793
if (hasNonTextContent || options.length < 2) {
731794
return {options: trimmedOptions};
732795
}
733796

734-
const stringOptions = trimmedOptions as [string, string][];
797+
const stringOptions = trimmedOptions as [string, string, string?][];
735798
const stringLabels = stringOptions.map(([label]) => label);
736799

737800
const shortest = utilsString.shortestStringLength(stringLabels);
@@ -770,13 +833,14 @@ export class FieldDropdown extends Field<string> {
770833
* @returns A new array with all of the option text trimmed.
771834
*/
772835
private applyTrim(
773-
options: [string, string][],
836+
options: [string, string, string?][],
774837
prefixLength: number,
775838
suffixLength: number,
776839
): MenuOption[] {
777-
return options.map(([text, value]) => [
840+
return options.map(([text, value, opt_ariaLabel]) => [
778841
text.substring(prefixLength, text.length - suffixLength),
779842
value,
843+
opt_ariaLabel,
780844
]);
781845
}
782846

@@ -868,7 +932,7 @@ export interface ImageProperties {
868932
* the language-neutral value.
869933
*/
870934
export type MenuOption =
871-
| [string | ImageProperties | HTMLElement, string]
935+
| [string | ImageProperties | HTMLElement, string, string?]
872936
| 'separator';
873937

874938
/**

core/field_image.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,16 +155,18 @@ export class FieldImage extends Field<string> {
155155
dom.addClass(this.fieldGroup_, 'blocklyImageField');
156156
}
157157

158+
const element = this.getFocusableElement();
158159
if (this.clickHandler) {
159160
this.imageElement.style.cursor = 'pointer';
161+
aria.setRole(element, aria.Role.BUTTON);
162+
} else {
163+
aria.setRole(element, aria.Role.IMAGE);
160164
}
161165

162-
const element = this.getFocusableElement();
163-
aria.setRole(element, aria.Role.IMAGE);
164166
aria.setState(
165167
element,
166168
aria.State.LABEL,
167-
this.name ? `Image ${this.name}` : 'Image',
169+
this.altText ?? this.getAriaName(),
168170
);
169171
}
170172

core/field_input.ts

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,8 @@ export abstract class FieldInput<T extends InputTypes> extends Field<
167167
const block = this.getSourceBlock();
168168
if (!block) throw new UnattachedFieldError();
169169
super.initView();
170+
if (!this.textElement_)
171+
throw new Error('Initialization failed for FieldInput');
170172

171173
if (this.isFullBlockField()) {
172174
this.clickTarget_ = (this.sourceBlock_ as BlockSvg).getSvgRoot();
@@ -176,13 +178,13 @@ export abstract class FieldInput<T extends InputTypes> extends Field<
176178
dom.addClass(this.fieldGroup_, 'blocklyInputField');
177179
}
178180

181+
// Showing the text-based value with the input's textbox ensures that the
182+
// input's value is correctly read out by screen readers with its role.
183+
aria.setState(this.textElement_, aria.State.HIDDEN, false);
184+
179185
const element = this.getFocusableElement();
180186
aria.setRole(element, aria.Role.TEXTBOX);
181-
aria.setState(
182-
element,
183-
aria.State.LABEL,
184-
this.name ? `Text ${this.name}` : 'Text',
185-
);
187+
aria.setState(element, aria.State.LABEL, this.getAriaName() ?? 'Text');
186188
}
187189

188190
override isFullBlockField(): boolean {

0 commit comments

Comments
 (0)