Open History to see the last commit
1import { useEffect, useRef, type RefObject } from "react";
2
3import { isCommandPaletteOpen } from "../commandPaletteBus";
4import { shouldRedirectInputToComposer } from "../components/chat/composerFocusRedirect";
5
6function isFrozenComposerTarget(target: Element, form: HTMLFormElement | null) {
7 return (
8 !!form?.contains(target) &&
9 !!target.closest('[data-testid="composer-editor"]') &&
10 !target.closest("textarea, input, button")
11 );
12}
13
14/** Keep submission shortcuts reachable when the frozen composer loses focus to the page. */
15export function useDictationSubmissionShortcut(input: {
16 enabled: boolean;
17 formRef: RefObject<HTMLFormElement | null>;
18 onKeyDown(event: KeyboardEvent): void;
19}) {
20 const latest = useRef(input);
21 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed inputs to the window keydown listener
22 useEffect(() => {
23 latest.current = input;
24 });
25 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to window keydown while dictation owns submission
26 useEffect(() => {
27 if (!input.enabled) return;
28 const onKeyDown = (event: KeyboardEvent) => {
29 if (event.defaultPrevented || isCommandPaletteOpen()) return;
30 const target = event.target;
31 if (!(target instanceof Element)) return;
32 if (
33 target !== document.body &&
34 target !== document.documentElement &&
35 !isFrozenComposerTarget(target, latest.current.formRef.current) &&
36 // Focus parked on the chat itself, such as the timeline, belongs to the composer.
37 !shouldRedirectInputToComposer(event)
38 )
39 return;
40 latest.current.onKeyDown(event);
41 };
42 window.addEventListener("keydown", onKeyDown, true);
43 return () => window.removeEventListener("keydown", onKeyDown, true);
44 }, [input.enabled]);
45}