From 523dca92bd4492115e58686e487b6aba3cfd5dcf Mon Sep 17 00:00:00 2001 From: Maribeth Moffatt Date: Wed, 14 May 2025 12:22:09 -0700 Subject: [PATCH] fix: fieldDropdown.getText works in node (#9048) * fix: dropdown getText works in node * chore: comment --- core/field_dropdown.ts | 23 ++++++++++++++++++++--- tests/node/run_node_test.mjs | 7 +++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/core/field_dropdown.ts b/core/field_dropdown.ts index 0b787bd77..b57668516 100644 --- a/core/field_dropdown.ts +++ b/core/field_dropdown.ts @@ -633,7 +633,13 @@ export class FieldDropdown extends Field { /** * 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 { 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; } /** diff --git a/tests/node/run_node_test.mjs b/tests/node/run_node_test.mjs index f32286bba..c6d215069 100644 --- a/tests/node/run_node_test.mjs +++ b/tests/node/run_node_test.mjs @@ -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'); + }); });