powerSearchNavigation.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 (event.key === "ArrowDown") {
  20. itemIndex.value = itemIndexValue < lastItemIndex ? itemIndexValue + 1 : 0
  21. } else if (itemIndexValue === 0) itemIndex.value = lastItemIndex
  22. else if (event.key === "ArrowUp") itemIndex.value = itemIndexValue - 1
  23. }
  24. const preventPropagation = options && options.stopPropagation
  25. const selectedEntry = ref(0)
  26. const onKeyUp = (event: any) => {
  27. handleArrowKeysNavigation(event, selectedEntry, preventPropagation)
  28. }
  29. function bindArrowKeysListerners() {
  30. window.addEventListener("keydown", onKeyUp, { capture: preventPropagation })
  31. }
  32. function unbindArrowKeysListerners() {
  33. window.removeEventListener("keydown", onKeyUp, {
  34. capture: preventPropagation,
  35. })
  36. }
  37. return {
  38. bindArrowKeysListerners,
  39. unbindArrowKeysListerners,
  40. selectedEntry,
  41. }
  42. }