The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { useRef, useState } from "react"; |
| 2 | |
| 3 | import type { ComposerTrigger } from "../../composer-logic"; |
| 4 | |
| 5 | const isSameTrigger = (a: ComposerTrigger | null, b: ComposerTrigger | null) => |
| 6 | a !== null && b !== null && a.kind === b.kind && a.rangeStart === b.rangeStart; |
| 7 | |
| 8 | /** Edits open suggestions unless Escape dismissed the trigger; caret moves only close, resets can open. */ |
| 9 | export function useComposerTriggerState(initialTrigger: () => ComposerTrigger | null) { |
| 10 | const [trigger, setActiveTrigger] = useState(initialTrigger); |
| 11 | // Key handlers read this before React commits the state. |
| 12 | const activeTriggerRef = useRef(trigger); |
| 13 | const dismissedTriggerRef = useRef<ComposerTrigger | null>(null); |
| 14 | |
| 15 | const activate = (next: ComposerTrigger | null) => { |
| 16 | activeTriggerRef.current = next; |
| 17 | setActiveTrigger(next); |
| 18 | }; |
| 19 | |
| 20 | /** The trigger at the caret when its menu is the open one, otherwise null. */ |
| 21 | const resolveTrigger = (candidate: ComposerTrigger | null) => |
| 22 | isSameTrigger(activeTriggerRef.current, candidate) ? candidate : null; |
| 23 | |
| 24 | /** After a text edit, with the trigger at the caret. */ |
| 25 | const setTrigger = (candidate: ComposerTrigger | null) => { |
| 26 | if (isSameTrigger(dismissedTriggerRef.current, candidate)) { |
| 27 | activate(null); |
| 28 | return; |
| 29 | } |
| 30 | dismissedTriggerRef.current = null; |
| 31 | activate(candidate); |
| 32 | }; |
| 33 | |
| 34 | /** After the caret moved without an edit, with the trigger at the caret. */ |
| 35 | const followCaret = (candidate: ComposerTrigger | null) => { |
| 36 | if (!isSameTrigger(dismissedTriggerRef.current, candidate)) { |
| 37 | dismissedTriggerRef.current = null; |
| 38 | } |
| 39 | activate(resolveTrigger(candidate)); |
| 40 | }; |
| 41 | |
| 42 | const dismissTrigger = (candidate: ComposerTrigger | null) => { |
| 43 | dismissedTriggerRef.current = candidate; |
| 44 | activate(null); |
| 45 | }; |
| 46 | |
| 47 | const resetTrigger = (candidate: ComposerTrigger | null) => { |
| 48 | dismissedTriggerRef.current = null; |
| 49 | activate(candidate); |
| 50 | }; |
| 51 | |
| 52 | return { trigger, setTrigger, followCaret, resolveTrigger, dismissTrigger, resetTrigger }; |
| 53 | } |