File size: 11,368 Bytes
d5c6d34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import { useState, useEffect, useCallback, useMemo } from "react";
import Button from "./Button";
import { THEME } from "../constants";

const ERROR_TYPES = {
  HTTPS: "https",
  NOT_SUPPORTED: "not-supported",
  PERMISSION: "permission",
  GENERAL: "general",
} as const;

const VIDEO_CONSTRAINTS = {
  video: {
    width: { ideal: 1920, max: 1920 },
    height: { ideal: 1080, max: 1080 },
    facingMode: "user",
  },
};

interface ErrorInfo {
  type: (typeof ERROR_TYPES)[keyof typeof ERROR_TYPES];
  message: string;
}

interface WebcamPermissionDialogProps {
  onPermissionGranted: (stream: MediaStream) => void;
}

export default function WebcamPermissionDialog({
  onPermissionGranted,
}: WebcamPermissionDialogProps) {
  const [isRequesting, setIsRequesting] = useState(false);
  const [error, setError] = useState<ErrorInfo | null>(null);

  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);

  const getErrorInfo = (err: unknown): ErrorInfo => {
    if (!navigator.mediaDevices) {
      return {
        type: ERROR_TYPES.HTTPS,
        message: "Camera access requires a secure connection (HTTPS)",
      };
    }

    if (!navigator.mediaDevices.getUserMedia) {
      return {
        type: ERROR_TYPES.NOT_SUPPORTED,
        message: "Camera access not supported in this browser",
      };
    }

    if (err instanceof DOMException) {
      switch (err.name) {
        case "NotAllowedError":
          return {
            type: ERROR_TYPES.PERMISSION,
            message: "Camera access denied",
          };
        case "NotFoundError":
          return {
            type: ERROR_TYPES.GENERAL,
            message: "No camera found",
          };
        case "NotReadableError":
          return {
            type: ERROR_TYPES.GENERAL,
            message: "Camera is in use by another application",
          };
        case "OverconstrainedError":
          return {
            type: ERROR_TYPES.GENERAL,
            message: "Camera doesn't meet requirements",
          };
        case "SecurityError":
          return {
            type: ERROR_TYPES.HTTPS,
            message: "Security error accessing camera",
          };
        default:
          return {
            type: ERROR_TYPES.GENERAL,
            message: `Camera error: ${err.name}`,
          };
      }
    }

    return {
      type: ERROR_TYPES.GENERAL,
      message: "Failed to access camera",
    };
  };

  const requestWebcamAccess = useCallback(async () => {
    setIsRequesting(true);
    setError(null);

    try {
      if (!navigator.mediaDevices?.getUserMedia) {
        throw new Error("NOT_SUPPORTED");
      }

      const stream =
        await navigator.mediaDevices.getUserMedia(VIDEO_CONSTRAINTS);
      onPermissionGranted(stream);
    } catch (err) {
      const errorInfo = getErrorInfo(err);
      setError(errorInfo);
      console.error("Error accessing webcam:", err, errorInfo);
    } finally {
      setIsRequesting(false);
    }
  }, [onPermissionGranted]);

  useEffect(() => {
    requestWebcamAccess();
  }, [requestWebcamAccess]);

  const troubleshootingData = useMemo(
    () => ({
      [ERROR_TYPES.HTTPS]: {
        title: "HTTPS Required",
        items: [
          "Access this app via https:// instead of http://",
          "If developing locally, use localhost",
          "Deploy to a secure hosting service (Hugging Face spaces)",
        ],
      },
      [ERROR_TYPES.NOT_SUPPORTED]: {
        title: "Browser Compatibility",
        items: [
          "Update your browser to the latest version",
          "Try Chrome, Edge, or Firefox",
          "Enable JavaScript if disabled",
        ],
      },
      [ERROR_TYPES.PERMISSION]: {
        title: "Permission Issues",
        items: [
          "Click the camera icon in your address bar",
          'Select "Always allow" for camera access',
          "Check System Preferences → Security & Privacy",
          "Refresh the page after changing settings",
        ],
      },
      [ERROR_TYPES.GENERAL]: {
        title: "General Troubleshooting",
        items: [
          "Ensure no other apps (Zoom, Teams) are using the camera",
          "Try unplugging and replugging your webcam",
          "Try using a different browser",
        ],
      },
    }),
    [],
  );

  const getTroubleshootingContent = () => {
    if (!error) return null;
    const content = troubleshootingData[error.type];

    return (
      <div
        className="bg-white border p-5 mt-6"
        style={{ borderColor: THEME.beigeDark }}
      >
        <h4 className="text-sm font-bold uppercase tracking-wider text-gray-500 mb-3 flex items-center gap-2">
          <span
            className="w-2 h-2 rounded-full"
            style={{ backgroundColor: THEME.mistralOrange }}
          ></span>
          Troubleshooting
        </h4>
        <div className="space-y-2">
          <p className="font-semibold" style={{ color: THEME.textBlack }}>
            {content.title}
          </p>
          <ul className="space-y-2">
            {content.items.map((item, index) => (
              <li
                key={index}
                className="text-sm text-gray-600 flex items-start"
              >
                <span
                  className="mr-2 font-mono"
                  style={{ color: THEME.beigeDark }}
                >
                  /
                </span>{" "}
                {item}
              </li>
            ))}
          </ul>
        </div>

        {/* Technical Details Footer */}
        <div className="mt-4 pt-4 border-t border-gray-100 flex flex-col gap-1">
          <p className="text-xs text-gray-400 font-mono uppercase">
            Diagnostics
          </p>
          <div className="bg-gray-50 p-2 rounded text-xs font-mono text-gray-600 break-all border border-gray-100">
            LOC: {window.location.protocol}//{window.location.host}
            <br />
            ERR: {error.type.toUpperCase()}
          </div>
        </div>
      </div>
    );
  };

  const getTitle = () => {
    if (isRequesting) return "Initialize Camera";
    if (error) return "Connection Failed";
    return "Permission Required";
  };

  const getDescription = () => {
    if (isRequesting) return "Requesting access to video input device...";
    if (error) return error.message;
    return "Ministral WebGPU requires local camera access for real-time inference.";
  };

  return (
    <>
      <div
        className="fixed inset-0 flex items-center justify-center p-4 z-50"
        style={{
          backgroundColor: THEME.beigeLight,
          backgroundImage: `
            linear-gradient(${THEME.beigeDark} 1px, transparent 1px), 
            linear-gradient(90deg, ${THEME.beigeDark} 1px, transparent 1px)
          `,
          backgroundSize: "40px 40px",
        }}
        role="dialog"
        aria-labelledby="webcam-dialog-title"
      >
        <div
          className={`max-w-lg w-full backdrop-blur-sm border shadow-2xl transition-all duration-700 ${mounted ? "opacity-100 translate-y-0" : "opacity-0 translate-y-4"}`}
          style={{
            backgroundColor: `${THEME.beigeLight}F2`,
            borderColor: THEME.beigeDark,
          }}
        >
          {/* Header Bar */}
          <div
            className="h-1 w-full"
            style={{ backgroundColor: THEME.mistralOrange }}
          ></div>

          <div className="p-8 md:p-10">
            {/* Icon Area */}
            <div className="flex justify-center mb-8">
              {isRequesting ? (
                <div className="relative">
                  <div
                    className="absolute inset-0 blur-lg opacity-20 rounded-full animate-pulse"
                    style={{ backgroundColor: THEME.mistralOrange }}
                  ></div>
                  <div
                    className="w-16 h-16 border-4 rounded-full animate-spin"
                    style={{
                      borderColor: THEME.beigeDark,
                      borderTopColor: THEME.mistralOrange,
                    }}
                  ></div>
                </div>
              ) : (
                <div
                  className={`w-16 h-16 flex items-center justify-center border-2`}
                  style={{
                    borderColor: error ? THEME.errorRed : THEME.mistralOrange,
                    backgroundColor: error
                      ? `${THEME.errorRed}0D`
                      : `${THEME.mistralOrange}1A`,
                  }}
                >
                  {error ? (
                    <svg
                      className="w-8 h-8"
                      style={{ color: THEME.errorRed }}
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                      strokeWidth={2}
                    >
                      <path
                        strokeLinecap="square"
                        strokeLinejoin="miter"
                        d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
                      />
                    </svg>
                  ) : (
                    <svg
                      className="w-8 h-8"
                      style={{ color: THEME.mistralOrange }}
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                      strokeWidth={1.5}
                    >
                      <path
                        strokeLinecap="square"
                        strokeLinejoin="miter"
                        d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"
                      />
                    </svg>
                  )}
                </div>
              )}
            </div>

            {/* Text Content */}
            <div className="text-center space-y-4 mb-8">
              <h2
                id="webcam-dialog-title"
                className="text-2xl font-bold tracking-tight"
                style={{ color: THEME.textBlack }}
              >
                {getTitle()}
              </h2>
              <p className="text-gray-600 leading-relaxed font-light text-lg">
                {getDescription()}
              </p>
            </div>

            {/* Error Actions */}
            {error && (
              <div className="animate-enter">
                <div className="flex justify-center mb-6">
                  <Button
                    onClick={requestWebcamAccess}
                    disabled={isRequesting}
                    className="px-8 py-3 text-white shadow-lg hover:shadow-xl transition-all font-semibold tracking-wide hover:bg-[var(--mistral-orange-dark)]"
                  >
                    Try Again
                  </Button>
                </div>

                {getTroubleshootingContent()}
              </div>
            )}

            {/* Loading State Helper */}
            {isRequesting && (
              <p className="text-center text-sm text-gray-400 font-mono animate-pulse">
                Waiting for browser permission...
              </p>
            )}
          </div>
        </div>
      </div>
    </>
  );
}