diff --git a/packages/hooks/src/useMediaDevices/index.page.jsx b/packages/hooks/src/useMediaDevices/index.page.jsx index 0db27d7..e92943d 100644 --- a/packages/hooks/src/useMediaDevices/index.page.jsx +++ b/packages/hooks/src/useMediaDevices/index.page.jsx @@ -21,7 +21,7 @@ export function Camera() { return (
-
diff --git a/packages/hooks/src/useScreenCapture/index.ts b/packages/hooks/src/useScreenCapture/index.ts index 5f5cc59..be1b1a6 100644 --- a/packages/hooks/src/useScreenCapture/index.ts +++ b/packages/hooks/src/useScreenCapture/index.ts @@ -1,39 +1,34 @@ -import { useCallback, useRef, useState } from 'react'; +import { useCallback, useState } from 'react'; /** * @see {@link https://malkiii.github.io/react-pre-hooks/docs/hooks/useScreenCapture | useScreenCapture} hook. */ export const useScreenCapture = (options: DisplayMediaStreamOptions = {}) => { - const streamRef = useRef(); - const [isEnabled, setIsEnabled] = useState(false); + const [stream, setStream] = useState(null); + const [isPending, setIsPending] = useState(false); const startStreaming = useCallback(async () => { - streamRef.current?.getTracks().forEach(t => t.stop()); + setIsPending(true); + stream?.getTracks().forEach(t => t.stop()); try { - streamRef.current = await navigator.mediaDevices.getDisplayMedia(options); - const videoTrack = streamRef.current.getVideoTracks().at(0); - if (videoTrack) videoTrack.onended = () => setIsEnabled(false); + const newStream = await navigator.mediaDevices.getDisplayMedia(options); + const videoTrack = newStream.getVideoTracks()[0]; + if (videoTrack) videoTrack.onended = () => setStream(null); - setIsEnabled(true); - } catch (error) { - setIsEnabled(false); - throw error; + setStream(newStream); + setIsPending(false); + + return newStream; + } finally { + setIsPending(false); } - }, []); + }, [stream]); const stopStreaming = useCallback(() => { - streamRef.current?.getTracks().forEach(t => t.stop()); - setIsEnabled(false); - }, []); - - const toggle = useCallback( - async (force?: boolean) => { - const shouldStart = force ?? !isEnabled; - shouldStart ? await startStreaming() : stopStreaming(); - }, - [isEnabled] - ); + stream?.getTracks().forEach(t => t.stop()); + setStream(null); + }, [stream]); - return { streamRef, start: startStreaming, stop: stopStreaming, toggle, isEnabled }; + return { stream, start: startStreaming, stop: stopStreaming, isPending }; };