| 1 | import { useEffect, useRef } from "react"; |
| 2 | |
| 3 | import { |
| 4 | checkClipboardForImage, |
| 5 | getClipboardImage, |
| 6 | } from "../../util/clipboard.js"; |
| 7 | import { logger } from "../../util/logger.js"; |
| 8 | |
| 9 | interface UseClipboardMonitorOptions { |
| 10 | onImageStatusChange?: (hasImage: boolean) => void; |
| 11 | enabled?: boolean; |
| 12 | pollInterval?: number; |
| 13 | } |
| 14 | |
| 15 | /** |
| 16 | * Hook to monitor clipboard for images and notify when status changes |
| 17 | * Shows helpful UI messages when images are available for pasting |
| 18 | */ |
| 19 | export function useClipboardMonitor({ |
| 20 | onImageStatusChange, |
| 21 | enabled = true, |
| 22 | pollInterval = 1000, // Check every second |
| 23 | }: UseClipboardMonitorOptions) { |
| 24 | const lastImageStatus = useRef<boolean>(false); |
| 25 | const isChecking = useRef<boolean>(false); |
| 26 | |
| 27 | useEffect(() => { |
| 28 | if (!enabled) { |
| 29 | return; |
| 30 | } |
| 31 | |
| 32 | const checkClipboard = async () => { |
| 33 | // Prevent overlapping checks |
| 34 | if (isChecking.current) { |
| 35 | return; |
| 36 | } |
| 37 | |
| 38 | isChecking.current = true; |
| 39 | |
| 40 | try { |
| 41 | const hasImage = await checkClipboardForImage(); |
| 42 | |
| 43 | // Only notify if status changed |
| 44 | if (hasImage !== lastImageStatus.current) { |
| 45 | lastImageStatus.current = hasImage; |
| 46 | if (onImageStatusChange) { |
| 47 | onImageStatusChange(hasImage); |
| 48 | } |
| 49 | logger.debug( |
| 50 | hasImage ? "Image detected in clipboard" : "No image in clipboard", |
| 51 | ); |
| 52 | } |
| 53 | } catch (error) { |
| 54 | logger.debug("Error checking clipboard:", error); |
| 55 | } finally { |
| 56 | isChecking.current = false; |
| 57 | } |
| 58 | }; |
| 59 | |
| 60 | // Start monitoring |
| 61 | const intervalId: NodeJS.Timeout = setInterval( |
| 62 | checkClipboard, |
| 63 | pollInterval, |
| 64 | ); |
| 65 | |
| 66 | // Initial check |
| 67 | checkClipboard(); |
| 68 | |
| 69 | // Cleanup |
| 70 | return () => { |
| 71 | clearInterval(intervalId); |
| 72 | }; |
| 73 | }, [enabled, onImageStatusChange, pollInterval]); |
| 74 | |
| 75 | // Manual check function for explicit paste operations |
| 76 | const checkNow = async (): Promise<Buffer | null> => { |
| 77 | if (!enabled || isChecking.current) { |
| 78 | return null; |
| 79 | } |
| 80 | |
| 81 | isChecking.current = true; |
| 82 | |
| 83 | try { |
| 84 | const hasImage = await checkClipboardForImage(); |
| 85 | |
| 86 | if (hasImage) { |
| 87 | const imageBuffer = await getClipboardImage(); |
| 88 | return imageBuffer; |
| 89 | } |
| 90 | } catch (error) { |
| 91 | logger.debug("Error in manual clipboard check:", error); |
| 92 | } finally { |
| 93 | isChecking.current = false; |
| 94 | } |
| 95 | |
| 96 | return null; |
| 97 | }; |
| 98 | |
| 99 | return { checkNow }; |
| 100 | } |