add basic keyboard navigation

This commit is contained in:
Philipp Kühn 2021-01-18 16:45:49 +01:00
parent 697eb4fc49
commit 7adc8b24a0
3 changed files with 75 additions and 7 deletions

View File

@ -1,6 +1,11 @@
<template>
<div>
<div v-for="(item, index) in items" :key="index">
<div class="items">
<div
class="item"
:class="{ 'is-selected': index === selectedIndex }"
v-for="(item, index) in items"
:key="index"
>
{{ item }}
</div>
</div>
@ -14,9 +19,69 @@ export default {
default: () => [],
},
},
data() {
return {
selectedIndex: 0,
}
},
watch: {
items() {
this.selectedIndex = 0
},
},
methods: {
onKeyDown({ event }) {
if (event.key === 'ArrowUp') {
this.upHandler()
return true
}
if (event.key === 'ArrowDown') {
this.downHandler()
return true
}
if (event.key === 'Enter') {
this.enterHandler()
return true
}
return false
},
upHandler() {
this.selectedIndex = ((this.selectedIndex + this.items.length) - 1) % this.items.length
},
downHandler() {
this.selectedIndex = (this.selectedIndex + 1) % this.items.length
},
enterHandler() {
const item = this.items[this.selectedIndex]
if (item) {
console.log('select', item)
}
},
},
}
</script>
<style>
<style lang="scss" scoped>
.items {
position: relative;
}
.item {
background: white;
color: black;
padding: 0.5rem;
&.is-selected {
background: #ccc;
}
}
</style>

View File

@ -58,6 +58,9 @@ export default {
onUpdate(props) {
component.updateProps(props)
},
onKeyDown(props) {
return component.vm.onKeyDown(props)
},
onExit() {
popup[0].destroy()
component.destroy()

View File

@ -13,10 +13,10 @@ export interface SuggestionOptions {
command?: () => any,
items?: (query: string) => any[],
renderer?: () => {
onStart?: (props: any) => any,
onUpdate?: (props: any) => any,
onExit?: (props: any) => any,
onKeyDown?: (props: any) => any,
onStart?: (props: any) => void,
onUpdate?: (props: any) => void,
onExit?: (props: any) => void,
onKeyDown?: (props: any) => boolean,
},
}