Skip to content

Commit

Permalink
refactor: combobox machine and connect
Browse files Browse the repository at this point in the history
  • Loading branch information
segunadebayo committed Apr 25, 2022
1 parent b396be7 commit e251c32
Show file tree
Hide file tree
Showing 5 changed files with 137 additions and 163 deletions.
32 changes: 7 additions & 25 deletions packages/machines/combobox/src/combobox.connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,42 +135,24 @@ export function connect<T extends PropTypes = ReactPropTypes>(state: State, send
const evt = getNativeEvent(event)
if (evt.ctrlKey || evt.shiftKey || evt.isComposing) return

let preventDefault = false
let prevent = false

const keymap: EventKeyMap = {
ArrowDown(event) {
send(event.altKey ? "ALT_ARROW_DOWN" : "ARROW_DOWN")
preventDefault = true
prevent = true
},
ArrowUp() {
send("ARROW_UP")
preventDefault = true
},
Home(event) {
const isCtrlKey = event.ctrlKey || event.metaKey
if (isCtrlKey) return
send("HOME")
preventDefault = true
},
End(event) {
const isCtrlKey = event.ctrlKey || event.metaKey
if (isCtrlKey) return
send("END")
preventDefault = true
send(event.altKey ? "ALT_ARROW_UP" : "ARROW_UP")
prevent = true
},
Enter() {
send("ENTER")
preventDefault = true
prevent = true
},
Escape() {
send("ESCAPE")
preventDefault = true
},
Backspace() {
send("CLEAR_FOCUS")
},
Delete() {
send("CLEAR_FOCUS")
prevent = true
},
Tab() {
send("TAB")
Expand All @@ -181,7 +163,7 @@ export function connect<T extends PropTypes = ReactPropTypes>(state: State, send
const exec = keymap[key]
exec?.(event)

if (preventDefault) {
if (prevent) {
event.preventDefault()
}
},
Expand Down
18 changes: 11 additions & 7 deletions packages/machines/combobox/src/combobox.dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,22 @@ export const dom = {
}),
getOptionCount: (ctx: Ctx) => {
// if option has `aria-setsize`, announce the number of options
const listboxEl = dom.getListboxEl(ctx)
const setSize = listboxEl?.querySelector("[role-option]")?.getAttribute("aria-setsize")
if (setSize != null) {
return parseInt(setSize)
}
const listbox = dom.getListboxEl(ctx)
const count = listbox?.querySelector("[role-option]")?.getAttribute("aria-setsize")

if (count != null) return parseInt(count)
// else announce the number of options by querying the listbox
return listboxEl?.querySelectorAll("[role=option]").length ?? 0
return listbox?.querySelectorAll("[role=option]").length ?? 0
},
getMatchingOptionEl: (ctx: Ctx, value = ctx.inputValue) => {
if (!value) return null

const selector = `[role=option][data-label="${CSS.escape(value)}"`
return dom.getListboxEl(ctx)?.querySelector<HTMLElement>(selector)

const listbox = dom.getListboxEl(ctx)
if (!listbox) return null

return listbox.querySelector<HTMLElement>(selector)
},

scrollIntoView: (ctx: Ctx, el: HTMLElement) => {
Expand Down
Loading

0 comments on commit e251c32

Please sign in to comment.