Ezmary commited on
Commit
3e36429
·
verified ·
1 Parent(s): cfee1d1

Update src/components/control-tray/ControlTray.tsx

Browse files
src/components/control-tray/ControlTray.tsx CHANGED
@@ -1,18 +1,13 @@
1
  // src/components/control-tray/ControlTray.tsx
2
- /**
3
- Copyright 2024 Google LLC
4
- ... (لایسنس) ...
5
- */
6
  import cn from "classnames";
7
- import React, { memo, ReactNode, RefObject, useEffect, useState, useCallback } from "react"; // useCallback اضافه شد
8
  import { useLiveAPIContext } from "../../contexts/LiveAPIContext";
9
  import { AudioRecorder } from "../../lib/audio-recorder";
10
  import LogoAnimation from '../logo-animation/LogoAnimation';
11
 
12
- const SvgPauseIcon = () => <svg width="37" height="37" viewBox="0 0 37 37" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M15.9872 29.6198V8.28342C15.9872 6.25781 15.132 5.44757 12.9713 5.44757H7.52469C5.36404 5.44757 4.50879 6.25781 4.50879 8.28342V29.6198C4.50879 31.6454 5.36404 32.4556 7.52469 32.4556H12.9713C15.132 32.4556 15.9872 31.6454 15.9872 29.6198Z" fill="#BE123C"/><path opacity="0.4" d="M31.5175 29.6198V8.28342C31.5175 6.25781 30.6622 5.44757 28.5016 5.44757H23.055C20.9093 5.44757 20.0391 6.25781 20.0391 8.28342V29.6198C20.0391 31.6454 20.8943 32.4556 23.055 32.4556H28.5016C30.6622 32.4556 31.5175 31.6454 31.5175 29.6198Z" fill="#BE123C"/></svg>;
13
- const SvgCameraIcon = () => <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg"><path opacity="0.4" d="M21.8118 5.52235H11.9265C6.29183 5.52235 4.10059 7.7136 4.10059 13.3482V26.5286C4.10059 30.318 6.16002 34.3545 11.9265 34.3545H21.8118C27.4464 34.3545 29.6376 32.1633 29.6376 26.5286V13.3482C29.6376 7.7136 27.4464 5.52235 21.8118 5.52235Z" fill="#2252A0"/><path d="M19.3406 18.9169C21.0512 18.9169 22.438 17.5302 22.438 15.8195C22.438 14.1089 21.0512 12.7222 19.3406 12.7222C17.6299 12.7222 16.2432 14.1089 16.2432 15.8195C16.2432 17.5302 17.6299 18.9169 19.3406 18.9169Z" fill="#2252A0"/><path d="M36.0629 10.3332C35.3874 9.98721 33.9705 9.5918 32.0429 10.9428L29.6045 12.6562C29.621 12.8869 29.6374 13.1011 29.6374 13.3482V26.5286C29.6374 26.7758 29.6045 26.9899 29.6045 27.2206L32.0429 28.934C33.0643 29.659 33.954 29.8896 34.6625 29.8896C35.2721 29.8896 35.7499 29.7249 36.0629 29.5601C36.7384 29.2141 37.8752 28.275 37.8752 25.919V13.9743C37.8752 11.6183 36.7384 10.6792 36.0629 10.3332Z" fill="#2252A0"/></svg>;
14
- const SvgStopCamIcon = () => <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg"><path opacity="0.4" d="M29.0785 10.8076L6.91966 32.9665C4.61316 31.5002 3.70703 28.8807 3.70703 26.36V13.18C3.70703 7.54555 5.89821 5.35437 11.5327 5.35437H21.4177C26.1789 5.35437 28.4854 6.9195 29.0785 10.8076Z" fill="#2252A0"/><path opacity="0.4" d="M29.2427 15.2394V26.36C29.2427 26.4918 29.2262 26.5907 29.2262 26.706C29.2262 26.8213 29.2097 26.9366 29.2097 27.052H29.2262C29.045 32.1757 26.8208 34.1856 21.417 34.1856H11.532C11.1202 34.1856 10.7412 34.1692 10.3623 34.1197L29.2427 15.2394Z" fill="#2252A0"/><path opacity="0.4" d="M29.21 27.052C29.21 26.9366 29.2264 26.8213 29.2264 26.706C29.2429 26.8213 29.2429 26.9366 29.2264 27.052H29.21Z" fill="#2252A0"/><path opacity="0.4" d="M29.2264 12.4716C29.2429 12.5869 29.2429 12.7187 29.2264 12.834C29.2264 12.7187 29.21 12.6034 29.21 12.488L29.2264 12.4716Z" fill="#2252A0"/><path d="M37.4804 13.8061V25.734C37.4804 28.0899 36.3436 29.029 35.6682 29.3749C35.3551 29.5397 34.8774 29.7209 34.2678 29.7209C33.5594 29.7209 32.6697 29.4903 31.6483 28.7654L29.2264 27.052H29.21C29.21 26.9366 29.2264 26.8213 29.2264 26.706C29.2264 26.5907 29.2429 26.4918 29.2429 26.36V15.2394L34.6302 9.85205C35.0751 9.885 35.421 10.0168 35.6682 10.1651C36.3436 10.5111 37.4804 11.4501 37.4804 13.8061Z" fill="#2252A0"/><path d="M35.8666 3.67393C35.3723 3.17968 34.565 3.17968 34.0708 3.67393L3.6744 34.0868C3.18015 34.581 3.18015 35.3883 3.6744 35.8826C3.92152 36.1132 4.23455 36.245 4.56405 36.245C4.89355 36.245 5.20657 36.1132 5.4537 35.8661L35.8666 5.45323C36.3773 4.95898 36.3773 4.16818 35.8666 3.67393Z" fill="#2252A0"/></svg>;
15
- const SvgSwitchCameraIcon = () => <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-[22px] h-[22px]"><path d="M11 19H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5"/><path d="M13 5h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-5"/><path d="m17 12-3-3 3-3"/><path d="m7 12 3 3-3 3"/></svg>;
16
 
17
  export type ControlTrayProps = {
18
  videoRef: RefObject<HTMLVideoElement>;
@@ -23,8 +18,8 @@ export type ControlTrayProps = {
23
  isAppCamActive: boolean;
24
  onAppCamToggle: (active: boolean) => void;
25
  ReferenceMicrophoneIcon: () => JSX.Element;
26
- currentFacingMode: 'user' | 'environment';
27
- setCurrentFacingMode: React.Dispatch<React.SetStateAction<'user' | 'environment'>>;
28
  };
29
 
30
  const ControlTray: React.FC<ControlTrayProps> = ({
@@ -36,174 +31,112 @@ const ControlTray: React.FC<ControlTrayProps> = ({
36
  isAppCamActive,
37
  onAppCamToggle,
38
  ReferenceMicrophoneIcon,
39
- currentFacingMode,
40
- setCurrentFacingMode,
41
  }) => {
42
- const { client, connected, connect, disconnect: liveApiDisconnect } = useLiveAPIContext(); // disconnect به liveApiDisconnect تغییر نام یافت
43
  const [audioRecorder] = useState(() => new AudioRecorder());
44
  const [activeLocalVideoStream, setActiveLocalVideoStream] = useState<MediaStream | null>(null);
 
 
45
  const [isSwitchingCamera, setIsSwitchingCamera] = useState(false);
46
  const renderCanvasRef = React.useRef<HTMLCanvasElement>(null);
47
 
48
- const ensureConnectedAndReady = useCallback(async (): Promise<boolean> => {
49
- if (!connected) {
50
- try {
51
- await connect();
52
- return true;
53
- } catch (err) {
54
- console.error('❌ CT Connect err:', err);
55
- return false;
56
- }
 
 
 
57
  }
58
- return true;
59
- }, [connected, connect]);
 
60
 
61
- const _startWebcam = useCallback(async (facingModeToTry: 'user' | 'environment'): Promise<MediaStream | null> => {
62
- // isSwitchingCamera در اینجا کنترل نمی‌شود، بلکه در توابع بالاتر
 
63
  try {
64
  const mediaStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: facingModeToTry }, audio: false });
65
  setActiveLocalVideoStream(mediaStream);
66
- onVideoStreamChange(mediaStream); // این باید srcObject ویدیو را در AppCore تنظیم کند
67
- return mediaStream;
 
68
  } catch (error) {
69
  console.error(`❌ Start WC err ${facingModeToTry}:`, error);
70
  setActiveLocalVideoStream(null);
71
  onVideoStreamChange(null);
72
- onAppCamToggle(false); // اطلاع به AppCore که دوربین خاموش شود
73
- return null;
74
- }
75
- }, [onVideoStreamChange, onAppCamToggle]); // وابستگی‌ها
76
-
77
- const _stopWebcam = useCallback(() => {
78
- if (activeLocalVideoStream) {
79
- activeLocalVideoStream.getTracks().forEach(track => track.stop());
80
- }
81
- setActiveLocalVideoStream(null);
82
- onVideoStreamChange(null);
83
- }, [activeLocalVideoStream, onVideoStreamChange]);
84
-
85
- useEffect(() => {
86
- if (isAppCamActive) {
87
- if (!activeLocalVideoStream && !isSwitchingCamera) {
88
- _startWebcam(currentFacingMode);
89
- }
90
- } else {
91
- if (activeLocalVideoStream) {
92
- _stopWebcam();
93
- }
94
- }
95
- }, [isAppCamActive, _startWebcam, _stopWebcam, activeLocalVideoStream, isSwitchingCamera, currentFacingMode]);
96
-
97
-
98
- useEffect(() => {
99
- const onData = (base64: string) => {
100
- if (client && connected && isAppMicActive) {
101
- client.sendRealtimeInput([{ mimeType: "audio/pcm;rate=16000", data: base64 }]);
102
- }
103
- };
104
- if (connected && isAppMicActive && audioRecorder) {
105
- audioRecorder.on("data", onData).start();
106
- } else if (audioRecorder && audioRecorder.recording) {
107
- audioRecorder.stop();
108
- }
109
- return () => {
110
- if (audioRecorder) {
111
- audioRecorder.off("data", onData);
112
- if (audioRecorder.recording) audioRecorder.stop();
113
- }
114
- };
115
- }, [connected, client, isAppMicActive, audioRecorder]);
116
-
117
- useEffect(() => {
118
- let timeoutId = -1;
119
- function sendVideoFrame() {
120
- if (connected && activeLocalVideoStream && client && videoRef.current) {
121
- // ... (م��طق ارسال فریم ویدیو بدون تغییر) ...
122
- }
123
- if (connected && activeLocalVideoStream) {
124
- timeoutId = window.setTimeout(sendVideoFrame, 1000 / 4); // 4 FPS
125
- }
126
- }
127
- if (connected && activeLocalVideoStream && videoRef.current) {
128
- timeoutId = window.setTimeout(sendVideoFrame, 200); // شروع با کمی تاخیر
129
  }
130
- return () => clearTimeout(timeoutId);
131
- }, [connected, activeLocalVideoStream, client, videoRef]);
132
-
133
- // useEffect برای قطع اتصال وقتی هیچکدام فعال نیستند (این منطق به AppCore منتقل شد)
134
- // useEffect(() => {
135
- // if (!isAppMicActive && !isAppCamActive && connected) {
136
- // liveApiDisconnect(); // استفاده از نام جدید
137
- // }
138
- // }, [isAppMicActive, isAppCamActive, connected, liveApiDisconnect]);
139
-
140
-
141
- const handleMicToggle = async () => {
142
- if (isSwitchingCamera) return;
143
- const newMicState = !isAppMicActive;
144
- if (newMicState) { // روشن کردن میکروفون
145
- if (!(await ensureConnectedAndReady())) {
146
- onAppMicToggle(false);
147
- return;
148
- }
149
- }
150
- onAppMicToggle(newMicState);
151
  };
152
 
153
- const handleCamToggle = async () => {
154
- if (isSwitchingCamera) return;
155
- const newCamState = !isAppCamActive;
156
-
157
- if (newCamState) { // روشن کردن دوربین
158
- if (!(await ensureConnectedAndReady())) {
159
- onAppCamToggle(false);
160
- return;
161
- }
162
- if (!isAppMicActive) { // اگر میکروفون خاموش است، آن را هم روشن کن
163
- onAppMicToggle(true);
164
- }
165
- onAppCamToggle(true); // این باعث می‌شود useEffect بالا _startWebcam را با currentFacingMode فعلی فراخوانی کند
166
- } else { // خاموش کردن دوربین
167
- onAppCamToggle(false); // این باعث می‌شود useEffect بالا _stopWebcam را فراخوانی کند
168
- }
169
- };
170
 
171
  const handleSwitchCamera = async () => {
172
  if (!isAppCamActive || !activeLocalVideoStream || isSwitchingCamera) return;
173
- setIsSwitchingCamera(true); // جلوگیری از فراخوانی‌های همزمان
174
-
175
  const targetFacingMode = currentFacingMode === 'user' ? 'environment' : 'user';
176
- _stopWebcam(); // توقف استریم فعلی
177
-
178
- await new Promise(resolve => setTimeout(resolve, 100)); // تاخیر کوچک
179
-
180
- const newStream = await _startWebcam(targetFacingMode);
181
- if (newStream) {
182
- setCurrentFacingMode(targetFacingMode); // آپدیت state در App.tsx
183
- } else {
184
- // اگر ناموفق بود، سعی در بازگرداندن به دوربین قبلی (currentFacingMode هنوز مقدار قبلی را دارد)
185
- await _startWebcam(currentFacingMode);
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  }
187
- setIsSwitchingCamera(false); // آزاد کردن قفل
188
  };
 
 
 
 
 
189
 
190
  return (
191
  <footer id="footer-controls" className="footer-controls-html-like">
 
192
  <canvas style={{ display: "none" }} ref={renderCanvasRef} />
193
- <div id="mic-button" className="control-button mic-button-color" onClick={handleMicToggle}>
 
194
  {isAppMicActive ? <SvgPauseIcon /> : <ReferenceMicrophoneIcon />}
195
  </div>
 
196
  {isAppCamActive && (
197
  <div id="small-logo-footer-container" className="small-logo-footer-html-like">
198
  <LogoAnimation isMini={true} isActive={true} type="human" forFooter={true} />
199
  </div>
200
  )}
 
201
  <div id="cam-button-wrapper" className="control-button-wrapper cam-wrapper-html-like">
202
- <div id="cam-button" className="control-button cam-button-color" onClick={handleCamToggle}>
203
  {isAppCamActive ? <SvgStopCamIcon /> : <SvgCameraIcon />}
204
  </div>
205
- <div id="switch-camera-button-container" className={cn("switch-camera-button-container", { visible: isAppCamActive && !isSwitchingCamera })}>
206
- <button id="switch-camera-button" aria-label="Switch Camera" className="switch-camera-button-content group" onClick={handleSwitchCamera} disabled={!isAppCamActive || isSwitchingCamera}>
207
  <SvgSwitchCameraIcon/>
208
  </button>
209
  </div>
 
1
  // src/components/control-tray/ControlTray.tsx
2
+
3
+ // ... (ایمپورت‌های اولیه و SVGهای دیگر مثل قبل) ...
 
 
4
  import cn from "classnames";
5
+ import React, { memo, ReactNode, RefObject, useEffect, useState } from "react";
6
  import { useLiveAPIContext } from "../../contexts/LiveAPIContext";
7
  import { AudioRecorder } from "../../lib/audio-recorder";
8
  import LogoAnimation from '../logo-animation/LogoAnimation';
9
 
10
+ // ... (SVG Icons: SvgPauseIcon, SvgCameraIcon, SvgStopCamIcon, SvgSwitchCameraIcon بدون تغییر) ...
 
 
 
11
 
12
  export type ControlTrayProps = {
13
  videoRef: RefObject<HTMLVideoElement>;
 
18
  isAppCamActive: boolean;
19
  onAppCamToggle: (active: boolean) => void;
20
  ReferenceMicrophoneIcon: () => JSX.Element;
21
+ initialFacingMode: 'user' | 'environment'; // *** NEW PROP ***
22
+ onFacingModeChange: (newMode: 'user' | 'environment') => void; // *** NEW PROP ***
23
  };
24
 
25
  const ControlTray: React.FC<ControlTrayProps> = ({
 
31
  isAppCamActive,
32
  onAppCamToggle,
33
  ReferenceMicrophoneIcon,
34
+ initialFacingMode, // *** NEW PROP ***
35
+ onFacingModeChange, // *** NEW PROP ***
36
  }) => {
37
+ const { client, connected, connect } = useLiveAPIContext();
38
  const [audioRecorder] = useState(() => new AudioRecorder());
39
  const [activeLocalVideoStream, setActiveLocalVideoStream] = useState<MediaStream | null>(null);
40
+ // *** currentFacingMode حالا از initialFacingMode مقدار اولیه می‌گیرد ***
41
+ const [currentFacingMode, setCurrentFacingMode] = useState<'user' | 'environment'>(initialFacingMode);
42
  const [isSwitchingCamera, setIsSwitchingCamera] = useState(false);
43
  const renderCanvasRef = React.useRef<HTMLCanvasElement>(null);
44
 
45
+ // وقتی initialFacingMode از بیرون تغییر می‌کند، state داخلی را هم آپدیت کن
46
+ useEffect(() => {
47
+ setCurrentFacingMode(initialFacingMode);
48
+ }, [initialFacingMode]);
49
+
50
+ // ... (useEffect های audioRecorder, sendVideoFrame, videoRef.srcObject بدون تغییر) ...
51
+ useEffect(() => {
52
+ if (isAppCamActive && !activeLocalVideoStream && !isSwitchingCamera) {
53
+ // هنگام شروع وب‌کم، از currentFacingMode داخلی استفاده کن
54
+ startWebcam(currentFacingMode);
55
+ } else if (!isAppCamActive && activeLocalVideoStream) {
56
+ stopWebcam();
57
  }
58
+ // eslint-disable-next-line react-hooks/exhaustive-deps
59
+ }, [isAppCamActive, activeLocalVideoStream, isSwitchingCamera]); // currentFacingMode را از وابستگی‌ها حذف می‌کنیم تا startWebcam فقط یکبار با مقدار اولیه اجرا شود و بعدا توسط handleSwitchCamera مدیریت شود.
60
+
61
 
62
+ const startWebcam = async (facingModeToTry: 'user' | 'environment' = currentFacingMode) => {
63
+ if (isSwitchingCamera) return;
64
+ setIsSwitchingCamera(true);
65
  try {
66
  const mediaStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: facingModeToTry }, audio: false });
67
  setActiveLocalVideoStream(mediaStream);
68
+ onVideoStreamChange(mediaStream);
69
+ setCurrentFacingMode(facingModeToTry); // آپدیت state داخلی
70
+ onFacingModeChange(facingModeToTry); // اطلاع به والد
71
  } catch (error) {
72
  console.error(`❌ Start WC err ${facingModeToTry}:`, error);
73
  setActiveLocalVideoStream(null);
74
  onVideoStreamChange(null);
75
+ onAppCamToggle(false); // اگر وب‌کم شروع نشد، دکمه دوربین را خاموش کن
76
+ } finally {
77
+ setIsSwitchingCamera(false);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  };
80
 
81
+ // ... (stopWebcam, ensureConnectedAndReady, handleMicToggle, handleCamToggle بدون تغییر عمده) ...
82
+ // فقط handleCamToggle ممکن است نیاز به استفاده از currentFacingMode داشته باشد اگر اولین بار دوربین را با جهت خاصی می‌خواهید روشن کنید
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  const handleSwitchCamera = async () => {
85
  if (!isAppCamActive || !activeLocalVideoStream || isSwitchingCamera) return;
86
+ setIsSwitchingCamera(true);
 
87
  const targetFacingMode = currentFacingMode === 'user' ? 'environment' : 'user';
88
+ activeLocalVideoStream.getTracks().forEach(track => track.stop());
89
+ try {
90
+ const newStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { exact: targetFacingMode } }, audio: false });
91
+ setActiveLocalVideoStream(newStream);
92
+ onVideoStreamChange(newStream);
93
+ setCurrentFacingMode(targetFacingMode); // آپدیت state داخلی
94
+ onFacingModeChange(targetFacingMode); // اطلاع به والد
95
+ } catch (error) {
96
+ console.error(`❌ Switch Cam err ${targetFacingMode}:`, error);
97
+ // سعی در بازگرداندن به دوربین قبلی
98
+ try {
99
+ const restoredStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: currentFacingMode }, audio: false }); // استفاده از currentFacingMode قبلی
100
+ setActiveLocalVideoStream(restoredStream);
101
+ onVideoStreamChange(restoredStream);
102
+ // onFacingModeChange(currentFacingMode); // نیازی نیست چون به حالت قبلی برگشتیم
103
+ } catch (restoreError) {
104
+ console.error('❌ Restore Cam err:', restoreError);
105
+ setActiveLocalVideoStream(null);
106
+ onVideoStreamChange(null);
107
+ onAppCamToggle(false);
108
+ }
109
+ } finally {
110
+ setIsSwitchingCamera(false);
111
  }
 
112
  };
113
+ // ... (بقیه useEffect ها و توابع handle مثل قبل)
114
+ const ensureConnectedAndReady = async (): Promise<boolean> => { /* ... */ return false; };
115
+ const handleMicToggle = async () => { /* ... */ };
116
+ const handleCamToggle = async () => { /* ... */ };
117
+
118
 
119
  return (
120
  <footer id="footer-controls" className="footer-controls-html-like">
121
+ {/* ... (JSX فوتر مثل قبل) ... */}
122
  <canvas style={{ display: "none" }} ref={renderCanvasRef} />
123
+
124
+ <div id="mic-button" className="control-button mic-button-color" onClick={handleMicToggle} >
125
  {isAppMicActive ? <SvgPauseIcon /> : <ReferenceMicrophoneIcon />}
126
  </div>
127
+
128
  {isAppCamActive && (
129
  <div id="small-logo-footer-container" className="small-logo-footer-html-like">
130
  <LogoAnimation isMini={true} isActive={true} type="human" forFooter={true} />
131
  </div>
132
  )}
133
+
134
  <div id="cam-button-wrapper" className="control-button-wrapper cam-wrapper-html-like">
135
+ <div id="cam-button" className="control-button cam-button-color" onClick={handleCamToggle} >
136
  {isAppCamActive ? <SvgStopCamIcon /> : <SvgCameraIcon />}
137
  </div>
138
+ <div id="switch-camera-button-container" className={cn("switch-camera-button-container", { visible: isAppCamActive && !isSwitchingCamera })} >
139
+ <button id="switch-camera-button" aria-label="Switch Camera" className="switch-camera-button-content group" onClick={handleSwitchCamera} disabled={!isAppCamActive || isSwitchingCamera} >
140
  <SvgSwitchCameraIcon/>
141
  </button>
142
  </div>