1 "use client"
2
3 import { useCallback, useEffect, useMemo } from "react"
4 import { useAiAssistant } from "@/providers/AiAssistant"
5 import { findNextSibling, findPrevSibling } from "@/utils"
6 import {
7 useKeyboardShortcut,
8 type useKeyboardShortcutOptions,
9 } from "../use-keyboard-shortcut"
10
11 export type UseAiAssistantChatNavigationProps = {
12 getChatWindowElm: () => HTMLElement | null
13 getInputElm: () => HTMLTextAreaElement | null
14 focusInput: () => void
15 keyboardProps?: Partial<useKeyboardShortcutOptions>
16 question: string
17 }
18
19 export const useAiAssistantChatNavigation = ({
20 getInputElm,
21 focusInput,
22 keyboardProps,
23 getChatWindowElm,
24 question,
25 }: UseAiAssistantChatNavigationProps) => {
26 const shortcutKeys = useMemo(() => ["ArrowUp", "ArrowDown", "Enter"], [])
27 const { chatOpened } = useAiAssistant()
28
29 const handleKeyAction = (e: KeyboardEvent) => {
30 const chatElm = getChatWindowElm()
31 if (
32 !chatOpened ||
33 e.metaKey ||
34 e.ctrlKey ||
35 !chatElm?.contains(document.activeElement) ||
36 (question.length && question.includes("\n"))
37 ) {
38 return
39 }
40 e.preventDefault()
41 const focusedItem = chatElm?.querySelector(":focus") as HTMLElement
42 if (!focusedItem) {
43 // focus the first data-hit
44 const nextItem = chatElm?.querySelector("[data-hit]") as HTMLElement
45 nextItem?.focus()
46 return
47 }
48
49 const isHit = focusedItem.hasAttribute("data-hit")
50 const isInput = focusedItem.tagName.toLowerCase() === "textarea"
51
52 if (!isHit && !isInput) {
53 // ignore if focused items aren't input/data-hit
54 return
55 }
56
57 const lowerPressedKey = e.key.toLowerCase()
58
59 if (lowerPressedKey === "enter") {
60 if (isHit) {
61 // trigger click event of the focused element
62 focusedItem.click()
63 }
64 return
65 }
66
67 if (lowerPressedKey === "arrowdown") {
68 // only hit items has action on arrow down
69 if (isHit) {
70 // find if there's a data-hit item before this one
71 const beforeItem = findNextSibling(focusedItem, "[data-hit]")
72 if (!beforeItem) {
73 // focus the input
74 focusInput()
75 } else {
76 // focus the previous item
77 beforeItem.focus()
78 }
79 }
80 } else if (lowerPressedKey === "arrowup") {
81 // check if item is input or hit
82 if (isInput) {
83 // go to the first data-hit item
84 const nextItem = chatElm?.querySelector(
85 "[data-hit]:last-child"
86 ) as HTMLElement
87 nextItem?.focus()
88 } else {
89 // handle go down for hit items
90 // find if there's a data-hit item after this one
91 const afterItem = findPrevSibling(focusedItem, "[data-hit]")
92 if (afterItem) {
93 // focus the next item
94 afterItem.focus()
95 }
96 }
97 }
98 }
99
100 /** Handles starting to type which focuses the input */
101 const handleKeyDown = useCallback(
102 (e: KeyboardEvent) => {
103 if (!chatOpened) {
104 return
105 }
106 // check if shortcut keys were pressed
107 const lowerPressedKey = e.key.toLowerCase()
108 const pressedShortcut = [...shortcutKeys, "Escape"].some(
109 (s) => s.toLowerCase() === lowerPressedKey
110 )
111 if (pressedShortcut) {
112 return
113 }
114
115 const chatElm = getChatWindowElm()
116 if (!chatElm?.contains(document.activeElement)) {
117 return
118 }
119 const focusedItem = chatElm?.querySelector(":focus") as HTMLElement
120 const inputElm = getInputElm()
121 if (inputElm && focusedItem !== inputElm) {
122 focusInput()
123 }
124 },
125 [shortcutKeys, chatOpened, shortcutKeys, getInputElm, focusInput]
126 )
127
128 useEffect(() => {
129 window.addEventListener("keydown", handleKeyDown)
130
131 return () => {
132 window.removeEventListener("keydown", handleKeyDown)
133 }
134 }, [handleKeyDown])
135
136 useKeyboardShortcut({
137 metakey: false,
138 shortcutKeys: shortcutKeys,
139 checkEditing: false,
140 isLoading: false,
141 preventDefault: false,
142 action: handleKeyAction,
143 ...keyboardProps,
144 })
145 }