mirror of
https://github.com/google/blockly.git
synced 2026-01-08 09:30:06 +01:00
## 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.
661 lines
20 KiB
TypeScript
661 lines
20 KiB
TypeScript
/**
|
|
* @license
|
|
* Copyright 2012 Google LLC
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
*/
|
|
|
|
/**
|
|
* Variable input field.
|
|
*
|
|
* @class
|
|
*/
|
|
// Former goog.module ID: Blockly.FieldVariable
|
|
|
|
// Unused import preserved for side-effects. Remove if unneeded.
|
|
import './events/events_block_change.js';
|
|
|
|
import type {Block} from './block.js';
|
|
import {Field, FieldConfig, UnattachedFieldError} from './field.js';
|
|
import {
|
|
FieldDropdown,
|
|
FieldDropdownValidator,
|
|
MenuGenerator,
|
|
MenuOption,
|
|
} from './field_dropdown.js';
|
|
import * as fieldRegistry from './field_registry.js';
|
|
import {IVariableModel, IVariableState} from './interfaces/i_variable_model.js';
|
|
import * as internalConstants from './internal_constants.js';
|
|
import type {Menu} from './menu.js';
|
|
import type {MenuItem} from './menuitem.js';
|
|
import {Msg} from './msg.js';
|
|
import * as dom from './utils/dom.js';
|
|
import * as parsing from './utils/parsing.js';
|
|
import {Size} from './utils/size.js';
|
|
import * as Variables from './variables.js';
|
|
import * as Xml from './xml.js';
|
|
|
|
/**
|
|
* Class for a variable's dropdown field.
|
|
*/
|
|
export class FieldVariable extends FieldDropdown {
|
|
protected override menuGenerator_: MenuGenerator | undefined;
|
|
defaultVariableName: string;
|
|
|
|
/** The type of the default variable for this field. */
|
|
private defaultType = '';
|
|
|
|
/**
|
|
* All of the types of variables that will be available in this field's
|
|
* dropdown.
|
|
*/
|
|
variableTypes: string[] | null = [];
|
|
|
|
/** The variable model associated with this field. */
|
|
private variable: IVariableModel<IVariableState> | null = null;
|
|
|
|
/**
|
|
* Serializable fields are saved by the serializer, non-serializable fields
|
|
* are not. Editable fields should also be serializable.
|
|
*/
|
|
override SERIALIZABLE = true;
|
|
|
|
/**
|
|
* @param varName The default name for the variable.
|
|
* If null, a unique variable name will be generated.
|
|
* 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 validator A function that is called to validate changes to the
|
|
* field's value. Takes in a variable ID & returns a validated variable
|
|
* ID, or null to abort the change.
|
|
* @param variableTypes A list of the types of variables to include in the
|
|
* dropdown. Pass `null` to include all types that exist on the
|
|
* workspace. Will only be used if config is not provided.
|
|
* @param defaultType The type of variable to create if this field's value
|
|
* is not explicitly set. Defaults to ''. Will only be used if config
|
|
* is not provided.
|
|
* @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/variable#creation}
|
|
* for a list of properties this parameter supports.
|
|
*/
|
|
constructor(
|
|
varName: string | null | typeof Field.SKIP_SETUP,
|
|
validator?: FieldVariableValidator,
|
|
variableTypes?: string[] | null,
|
|
defaultType?: string,
|
|
config?: FieldVariableConfig,
|
|
) {
|
|
super(Field.SKIP_SETUP);
|
|
|
|
/**
|
|
* An array of options for a dropdown list,
|
|
* or a function which generates these options.
|
|
*/
|
|
this.menuGenerator_ = FieldVariable.dropdownCreate as MenuGenerator;
|
|
|
|
/**
|
|
* The initial variable name passed to this field's constructor, or an
|
|
* empty string if a name wasn't provided. Used to create the initial
|
|
* variable.
|
|
*/
|
|
this.defaultVariableName = typeof varName === 'string' ? varName : '';
|
|
|
|
/** The size of the area rendered by the field. */
|
|
this.size_ = new Size(0, 0);
|
|
|
|
if (varName === Field.SKIP_SETUP) return;
|
|
|
|
if (config) {
|
|
this.configure_(config);
|
|
} else {
|
|
this.setTypes(variableTypes, defaultType);
|
|
}
|
|
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: FieldVariableConfig) {
|
|
super.configure_(config);
|
|
this.setTypes(config.variableTypes, config.defaultType);
|
|
}
|
|
|
|
/**
|
|
* Initialize the model for this field if it has not already been initialized.
|
|
* If the value has not been set to a variable by the first render, we make up
|
|
* a variable rather than let the value be invalid.
|
|
*/
|
|
override initModel() {
|
|
const block = this.getSourceBlock();
|
|
if (!block) {
|
|
throw new UnattachedFieldError();
|
|
}
|
|
if (this.variable) {
|
|
return; // Initialization already happened.
|
|
}
|
|
const variable = Variables.getOrCreateVariablePackage(
|
|
block.workspace,
|
|
null,
|
|
this.defaultVariableName,
|
|
this.defaultType,
|
|
);
|
|
// Don't call setValue because we don't want to cause a rerender.
|
|
this.doValueUpdate_(variable.getId());
|
|
}
|
|
|
|
override initView() {
|
|
super.initView();
|
|
dom.addClass(this.fieldGroup_!, 'blocklyVariableField');
|
|
}
|
|
|
|
override shouldAddBorderRect_() {
|
|
const block = this.getSourceBlock();
|
|
if (!block) {
|
|
throw new UnattachedFieldError();
|
|
}
|
|
return (
|
|
super.shouldAddBorderRect_() &&
|
|
(!this.getConstants()!.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW ||
|
|
block.type !== 'variables_get')
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Initialize this field based on the given XML.
|
|
*
|
|
* @param fieldElement The element containing information about the variable
|
|
* field's state.
|
|
*/
|
|
override fromXml(fieldElement: Element) {
|
|
const block = this.getSourceBlock();
|
|
if (!block) {
|
|
throw new UnattachedFieldError();
|
|
}
|
|
const id = fieldElement.getAttribute('id');
|
|
const variableName = fieldElement.textContent;
|
|
// 'variabletype' should be lowercase, but until July 2019 it was sometimes
|
|
// recorded as 'variableType'. Thus we need to check for both.
|
|
const variableType =
|
|
fieldElement.getAttribute('variabletype') ||
|
|
fieldElement.getAttribute('variableType') ||
|
|
'';
|
|
|
|
// AnyDuringMigration because: Argument of type 'string | null' is not
|
|
// assignable to parameter of type 'string | undefined'.
|
|
const variable = Variables.getOrCreateVariablePackage(
|
|
block.workspace,
|
|
id,
|
|
variableName as AnyDuringMigration,
|
|
variableType,
|
|
);
|
|
|
|
// This should never happen :)
|
|
if (variableType !== null && variableType !== variable.getType()) {
|
|
throw Error(
|
|
"Serialized variable type with id '" +
|
|
variable.getId() +
|
|
"' had type " +
|
|
variable.getType() +
|
|
', and ' +
|
|
'does not match variable field that references it: ' +
|
|
Xml.domToText(fieldElement) +
|
|
'.',
|
|
);
|
|
}
|
|
|
|
this.setValue(variable.getId());
|
|
}
|
|
|
|
/**
|
|
* Serialize this field to XML.
|
|
*
|
|
* @param fieldElement The element to populate with info about the field's
|
|
* state.
|
|
* @returns The element containing info about the field's state.
|
|
*/
|
|
override toXml(fieldElement: Element): Element {
|
|
// Make sure the variable is initialized.
|
|
this.initModel();
|
|
|
|
fieldElement.id = this.variable!.getId();
|
|
fieldElement.textContent = this.variable!.getName();
|
|
if (this.variable!.getType()) {
|
|
fieldElement.setAttribute('variabletype', this.variable!.getType());
|
|
}
|
|
return fieldElement;
|
|
}
|
|
|
|
/**
|
|
* Saves this field's value.
|
|
*
|
|
* @param doFullSerialization If true, the variable field will serialize the
|
|
* full state of the field being referenced (ie ID, name, and type) rather
|
|
* than just a reference to it (ie ID).
|
|
* @returns The state of the variable field.
|
|
* @internal
|
|
*/
|
|
override saveState(doFullSerialization?: boolean): AnyDuringMigration {
|
|
const legacyState = this.saveLegacyState(FieldVariable);
|
|
if (legacyState !== null) {
|
|
return legacyState;
|
|
}
|
|
// Make sure the variable is initialized.
|
|
this.initModel();
|
|
const state = {'id': this.variable!.getId()};
|
|
if (doFullSerialization) {
|
|
(state as AnyDuringMigration)['name'] = this.variable!.getName();
|
|
(state as AnyDuringMigration)['type'] = this.variable!.getType();
|
|
}
|
|
return state;
|
|
}
|
|
|
|
/**
|
|
* Sets the field's value based on the given state.
|
|
*
|
|
* @param state The state of the variable to assign to this variable field.
|
|
* @internal
|
|
*/
|
|
override loadState(state: AnyDuringMigration) {
|
|
const block = this.getSourceBlock();
|
|
if (!block) {
|
|
throw new UnattachedFieldError();
|
|
}
|
|
if (this.loadLegacyState(FieldVariable, state)) {
|
|
return;
|
|
}
|
|
// This is necessary so that blocks in the flyout can have custom var names.
|
|
const variable = Variables.getOrCreateVariablePackage(
|
|
block.workspace,
|
|
state['id'] || null,
|
|
state['name'],
|
|
state['type'] || '',
|
|
);
|
|
this.setValue(variable.getId());
|
|
}
|
|
|
|
/**
|
|
* Attach this field to a block.
|
|
*
|
|
* @param block The block containing this field.
|
|
*/
|
|
override setSourceBlock(block: Block) {
|
|
if (block.isShadow()) {
|
|
throw Error('Variable fields are not allowed to exist on shadow blocks.');
|
|
}
|
|
super.setSourceBlock(block);
|
|
}
|
|
|
|
/**
|
|
* Get the variable's ID.
|
|
*
|
|
* @returns Current variable's ID.
|
|
*/
|
|
override getValue(): string | null {
|
|
return this.variable ? this.variable.getId() : null;
|
|
}
|
|
|
|
/**
|
|
* Get the text from this field, which is the selected variable's name.
|
|
*
|
|
* @returns The selected variable's name, or the empty string if no variable
|
|
* is selected.
|
|
*/
|
|
override getText(): string {
|
|
return this.variable ? this.variable.getName() : '';
|
|
}
|
|
|
|
/**
|
|
* Get the variable model for the selected variable.
|
|
* Not guaranteed to be in the variable map on the workspace (e.g. if accessed
|
|
* after the variable has been deleted).
|
|
*
|
|
* @returns The selected variable, or null if none was selected.
|
|
* @internal
|
|
*/
|
|
getVariable(): IVariableModel<IVariableState> | null {
|
|
return this.variable;
|
|
}
|
|
|
|
/**
|
|
* Gets the type of this field's default variable.
|
|
*
|
|
* @returns The default type for this variable field.
|
|
*/
|
|
protected getDefaultType(): string {
|
|
return this.defaultType;
|
|
}
|
|
|
|
/**
|
|
* Gets the validation function for this field, or null if not set.
|
|
* Returns null if the variable is not set, because validators should not
|
|
* run on the initial setValue call, because the field won't be attached to
|
|
* a block and workspace at that point.
|
|
*
|
|
* @returns Validation function, or null.
|
|
*/
|
|
override getValidator(): FieldVariableValidator | null {
|
|
// Validators shouldn't operate on the initial setValue call.
|
|
// Normally this is achieved by calling setValidator after setValue, but
|
|
// this is not a possibility with variable fields.
|
|
if (this.variable) {
|
|
return this.validator_;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Ensure that the ID belongs to a valid variable of an allowed type.
|
|
*
|
|
* @param newValue The ID of the new variable to set.
|
|
* @returns The validated ID, or null if invalid.
|
|
*/
|
|
protected override doClassValidation_(
|
|
newValue?: AnyDuringMigration,
|
|
): string | null {
|
|
if (newValue === null) {
|
|
return null;
|
|
}
|
|
const block = this.getSourceBlock();
|
|
if (!block) {
|
|
throw new UnattachedFieldError();
|
|
}
|
|
const newId = newValue as string;
|
|
const variable = Variables.getVariable(block.workspace, newId);
|
|
if (!variable) {
|
|
console.warn(
|
|
"Variable id doesn't point to a real variable! " + 'ID was ' + newId,
|
|
);
|
|
return null;
|
|
}
|
|
// Type Checks.
|
|
const type = variable.getType();
|
|
if (!this.typeIsAllowed(type)) {
|
|
console.warn("Variable type doesn't match this field! Type was " + type);
|
|
return null;
|
|
}
|
|
return newId;
|
|
}
|
|
|
|
/**
|
|
* Update the value of this variable field, as well as its variable and text.
|
|
*
|
|
* The variable ID should be valid at this point, but if a variable field
|
|
* validator returns a bad ID, this could break.
|
|
*
|
|
* @param newId The value to be saved.
|
|
*/
|
|
protected override doValueUpdate_(newId: string) {
|
|
const block = this.getSourceBlock();
|
|
if (!block) {
|
|
throw new UnattachedFieldError();
|
|
}
|
|
this.variable = Variables.getVariable(block.workspace, newId as string);
|
|
super.doValueUpdate_(newId);
|
|
}
|
|
|
|
/**
|
|
* Check whether the given variable type is allowed on this field.
|
|
*
|
|
* @param type The type to check.
|
|
* @returns True if the type is in the list of allowed types.
|
|
*/
|
|
private typeIsAllowed(type: string): boolean {
|
|
const typeList = this.getVariableTypes();
|
|
if (!typeList) {
|
|
return true; // If it's null, all types are valid.
|
|
}
|
|
for (let i = 0; i < typeList.length; i++) {
|
|
if (type === typeList[i]) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Return a list of variable types to include in the dropdown.
|
|
*
|
|
* @returns Array of variable types.
|
|
*/
|
|
private getVariableTypes(): string[] {
|
|
if (this.variableTypes) return this.variableTypes;
|
|
|
|
if (!this.sourceBlock_ || this.sourceBlock_.isDeadOrDying()) {
|
|
// We should include all types in the block's workspace,
|
|
// but the block is dead so just give up.
|
|
return [''];
|
|
}
|
|
|
|
// If variableTypes is null, return all variable types in the workspace.
|
|
let allTypes = this.sourceBlock_.workspace.getVariableMap().getTypes();
|
|
if (this.sourceBlock_.isInFlyout) {
|
|
// If this block is in a flyout, we also need to check the potential variables
|
|
const potentialMap =
|
|
this.sourceBlock_.workspace.getPotentialVariableMap();
|
|
if (!potentialMap) return allTypes;
|
|
allTypes = Array.from(new Set([...allTypes, ...potentialMap.getTypes()]));
|
|
}
|
|
|
|
return allTypes;
|
|
}
|
|
|
|
/**
|
|
* Parse the optional arguments representing the allowed variable types and
|
|
* the default variable type.
|
|
*
|
|
* @param variableTypes A list of the types of variables to include in the
|
|
* dropdown. If null or undefined, variables of all types will be
|
|
* displayed in the dropdown.
|
|
* @param defaultType The type of the variable to create if this field's
|
|
* value is not explicitly set. Defaults to ''.
|
|
*/
|
|
private setTypes(variableTypes: string[] | null = null, defaultType = '') {
|
|
const name = this.getText();
|
|
if (Array.isArray(variableTypes)) {
|
|
if (variableTypes.length === 0) {
|
|
// Throw an error if variableTypes is an empty list.
|
|
throw Error(
|
|
`'variableTypes' of field variable ${name} was an empty list. If you want to include all variable types, pass 'null' instead.`,
|
|
);
|
|
}
|
|
|
|
// Make sure the default type is valid.
|
|
let isInArray = false;
|
|
for (let i = 0; i < variableTypes.length; i++) {
|
|
if (variableTypes[i] === defaultType) {
|
|
isInArray = true;
|
|
}
|
|
}
|
|
if (!isInArray) {
|
|
throw Error(
|
|
"Invalid default type '" +
|
|
defaultType +
|
|
"' in " +
|
|
'the definition of a FieldVariable',
|
|
);
|
|
}
|
|
} else if (variableTypes !== null) {
|
|
throw Error(
|
|
`'variableTypes' was not an array or null in the definition of FieldVariable ${name}`,
|
|
);
|
|
}
|
|
// Only update the field once all checks pass.
|
|
this.defaultType = defaultType;
|
|
this.variableTypes = variableTypes;
|
|
}
|
|
|
|
/**
|
|
* Refreshes the name of the variable by grabbing the name of the model.
|
|
* Used when a variable gets renamed, but the ID stays the same. Should only
|
|
* be called by the block.
|
|
*
|
|
* @internal
|
|
*/
|
|
override refreshVariableName() {
|
|
this.forceRerender();
|
|
}
|
|
|
|
/**
|
|
* Handle the selection of an item in the variable dropdown menu.
|
|
* Special case the 'Rename variable...' and 'Delete variable...' options.
|
|
* In the rename case, prompt the user for a new name.
|
|
*
|
|
* @param menu The Menu component clicked.
|
|
* @param menuItem The MenuItem selected within menu.
|
|
*/
|
|
protected override onItemSelected_(menu: Menu, menuItem: MenuItem) {
|
|
const id = menuItem.getValue();
|
|
// Handle special cases.
|
|
if (this.sourceBlock_ && !this.sourceBlock_.isDeadOrDying()) {
|
|
if (id === internalConstants.RENAME_VARIABLE_ID && this.variable) {
|
|
// Rename variable.
|
|
Variables.renameVariable(this.sourceBlock_.workspace, this.variable);
|
|
return;
|
|
} else if (id === internalConstants.DELETE_VARIABLE_ID && this.variable) {
|
|
// Delete variable.
|
|
const workspace = this.variable.getWorkspace();
|
|
Variables.deleteVariable(workspace, this.variable, this.sourceBlock_);
|
|
return;
|
|
}
|
|
}
|
|
// Handle unspecial case.
|
|
this.setValue(id);
|
|
}
|
|
|
|
/**
|
|
* Overrides referencesVariables(), indicating this field refers to a
|
|
* variable.
|
|
*
|
|
* @returns True.
|
|
* @internal
|
|
*/
|
|
override referencesVariables(): boolean {
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Construct a FieldVariable from a JSON arg object,
|
|
* dereferencing any string table references.
|
|
*
|
|
* @param options A JSON object with options (variable, variableTypes, and
|
|
* defaultType).
|
|
* @returns The new field instance.
|
|
* @nocollapse
|
|
* @internal
|
|
*/
|
|
static override fromJson(
|
|
options: FieldVariableFromJsonConfig,
|
|
): FieldVariable {
|
|
const varName = parsing.replaceMessageReferences(options.variable);
|
|
// `this` might be a subclass of FieldVariable if that class doesn't
|
|
// override the static fromJson method.
|
|
return new this(varName, undefined, undefined, undefined, options);
|
|
}
|
|
|
|
/**
|
|
* Return a sorted list of variable names for variable dropdown menus.
|
|
* Include a special option at the end for creating a new variable name.
|
|
*
|
|
* @returns Array of variable names/id tuples.
|
|
*/
|
|
static dropdownCreate(this: FieldVariable): MenuOption[] {
|
|
if (!this.variable) {
|
|
throw Error(
|
|
'Tried to call dropdownCreate on a variable field with no' +
|
|
' variable selected.',
|
|
);
|
|
}
|
|
const name = this.getText();
|
|
let variableModelList: IVariableModel<IVariableState>[] = [];
|
|
const sourceBlock = this.getSourceBlock();
|
|
if (sourceBlock && !sourceBlock.isDeadOrDying()) {
|
|
const workspace = sourceBlock.workspace;
|
|
const variableTypes = this.getVariableTypes();
|
|
// Get a copy of the list, so that adding rename and new variable options
|
|
// doesn't modify the workspace's list.
|
|
for (let i = 0; i < variableTypes.length; i++) {
|
|
const variableType = variableTypes[i];
|
|
const variables = workspace
|
|
.getVariableMap()
|
|
.getVariablesOfType(variableType);
|
|
variableModelList = variableModelList.concat(variables);
|
|
if (workspace.isFlyout) {
|
|
variableModelList = variableModelList.concat(
|
|
workspace
|
|
.getPotentialVariableMap()
|
|
?.getVariablesOfType(variableType) ?? [],
|
|
);
|
|
}
|
|
}
|
|
}
|
|
variableModelList.sort(Variables.compareByName);
|
|
|
|
const options: [string, string, string?][] = [];
|
|
for (let i = 0; i < variableModelList.length; i++) {
|
|
// Set the UUID as the internal representation of the variable.
|
|
options[i] = [
|
|
variableModelList[i].getName(),
|
|
variableModelList[i].getId(),
|
|
Msg['ARIA_LABEL_FOR_VARIABLE_NAME'].replace(
|
|
'%1',
|
|
variableModelList[i].getName(),
|
|
),
|
|
];
|
|
}
|
|
options.push([
|
|
Msg['RENAME_VARIABLE'],
|
|
internalConstants.RENAME_VARIABLE_ID,
|
|
Msg['RENAME_VARIABLE'],
|
|
]);
|
|
if (Msg['DELETE_VARIABLE']) {
|
|
options.push([
|
|
Msg['DELETE_VARIABLE'].replace('%1', name),
|
|
internalConstants.DELETE_VARIABLE_ID,
|
|
Msg['DELETE_VARIABLE'].replace('%1', name),
|
|
]);
|
|
}
|
|
|
|
return options;
|
|
}
|
|
}
|
|
|
|
fieldRegistry.register('field_variable', FieldVariable);
|
|
|
|
/**
|
|
* Config options for the variable field.
|
|
*/
|
|
export interface FieldVariableConfig extends FieldConfig {
|
|
variableTypes?: string[];
|
|
defaultType?: string;
|
|
}
|
|
|
|
/**
|
|
* fromJson config options for the variable field.
|
|
*/
|
|
export interface FieldVariableFromJsonConfig extends FieldVariableConfig {
|
|
variable?: string;
|
|
}
|
|
|
|
/**
|
|
* 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 FieldVariableValidator = FieldDropdownValidator;
|