File size: 5,960 Bytes
1f6c75f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useRef, useState, useCallback, useEffect } from "react";
import { Camera, CameraOff, Aperture, X } from "lucide-react";

export default function CameraPanel({ onCapture, previewUrl, onReset }) {
  const videoRef = useRef(null);
  const canvasRef = useRef(null);
  const streamRef = useRef(null);
  const [isCameraOn, setIsCameraOn] = useState(false);
  const [cameraError, setCameraError] = useState("");
  const [isVideoReady, setIsVideoReady] = useState(false);

  // Cleanup saat unmount
  useEffect(() => {
    return () => {
      stopCamera();
    };
  }, []);

  // Assign stream ke video element setelah state berubah dan element ter-render
  useEffect(() => {
    if (isCameraOn && videoRef.current && streamRef.current) {
      const video = videoRef.current;
      video.srcObject = streamRef.current;

      video.onloadedmetadata = () => {
        video.play()
          .then(() => setIsVideoReady(true))
          .catch((err) => console.error("Video play error:", err));
      };
    }
  }, [isCameraOn]);

  async function startCamera() {
    setCameraError("");
    setIsVideoReady(false);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: {
          facingMode: "environment",
          width: { ideal: 1280 },
          height: { ideal: 720 },
        },
      });
      streamRef.current = stream;

      // Set state dulu agar video element di-render,
      // lalu useEffect di atas akan assign stream
      setIsCameraOn(true);
    } catch (err) {
      console.error("Camera error:", err);
      if (err.name === "NotAllowedError") {
        setCameraError("Izin kamera ditolak. Aktifkan izin kamera pada browser.");
      } else if (err.name === "NotFoundError") {
        setCameraError("Kamera tidak ditemukan pada perangkat ini.");
      } else {
        setCameraError("Gagal mengaktifkan kamera. Coba lagi.");
      }
    }
  }

  function stopCamera() {
    if (streamRef.current) {
      streamRef.current.getTracks().forEach((track) => track.stop());
      streamRef.current = null;
    }
    if (videoRef.current) {
      videoRef.current.srcObject = null;
    }
    setIsCameraOn(false);
    setIsVideoReady(false);
  }

  const captureImage = useCallback(() => {
    if (!videoRef.current || !canvasRef.current) return;

    const video = videoRef.current;
    const canvas = canvasRef.current;

    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    const ctx = canvas.getContext("2d");
    ctx.drawImage(video, 0, 0);

    canvas.toBlob(
      (blob) => {
        if (blob) {
          const file = new File([blob], `capture_${Date.now()}.jpg`, {
            type: "image/jpeg",
          });
          onCapture(file);
          stopCamera();
        }
      },
      "image/jpeg",
      0.9
    );
  }, [onCapture]);

  return (
    <div className="space-y-4">
      {cameraError && (
        <div className="bg-red-50 border border-red-200 rounded-lg px-4 py-3 text-sm text-red-700">
          {cameraError}
        </div>
      )}

      {previewUrl ? (
        <div className="relative">
          <img
            src={previewUrl}
            alt="Captured"
            className="w-full rounded-xl border border-slate-200 object-contain max-h-72"
          />
          <button
            onClick={() => {
              onReset();
            }}
            className="absolute top-2 right-2 bg-red-500 hover:bg-red-600 text-white rounded-full p-1.5 shadow-md transition-colors cursor-pointer"
          >
            <X className="w-4 h-4" />
          </button>
        </div>
      ) : isCameraOn ? (
        <div className="relative rounded-xl overflow-hidden border border-slate-200 bg-slate-900">
          {/* Loading indicator sebelum video ready */}
          {!isVideoReady && (
            <div className="absolute inset-0 flex items-center justify-center z-10">
              <div className="text-center">
                <div className="w-8 h-8 border-3 border-white border-t-transparent rounded-full animate-spin mx-auto mb-2"></div>
                <p className="text-xs text-white/70">Memuat kamera...</p>
              </div>
            </div>
          )}

          <video
            ref={videoRef}
            autoPlay
            playsInline
            muted
            className="w-full object-cover"
            style={{ minHeight: "280px", maxHeight: "400px" }}
          />

          {isVideoReady && (
            <div className="absolute bottom-3 left-0 right-0 flex justify-center gap-3">
              <button
                onClick={captureImage}
                className="bg-white hover:bg-slate-100 text-slate-800 rounded-full p-3 shadow-lg transition-colors cursor-pointer"
                title="Ambil Gambar"
              >
                <Aperture className="w-6 h-6" />
              </button>
              <button
                onClick={stopCamera}
                className="bg-red-500 hover:bg-red-600 text-white rounded-full p-3 shadow-lg transition-colors cursor-pointer"
                title="Matikan Kamera"
              >
                <CameraOff className="w-6 h-6" />
              </button>
            </div>
          )}
        </div>
      ) : (
        <div className="border-2 border-dashed border-slate-300 rounded-xl p-8 md:p-12 text-center">
          <Camera className="w-10 h-10 text-slate-400 mx-auto mb-3" />
          <p className="text-sm text-slate-600 mb-4">
            Gunakan kamera untuk mengambil gambar kendaraan
          </p>
          <button
            onClick={startCamera}
            className="inline-flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium px-5 py-2.5 rounded-lg transition-colors cursor-pointer"
          >
            <Camera className="w-4 h-4" />
            Aktifkan Kamera
          </button>
        </div>
      )}

      <canvas ref={canvasRef} className="hidden" />
    </div>
  );
}