Files
blockly/core/field_number.ts
Ben Henning 3cf834a6a6 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.
2025-10-01 16:19:06 -07:00

382 lines
11 KiB
TypeScript

/**
* @license
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Number input field
*
* @class
*/
// Former goog.module ID: Blockly.FieldNumber
import {Field} from './field.js';
import {
FieldInput,
FieldInputConfig,
FieldInputValidator,
} from './field_input.js';
import * as fieldRegistry from './field_registry.js';
import * as dom from './utils/dom.js';
// TODO: Figure out how to either design this to be a 'number' input with proper
// 'valuemin' and 'valuemax' ARIA properties, build it so that subtypes can do
// this properly, or consider a separate field type altogether that handles that
// case properly. See: https://github.com/google/blockly/pull/9384#discussion_r2395601092.
/**
* Class for an editable number field.
*/
export class FieldNumber extends FieldInput<number> {
/** The minimum value this number field can contain. */
protected min_ = -Infinity;
/** The maximum value this number field can contain. */
protected max_ = Infinity;
/** The multiple to which this fields value is rounded. */
protected precision_ = 0;
/**
* The number of decimal places to allow, or null to allow any number of
* decimal digits.
*/
private decimalPlaces: number | null = null;
/** Don't spellcheck numbers. Our validator does a better job. */
protected override spellcheck_ = false;
/**
* @param value The initial value of the field. Should cast to a number.
* Defaults to 0. Also accepts Field.SKIP_SETUP if you wish to skip setup
* (only used by subclasses that want to handle configuration and setting
* the field value after their own constructors have run).
* @param min Minimum value. Will only be used if config is not
* provided.
* @param max Maximum value. Will only be used if config is not
* provided.
* @param precision Precision for value. Will only be used if config
* is not provided.
* @param validator A function that is called to validate changes to the
* field's value. Takes in a number & returns a validated number, or null
* to abort the change.
* @param config A map of options used to configure the field.
* See the [field creation documentation]{@link
* https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/number#creation}
* for a list of properties this parameter supports.
*/
constructor(
value?: string | number | typeof Field.SKIP_SETUP,
min?: string | number | null,
max?: string | number | null,
precision?: string | number | null,
validator?: FieldNumberValidator | null,
config?: FieldNumberConfig,
) {
// Pass SENTINEL so that we can define properties before value validation.
super(Field.SKIP_SETUP);
if (value === Field.SKIP_SETUP) return;
if (config) {
this.configure_(config);
} else {
this.setConstraints(min, max, precision);
}
this.setValue(value);
if (validator) {
this.setValidator(validator);
}
}
/**
* Configure the field based on the given map of options.
*
* @param config A map of options to configure the field based on.
*/
protected override configure_(config: FieldNumberConfig) {
super.configure_(config);
this.setMinInternal(config.min);
this.setMaxInternal(config.max);
this.setPrecisionInternal(config.precision);
}
/**
* Set the maximum, minimum and precision constraints on this field.
* Any of these properties may be undefined or NaN to be disabled.
* Setting precision (usually a power of 10) enforces a minimum step between
* values. That is, the user's value will rounded to the closest multiple of
* precision. The least significant digit place is inferred from the
* precision. Integers values can be enforces by choosing an integer
* precision.
*
* @param min Minimum value.
* @param max Maximum value.
* @param precision Precision for value.
*/
setConstraints(
min: number | string | undefined | null,
max: number | string | undefined | null,
precision: number | string | undefined | null,
) {
this.setMinInternal(min);
this.setMaxInternal(max);
this.setPrecisionInternal(precision);
this.setValue(this.getValue());
}
/**
* Sets the minimum value this field can contain. Updates the value to
* reflect.
*
* @param min Minimum value.
*/
setMin(min: number | string | undefined | null) {
this.setMinInternal(min);
this.setValue(this.getValue());
}
/**
* Sets the minimum value this field can contain. Called internally to avoid
* value updates.
*
* @param min Minimum value.
*/
private setMinInternal(min: number | string | undefined | null) {
if (min == null) {
this.min_ = -Infinity;
} else {
min = Number(min);
if (!isNaN(min)) {
this.min_ = min;
}
}
}
/**
* Returns the current minimum value this field can contain. Default is
* -Infinity.
*
* @returns The current minimum value this field can contain.
*/
getMin(): number {
return this.min_;
}
/**
* Sets the maximum value this field can contain. Updates the value to
* reflect.
*
* @param max Maximum value.
*/
setMax(max: number | string | undefined | null) {
this.setMaxInternal(max);
this.setValue(this.getValue());
}
/**
* Sets the maximum value this field can contain. Called internally to avoid
* value updates.
*
* @param max Maximum value.
*/
private setMaxInternal(max: number | string | undefined | null) {
if (max == null) {
this.max_ = Infinity;
} else {
max = Number(max);
if (!isNaN(max)) {
this.max_ = max;
}
}
}
/**
* Returns the current maximum value this field can contain. Default is
* Infinity.
*
* @returns The current maximum value this field can contain.
*/
getMax(): number {
return this.max_;
}
/**
* Sets the precision of this field's value, i.e. the number to which the
* value is rounded. Updates the field to reflect.
*
* @param precision The number to which the field's value is rounded.
*/
setPrecision(precision: number | string | undefined | null) {
this.setPrecisionInternal(precision);
this.setValue(this.getValue());
}
/**
* Sets the precision of this field's value. Called internally to avoid
* value updates.
*
* @param precision The number to which the field's value is rounded.
*/
private setPrecisionInternal(precision: number | string | undefined | null) {
this.precision_ = Number(precision) || 0;
let precisionString = String(this.precision_);
if (precisionString.includes('e')) {
// String() is fast. But it turns .0000001 into '1e-7'.
// Use the much slower toLocaleString to access all the digits.
precisionString = this.precision_.toLocaleString('en-US', {
maximumFractionDigits: 20,
});
}
const decimalIndex = precisionString.indexOf('.');
if (decimalIndex === -1) {
// If the precision is 0 (float) allow any number of decimals,
// otherwise allow none.
this.decimalPlaces = precision ? 0 : null;
} else {
this.decimalPlaces = precisionString.length - decimalIndex - 1;
}
}
/**
* Returns the current precision of this field. The precision being the
* number to which the field's value is rounded. A precision of 0 means that
* the value is not rounded.
*
* @returns The number to which this field's value is rounded.
*/
getPrecision(): number {
return this.precision_;
}
/**
* Ensure that the input value is a valid number (must fulfill the
* constraints placed on the field).
*
* @param newValue The input value.
* @returns A valid number, or null if invalid.
*/
protected override doClassValidation_(
newValue?: AnyDuringMigration,
): number | null {
if (newValue === null) {
return null;
}
// Clean up text.
newValue = `${newValue}`;
// TODO: Handle cases like 'ten', '1.203,14', etc.
// 'O' is sometimes mistaken for '0' by inexperienced users.
newValue = newValue.replace(/O/gi, '0');
// Strip out thousands separators.
newValue = newValue.replace(/,/g, '');
// Ignore case of 'Infinity'.
newValue = newValue.replace(/infinity/i, 'Infinity');
// Clean up number.
let n = Number(newValue || 0);
if (isNaN(n)) {
// Invalid number.
return null;
}
// Get the value in range.
n = Math.min(Math.max(n, this.min_), this.max_);
// Round to nearest multiple of precision.
if (this.precision_ && isFinite(n)) {
n = Math.round(n / this.precision_) * this.precision_;
}
// Clean up floating point errors.
if (this.decimalPlaces !== null) {
n = Number(n.toFixed(this.decimalPlaces));
}
return n;
}
/**
* Create the number input editor widget.
*
* @returns The newly created number input editor.
*/
protected override widgetCreate_(): HTMLInputElement {
const htmlInput = super.widgetCreate_() as HTMLInputElement;
if (this.min_ > -Infinity) {
htmlInput.min = `${this.min_}`;
}
if (this.max_ < Infinity) {
htmlInput.max = `${this.max_}`;
}
return htmlInput;
}
/**
* Initialize the field's DOM.
*
* @override
*/
public override initView() {
super.initView();
if (this.fieldGroup_) {
dom.addClass(this.fieldGroup_, 'blocklyNumberField');
}
}
/**
* Construct a FieldNumber from a JSON arg object.
*
* @param options A JSON object with options (value, min, max, and precision).
* @returns The new field instance.
* @nocollapse
* @internal
*/
static override fromJson(options: FieldNumberFromJsonConfig): FieldNumber {
// `this` might be a subclass of FieldNumber if that class doesn't override
// the static fromJson method.
return new this(
options.value,
undefined,
undefined,
undefined,
undefined,
options,
);
}
}
fieldRegistry.register('field_number', FieldNumber);
FieldNumber.prototype.DEFAULT_VALUE = 0;
/**
* Config options for the number field.
*/
export interface FieldNumberConfig extends FieldInputConfig {
min?: number;
max?: number;
precision?: number;
}
/**
* fromJson config options for the number field.
*/
export interface FieldNumberFromJsonConfig extends FieldNumberConfig {
value?: number;
}
/**
* A function that is called to validate changes to the field's value before
* they are set.
*
* @see {@link https://developers.google.com/blockly/guides/create-custom-blocks/fields/validators#return_values}
* @param newValue The value to be validated.
* @returns One of three instructions for setting the new value: `T`, `null`,
* or `undefined`.
*
* - `T` to set this function's returned value instead of `newValue`.
*
* - `null` to invoke `doValueInvalid_` and not set a value.
*
* - `undefined` to set `newValue` as is.
*/
export type FieldNumberValidator = FieldInputValidator<number>;