Spaces:
Running
Running
Download src/hooks/useCaptureResponder.ts from evalstate/mcp-webcam: direct link, hf CLI and curl.
- Browser
- Download file 2.24 kB
-
https://huggingface.co/spaces/evalstate/mcp-webcam/resolve/main/src/hooks/useCaptureResponder.ts
- Command line
-
hf download hf://spaces/evalstate/mcp-webcam/src/hooks/useCaptureResponder.ts
-
curl -L -o useCaptureResponder.ts https://huggingface.co/spaces/evalstate/mcp-webcam/resolve/main/src/hooks/useCaptureResponder.ts
2.24 kB
| import { useCallback, useEffect, useRef, useState } from 'react'; | |
| import { postCaptureResult } from '@/lib/api'; | |
| import type { CaptureCommand } from '@/lib/feed'; | |
| import type { CapturedFrame } from './useCamera'; | |
| import { captureScreen } from '@/utils/screenCapture'; | |
| export interface ActiveCaptureNotice { | |
| requestId: string; | |
| kind: 'webcam' | 'screen'; | |
| reason: string; | |
| at: number; | |
| } | |
| export function useCaptureResponder(opts: { | |
| user: string; | |
| mockMode: boolean; | |
| grabFrame: () => CapturedFrame | null; | |
| }) { | |
| const { user, mockMode, grabFrame } = opts; | |
| const [shutterCount, setShutterCount] = useState(0); | |
| const [activeNotice, setActiveNotice] = useState<ActiveCaptureNotice | null>(null); | |
| const noticeTimerRef = useRef<number | null>(null); | |
| useEffect(() => { | |
| return () => { | |
| if (noticeTimerRef.current !== null) { | |
| window.clearTimeout(noticeTimerRef.current); | |
| } | |
| }; | |
| }, []); | |
| const triggerNotice = useCallback((cmd: CaptureCommand) => { | |
| setShutterCount((c) => c + 1); | |
| setActiveNotice({ | |
| requestId: cmd.requestId, | |
| kind: cmd.kind, | |
| reason: cmd.reason, | |
| at: Date.now(), | |
| }); | |
| if (noticeTimerRef.current !== null) { | |
| window.clearTimeout(noticeTimerRef.current); | |
| } | |
| noticeTimerRef.current = window.setTimeout(() => { | |
| setActiveNotice(null); | |
| }, 3500); | |
| }, []); | |
| const handleCaptureCommand = useCallback( | |
| async (cmd: CaptureCommand) => { | |
| triggerNotice(cmd); | |
| if (mockMode) return; | |
| try { | |
| let image: string | undefined; | |
| if (cmd.kind === 'screen') { | |
| image = await captureScreen(); | |
| } else { | |
| const frame = grabFrame(); | |
| if (!frame) { | |
| throw new Error('Camera is not ready to capture a frame.'); | |
| } | |
| image = frame.dataUrl; | |
| } | |
| await postCaptureResult(cmd.requestId, user, { image }); | |
| } catch (err) { | |
| const message = err instanceof Error ? err.message : 'Capture failed'; | |
| await postCaptureResult(cmd.requestId, user, { error: message }).catch(() => {}); | |
| } | |
| }, | |
| [grabFrame, mockMode, triggerNotice, user], | |
| ); | |
| return { | |
| shutterCount, | |
| activeNotice, | |
| handleCaptureCommand, | |
| }; | |
| } | |