diff --git a/app/assets/javascripts/hw_combobox/models/combobox/selection.js b/app/assets/javascripts/hw_combobox/models/combobox/selection.js index fff228b..61a9610 100644 --- a/app/assets/javascripts/hw_combobox/models/combobox/selection.js +++ b/app/assets/javascripts/hw_combobox/models/combobox/selection.js @@ -71,9 +71,9 @@ Combobox.Selection = Base => class extends Base { } } - _selectFuzzyMatch() { - if (this._isFuzzyMatch) { - this._select(this._visibleOptionElements[0], { force: true }) + _ensureSelection() { + if (this._shouldEnsureSelection) { + this._select(this._ensurableOption, { force: true }) this.filter(nullEvent) } } @@ -82,7 +82,11 @@ Combobox.Selection = Base => class extends Base { return this.hiddenFieldTarget.value && !this._selectedOptionElement } - get _isFuzzyMatch() { - return this._isQueried && !!this._visibleOptionElements[0] && !this._isNewOptionWithPotentialMatches + get _shouldEnsureSelection() { + return this._isQueried && !!this._ensurableOption && !this._isNewOptionWithPotentialMatches + } + + get _ensurableOption() { + return this._selectedOptionElement || this._visibleOptionElements[0] } } diff --git a/app/assets/javascripts/hw_combobox/models/combobox/toggle.js b/app/assets/javascripts/hw_combobox/models/combobox/toggle.js index d7ef978..079b60b 100644 --- a/app/assets/javascripts/hw_combobox/models/combobox/toggle.js +++ b/app/assets/javascripts/hw_combobox/models/combobox/toggle.js @@ -50,10 +50,6 @@ Combobox.Toggle = Base => class extends Base { return clientX >= left && clientX <= right && clientY >= top && clientY <= bottom } - _ensureSelection() { - this._selectFuzzyMatch() - } - _openByFocusing() { this._actingCombobox.focus() } diff --git a/test/system/hotwire_combobox_test.rb b/test/system/hotwire_combobox_test.rb index 77e1b9f..c33682a 100644 --- a/test/system/hotwire_combobox_test.rb +++ b/test/system/hotwire_combobox_test.rb @@ -108,6 +108,19 @@ class HotwireComboboxTest < ApplicationSystemTestCase assert_selected_option_with selector: ".hw-combobox__option--selected", text: "Florida" end + test "selecting with the keyboard" do + visit html_options_path + + open_combobox "#state-field" + type_in_combobox "#state-field", "mi" + type_in_combobox "#state-field", :down, :down + assert_selected_option_with text: "Mississippi" + + type_in_combobox "#state-field", :enter + assert_closed_combobox + assert_combobox_display_and_value "#state-field", "Mississippi", "MS" + end + test "pressing enter locks in the current selection, but editing the text field resets it" do visit html_options_path