Spaces:
Running
Running
/** | |
Copyright 2024 Google LLC | |
(لایسنس مثل قبل) | |
*/ | |
import React, { createContext, FC, type ReactNode, useContext, useEffect, useState, useCallback } from "react"; // useState, useCallback added | |
import { useLiveAPI, type UseLiveAPIResults as OriginalUseLiveAPIResults } from "../hooks/use-live-api"; | |
import { LiveConfig } from "../multimodal-live-types"; | |
// Extend UseLiveAPIResults to include new functions | |
export type UseLiveAPIResults = OriginalUseLiveAPIResults & { | |
currentFacingMode?: 'user' | 'environment' | null; | |
setCurrentFacingMode?: React.Dispatch<React.SetStateAction<'user' | 'environment' | null>>; | |
rotateWebcam?: () => Promise<void>; | |
changeStreams?: (streamType: 'webcam' | 'screen' | 'none') => void; | |
// Allow updating the live config from ControlTray (or other components) | |
updateLiveConfig?: (updates: Partial<UseLiveAPIResults>) => void; | |
}; | |
const LiveAPIContext = createContext<UseLiveAPIResults | undefined>(undefined); | |
export type LiveAPIProviderProps = { | |
children: ReactNode; | |
url?: string; | |
initialConfig?: LiveConfig; | |
}; | |
export const LiveAPIProvider: FC<LiveAPIProviderProps> = ({ | |
url = process.env.NODE_ENV === 'development' | |
? `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//localhost:3001/ws` | |
: `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}/ws`, | |
initialConfig, | |
children, | |
}) => { | |
const liveAPIOriginal = useLiveAPI({ url }); | |
// State and functions to be managed by context for wider use | |
const [currentFacingMode, setCurrentFacingMode] = useState<'user' | 'environment' | null>(null); | |
const [dynamicConfig, setDynamicConfig] = useState<Partial<UseLiveAPIResults>>({}); | |
const updateLiveConfig = useCallback((updates: Partial<UseLiveAPIResults>) => { | |
setDynamicConfig(prev => ({ ...prev, ...updates })); | |
}, []); | |
useEffect(() => { | |
if (initialConfig && liveAPIOriginal.setConfig) { | |
console.log("Applying initial config from Provider:", initialConfig); | |
liveAPIOriginal.setConfig(initialConfig); | |
} | |
}, [initialConfig, liveAPIOriginal.setConfig]); | |
const contextValue: UseLiveAPIResults = { | |
...liveAPIOriginal, | |
currentFacingMode, | |
setCurrentFacingMode, | |
updateLiveConfig, | |
// Spread dynamic functions if they are provided by a component like ControlTray | |
...(dynamicConfig.rotateWebcam && { rotateWebcam: dynamicConfig.rotateWebcam }), | |
...(dynamicConfig.changeStreams && { changeStreams: dynamicConfig.changeStreams }), | |
}; | |
return ( | |
<LiveAPIContext.Provider value={contextValue}> | |
{children} | |
</LiveAPIContext.Provider> | |
); | |
}; | |
export const useLiveAPIContext = () => { | |
const context = useContext(LiveAPIContext); | |
if (!context) { | |
throw new Error("useLiveAPIContext must be used within a LiveAPIProvider"); | |
} | |
return context; | |
}; |