Open History to see the last commit
1import { pasteTextToFocusComposer, shouldRedirectInputToComposer } from "./composerFocusRedirect";
2import { readPastedComposerContext } from "../composerInlineTokenPaste";
3import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste";
4import { useEffect, useRef } from "react";
5import { isMacPlatform } from "../../lib/utils";
6import { isCommandPaletteOpen } from "../../commandPaletteBus";
7import { getTerminalFocusOwner } from "../../lib/terminalFocus";
8import type { ThreadId } from "@t3tools/contracts";
9import type { ComposerHandleRef } from "../../composerHandleContext";
10/**
11 * Paste-to-focus: the resting composer blurs on a click into the timeline, so a paste that
12 * follows has no editable target and would be dropped. This sends it to the composer instead.
13 */
14export function usePasteToFocusComposer(
15 activeThreadId: ThreadId | null,
16 composerRef: ComposerHandleRef,
17) {
18 const pasteAsTextShortcutUntilRef = useRef(0);
19 useEffect(() => {
20 const keyHandler = (event: KeyboardEvent) => {
21 if (
22 shouldRedirectInputToComposer(event) &&
23 isPasteAsTextShortcut(event, isMacPlatform(navigator.platform))
24 ) {
25 pasteAsTextShortcutUntilRef.current = Date.now() + 1_000;
26 }
27 };
28 const handler = (event: ClipboardEvent) => {
29 if (!activeThreadId || isCommandPaletteOpen()) return;
30 if (getTerminalFocusOwner() !== null) return;
31 if (composerRef.current?.isModelPickerOpen()) return;
32 const text = pasteTextToFocusComposer(event);
33 const clipboardData = event.clipboardData;
34 if (text === null || clipboardData === null) return;
35 const bypassAutoAttachment = Date.now() <= pasteAsTextShortcutUntilRef.current;
36 pasteAsTextShortcutUntilRef.current = 0;
37 if (
38 ((readPastedComposerContext(clipboardData)?.records.length ?? 0) === 0 &&
39 composerRef.current?.pasteTextAtEnd(text, { bypassAutoAttachment })) ||
40 composerRef.current?.insertTextAtEnd(text, { clipboardData })
41 ) {
42 event.preventDefault();
43 event.stopPropagation();
44 }
45 };
46 window.addEventListener("keydown", keyHandler, true);
47 window.addEventListener("paste", handler, true);
48 return () => {
49 window.removeEventListener("keydown", keyHandler, true);
50 window.removeEventListener("paste", handler, true);
51 };
52 }, [activeThreadId, composerRef]);
53}