The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { ScopedThreadRef } from "@t3tools/contracts"; |
| 2 | import { useEffect } from "react"; |
| 3 | |
| 4 | import { restoreFocusOnThreadEnter } from "../../lib/terminalFocus"; |
| 5 | |
| 6 | /** Restores thread focus, landing the caret a frame after composer entry. */ |
| 7 | export function useFocusComposerOnThreadOpen( |
| 8 | threadRef: ScopedThreadRef | null, |
| 9 | root: HTMLElement | null, |
| 10 | enabled: boolean, |
| 11 | terminalOpen: boolean, |
| 12 | focusComposer: () => void, |
| 13 | ) { |
| 14 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores DOM focus on thread entry and after the drawer opens or closes |
| 15 | useEffect(() => { |
| 16 | if (!threadRef || !enabled || !root) return; |
| 17 | let frame: number | undefined; |
| 18 | const leave = restoreFocusOnThreadEnter(threadRef, { |
| 19 | root, |
| 20 | focusComposer: () => { |
| 21 | frame = window.requestAnimationFrame(() => { |
| 22 | // Double-clicking a sidebar row opens its thread and its rename field in one gesture. |
| 23 | if (document.activeElement?.matches("[data-sidebar-row] input")) return; |
| 24 | focusComposer(); |
| 25 | }); |
| 26 | }, |
| 27 | }); |
| 28 | return () => { |
| 29 | leave(); |
| 30 | if (frame !== undefined) window.cancelAnimationFrame(frame); |
| 31 | }; |
| 32 | }, [ |
| 33 | threadRef, |
| 34 | root, |
| 35 | enabled, |
| 36 | // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Drawer visibility changes also restore focus after explicit open/close actions. |
| 37 | terminalOpen, |
| 38 | focusComposer, |
| 39 | ]); |
| 40 | } |