powerSearchNavigation.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { ref } from "@nuxtjs/composition-api"
  2. const NAVIGATION_KEYS = ["ArrowDown", "ArrowUp", "Enter"]
  3. export function useArrowKeysNavigation(searchItems: any, options: any = {}) {
  4. function handleArrowKeysNavigation(
  5. event: any,
  6. itemIndex: any,
  7. preventPropagation: Boolean
  8. ) {
  9. if (!NAVIGATION_KEYS.includes(event.key)) return
  10. if (preventPropagation) event.stopImmediatePropagation()
  11. const itemsLength = searchItems.value.length
  12. const lastItemIndex = itemsLength - 1
  13. const itemIndexValue = itemIndex.value
  14. const action = searchItems.value[itemIndexValue]?.action
  15. if (action && event.key === "Enter" && options.onEnter) {
  16. options.onEnter(action)
  17. return
  18. }
  19. if (itemsLength && event.key === "ArrowDown") {
  20. itemIndex.value = itemIndexValue < lastItemIndex ? itemIndexValue + 1 : 0
  21. } else if (itemIndexValue === 0) itemIndex.value = lastItemIndex
  22. else if (itemsLength && event.key === "ArrowUp")
  23. itemIndex.value = itemIndexValue - 1
  24. }
  25. const preventPropagation = options && options.stopPropagation
  26. const selectedEntry = ref(0)
  27. const onKeyUp = (event: any) => {
  28. handleArrowKeysNavigation(event, selectedEntry, preventPropagation)
  29. }
  30. function bindArrowKeysListeners() {
  31. window.addEventListener("keydown", onKeyUp, { capture: preventPropagation })
  32. }
  33. function unbindArrowKeysListeners() {
  34. window.removeEventListener("keydown", onKeyUp, {
  35. capture: preventPropagation,
  36. })
  37. }
  38. return {
  39. bindArrowKeysListeners,
  40. unbindArrowKeysListeners,
  41. selectedEntry,
  42. }
  43. }