diff --git a/src/index.ts b/src/index.ts index 80768b5..87b8146 100644 --- a/src/index.ts +++ b/src/index.ts @@ -126,28 +126,17 @@ export default class Combobox { const target = els[indexOfItem] if (!target) return - for (const el of els) { - el.removeAttribute('data-combobox-option-default') - - if (target === el) { - if (!target.id && !document.getElementById(`${this.list.id}-selected`)) { - target.id = `${this.list.id}-selected` - this.didAutoAssignLastSelectedId = true - } - if (target.id) { - this.input.setAttribute('aria-activedescendant', target.id) - } - target.setAttribute('aria-selected', 'true') - fireSelectEvent(target) - target.scrollIntoView(this.scrollIntoViewOptions) - } else { - if (el.id === `${this.list.id}-selected` && this.didAutoAssignLastSelectedId) { - el.removeAttribute('id') - this.didAutoAssignLastSelectedId = false - } - el.removeAttribute('aria-selected') - } + this.clearSelection() + if (!target.id && !document.getElementById(`${this.list.id}-selected`)) { + target.id = `${this.list.id}-selected` + this.didAutoAssignLastSelectedId = true + } + if (target.id) { + this.input.setAttribute('aria-activedescendant', target.id) } + target.setAttribute('aria-selected', 'true') + fireSelectEvent(target) + target.scrollIntoView(this.scrollIntoViewOptions) } clearSelection(): void { diff --git a/test/test.js b/test/test.js index 781a7f0..80c7e8a 100644 --- a/test/test.js +++ b/test/test.js @@ -531,5 +531,20 @@ describe('combobox-nav', function () { assert.equal(list.children[1].getAttribute('id'), 'hubot') assert.equal(list.children[2].getAttribute('id'), null) }) + + it('moves generated IDs backwards with the selected option', function () { + list.children[1].removeAttribute('id') + const combobox = new Combobox(input, list) + combobox.start() + press(input, 'ArrowDown') + press(input, 'ArrowDown') + press(input, 'ArrowUp') + + assert.equal(list.children[0].id, 'list-id-selected') + assert.equal(list.children[1].getAttribute('id'), null) + assert.equal(input.getAttribute('aria-activedescendant'), list.children[0].id) + assert.equal(document.getElementById(input.getAttribute('aria-activedescendant')), list.children[0]) + combobox.destroy() + }) }) })