fix: fieldDropdown.getText works in node (#9048)

* fix: dropdown getText works in node

* chore: comment
This commit is contained in:
Maribeth Moffatt
2025-05-14 12:22:09 -07:00
committed by GitHub
parent 7a7fad45c1
commit 523dca92bd
2 changed files with 27 additions and 3 deletions

View File

@@ -633,7 +633,13 @@ export class FieldDropdown extends Field<string> {
/**
* Use the `getText_` developer hook to override the field's text
* representation. Get the selected option text. If the selected option is
* an image we return the image alt text.
* an image we return the image alt text. If the selected option is
* an HTMLElement, return the title, ariaLabel, or innerText of the
* element.
*
* If you use HTMLElement options in Node.js and call this function,
* ensure that you are supplying an implementation of HTMLElement,
* such as through jsdom-global.
*
* @returns Selected option text.
*/
@@ -644,10 +650,21 @@ export class FieldDropdown extends Field<string> {
const option = this.selectedOption[0];
if (isImageProperties(option)) {
return option.alt;
} else if (option instanceof HTMLElement) {
} else if (
typeof HTMLElement !== 'undefined' &&
option instanceof HTMLElement
) {
return option.title ?? option.ariaLabel ?? option.innerText;
} else if (typeof option === 'string') {
return option;
}
return option;
console.warn(
"Can't get text for existing dropdown option. If " +
"you're using HTMLElement dropdown options in node, ensure you're " +
'using jsdom-global or similar.',
);
return null;
}
/**

View File

@@ -181,4 +181,11 @@ suite('Test Node.js', function () {
assert.deepEqual(jsonAfter, json);
});
test('Dropdown getText works with no HTMLElement defined', function () {
const field = new Blockly.FieldDropdown([
['firstOption', '1'],
['secondOption', '2'],
]);
assert.equal(field.getText(), 'firstOption');
});
});