Skip to content

Commit cd34c46

Browse files
authored
Merge pull request #56 from github/make-tab-optional
Make `Tab` insertion optional
2 parents b27b2e9 + 7704e9b commit cd34c46

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,18 @@ list.addEventListener('combobox-commit', function(event) {
6868

6969
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.
7070

71+
## Settings
72+
73+
For advanced configuration, the constructor takes an optional third argument. This is a settings object with the following setting:
74+
75+
- `tabInsertsSuggestions: boolean = true` - Control whether the highlighted suggestion is inserted when <kbd>Tab</kbd> is pressed (<kbd>Enter</kbd> will always insert a suggestion regardless of this setting). When `true`, tab-navigation will be hijacked when open (which can have negative impacts on accessibility) but the combobox will more closely imitate a native IDE experience.
76+
77+
For example:
78+
79+
```js
80+
const combobox = new Combobox(input, list, {tabInsertsSuggestions: true})
81+
```
82+
7183
## Development
7284

7385
```

src/index.ts

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
export type ComboboxSettings = {
2+
tabInsertsSuggestions?: boolean
3+
}
4+
15
export default class Combobox {
26
isComposing: boolean
37
list: HTMLElement
@@ -6,10 +10,17 @@ export default class Combobox {
610
compositionEventHandler: (event: Event) => void
711
inputHandler: (event: Event) => void
812
ctrlBindings: boolean
13+
tabInsertsSuggestions: boolean
914

10-
constructor(input: HTMLTextAreaElement | HTMLInputElement, list: HTMLElement) {
15+
constructor(
16+
input: HTMLTextAreaElement | HTMLInputElement,
17+
list: HTMLElement,
18+
{tabInsertsSuggestions}: ComboboxSettings = {}
19+
) {
1120
this.input = input
1221
this.list = list
22+
this.tabInsertsSuggestions = tabInsertsSuggestions ?? true
23+
1324
this.isComposing = false
1425

1526
if (!list.id) {
@@ -103,11 +114,15 @@ function keyboardBindings(event: KeyboardEvent, combobox: Combobox) {
103114

104115
switch (event.key) {
105116
case 'Enter':
106-
case 'Tab':
107117
if (commit(combobox.input, combobox.list)) {
108118
event.preventDefault()
109119
}
110120
break
121+
case 'Tab':
122+
if (combobox.tabInsertsSuggestions && commit(combobox.input, combobox.list)) {
123+
event.preventDefault()
124+
}
125+
break
111126
case 'Escape':
112127
combobox.clearSelection()
113128
break

0 commit comments

Comments
 (0)