Skip to content

Commit 523dca9

Browse files
authored
fix: fieldDropdown.getText works in node (#9048)
* fix: dropdown getText works in node * chore: comment
1 parent 7a7fad4 commit 523dca9

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

core/field_dropdown.ts

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -633,7 +633,13 @@ export class FieldDropdown extends Field<string> {
633633
/**
634634
* Use the `getText_` developer hook to override the field's text
635635
* representation. Get the selected option text. If the selected option is
636-
* an image we return the image alt text.
636+
* an image we return the image alt text. If the selected option is
637+
* an HTMLElement, return the title, ariaLabel, or innerText of the
638+
* element.
639+
*
640+
* If you use HTMLElement options in Node.js and call this function,
641+
* ensure that you are supplying an implementation of HTMLElement,
642+
* such as through jsdom-global.
637643
*
638644
* @returns Selected option text.
639645
*/
@@ -644,10 +650,21 @@ export class FieldDropdown extends Field<string> {
644650
const option = this.selectedOption[0];
645651
if (isImageProperties(option)) {
646652
return option.alt;
647-
} else if (option instanceof HTMLElement) {
653+
} else if (
654+
typeof HTMLElement !== 'undefined' &&
655+
option instanceof HTMLElement
656+
) {
648657
return option.title ?? option.ariaLabel ?? option.innerText;
658+
} else if (typeof option === 'string') {
659+
return option;
649660
}
650-
return option;
661+
662+
console.warn(
663+
"Can't get text for existing dropdown option. If " +
664+
"you're using HTMLElement dropdown options in node, ensure you're " +
665+
'using jsdom-global or similar.',
666+
);
667+
return null;
651668
}
652669

653670
/**

tests/node/run_node_test.mjs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,4 +181,11 @@ suite('Test Node.js', function () {
181181

182182
assert.deepEqual(jsonAfter, json);
183183
});
184+
test('Dropdown getText works with no HTMLElement defined', function () {
185+
const field = new Blockly.FieldDropdown([
186+
['firstOption', '1'],
187+
['secondOption', '2'],
188+
]);
189+
assert.equal(field.getText(), 'firstOption');
190+
});
184191
});

0 commit comments

Comments
 (0)