Skip to content

Commit

Permalink
Merge pull request #76 from nicowenterodt/combobox-select-event
Browse files Browse the repository at this point in the history
Introduce combobox-select event
  • Loading branch information
camertron authored Sep 14, 2023
2 parents a3d2178 + da9f673 commit 3fe250b
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,16 @@ list.addEventListener('combobox-commit', function (event) {
When a label is clicked on, `click` event is fired from both `<label>` and its associated input `label.control`. Since combobox does not know about the control, `combobox-commit` cannot be used as an indicator of the item's selection state.

A bubbling `combobox-select` event is fired on the list element when an option is selected but not yet committed.

For example, autocomplete when an option is selected but not yet committed:

```js
list.addEventListener('combobox-select', function (event) {
console.log('Element selected : ', event.target)
})
```

## Settings

For advanced configuration, the constructor takes an optional third argument. For example:
Expand Down
5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ export default class Combobox {
if (target === el) {
this.input.setAttribute('aria-activedescendant', target.id)
target.setAttribute('aria-selected', 'true')
fireSelectEvent(target)
scrollTo(this.list, target)
} else {
el.removeAttribute('aria-selected')
Expand Down Expand Up @@ -188,6 +189,10 @@ function fireCommitEvent(target: Element, detail?: Record<string, unknown>): voi
target.dispatchEvent(new CustomEvent('combobox-commit', {bubbles: true, detail}))
}

function fireSelectEvent(target: Element): void {
target.dispatchEvent(new Event('combobox-select', {bubbles: true}))
}

function visible(el: HTMLElement): boolean {
return (
!el.hidden &&
Expand Down
15 changes: 15 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,21 @@ describe('combobox-nav', function () {
assert.equal(expectedTargets[1], 'baymax')
})

it('fires select events on navigating', function () {
const expectedTargets = []

document.addEventListener('combobox-select', function ({target}) {
expectedTargets.push(target.id)
})

press(input, 'ArrowDown')
press(input, 'ArrowDown')

assert.equal(expectedTargets.length, 2)
assert.equal(expectedTargets[0], 'baymax')
assert.equal(expectedTargets[1], 'hubot')
})

it('clear selection on input operation', function () {
press(input, 'ArrowDown')
assert.equal(options[0].getAttribute('aria-selected'), 'true')
Expand Down

0 comments on commit 3fe250b

Please sign in to comment.