| 29 | * The hook automatically resets manual focus when the view changes. |
| 30 | */ |
| 31 | export function useFocusManagement({ |
| 32 | showApprovalPrompt, |
| 33 | pendingAsk, |
| 34 | }: UseFocusManagementOptions): UseFocusManagementReturn { |
| 35 | const { showCustomInput, manualFocus, setManualFocus } = useUIStateStore() |
| 36 | |
| 37 | // Determine if we're in a mode where focus can be toggled (text input is available) |
| 38 | const canToggleFocus = |
| 39 | !showApprovalPrompt && |
| 40 | (!pendingAsk || // Initial input or task complete or loading |
| 41 | pendingAsk.type === "followup" || // Followup question with suggestions or custom input |
| 42 | showCustomInput) // Custom input mode |
| 43 | |
| 44 | // Determine if scroll area should capture keyboard input |
| 45 | const isScrollAreaActive: boolean = |
| 46 | manualFocus === "scroll" ? true : manualFocus === "input" ? false : Boolean(showApprovalPrompt) |
| 47 | |
| 48 | // Determine if input area is active (for visual focus indicator) |
| 49 | const isInputAreaActive: boolean = |
| 50 | manualFocus === "input" ? true : manualFocus === "scroll" ? false : !showApprovalPrompt |
| 51 | |
| 52 | // Reset manual focus when view changes (e.g., agent starts responding) |
| 53 | useEffect(() => { |
| 54 | if (!canToggleFocus) { |
| 55 | setManualFocus(null) |
| 56 | } |
| 57 | }, [canToggleFocus, setManualFocus]) |
| 58 | |
| 59 | /** |
| 60 | * Toggle focus between scroll and input areas |
| 61 | */ |
| 62 | const toggleFocus = () => { |
| 63 | if (!canToggleFocus) { |
| 64 | return |
| 65 | } |
| 66 | |
| 67 | const prev = manualFocus |
| 68 | if (prev === "scroll") { |
| 69 | setManualFocus("input") |
| 70 | } else if (prev === "input") { |
| 71 | setManualFocus("scroll") |
| 72 | } else { |
| 73 | setManualFocus(isScrollAreaActive ? "input" : "scroll") |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | return { |
| 78 | canToggleFocus, |
| 79 | isScrollAreaActive, |
| 80 | isInputAreaActive, |
| 81 | manualFocus, |
| 82 | setManualFocus, |
| 83 | toggleFocus, |
| 84 | } |
| 85 | } |