summaryrefslogtreecommitdiff
path: root/app/lib/camera/component/sjCamera.tsx
blob: 73062e27c6b876e266cec0271b16b5d32697643b (plain)
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
import React, { useRef } from "react";
import useCameraStore from "../hooks/useCameraStore";
import { IconButton } from "@mui/material";
import { PendingActions } from "@mui/icons-material";

const SjCamera: React.FC = () => {
  const { setImageSj } = useCameraStore();
  const fileRef = useRef<HTMLInputElement | null>(null);

  const readFilesAsDataURL = (files: FileList | null): Promise<string[]> =>
    new Promise((resolve) => {
      if (!files || files.length === 0) return resolve([]);
      const list = Array.from(files);
      const out: string[] = [];
      let done = 0;
      list.forEach((f) => {
        const fr = new FileReader();
        fr.onload = (e) => {
          const dataUrl = (e.target?.result as string) || "";
          if (dataUrl) out.push(dataUrl);
          done += 1;
          if (done === list.length) resolve(out);
        };
        fr.onerror = () => {
          done += 1;
          if (done === list.length) resolve(out);
        };
        fr.readAsDataURL(f);
      });
    });

  const handleSuratJalanCapture = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const imgs = await readFilesAsDataURL(event.target.files);
    if (imgs.length > 0) {
      // APPEND: panggil setImageSj untuk tiap foto
      imgs.forEach((img) => setImageSj(img));
    }
    // reset supaya bisa pilih file yang sama lagi
    if (fileRef.current) fileRef.current.value = "";
  };

  return (
    <div className="p-4 py-8 items-center border-2 rounded-md shadow-sm w-[49%] text-center">
      <input
        ref={fileRef}
        id="suratJalanInput"
        type="file"
        accept="image/*"
        multiple
        className="hidden"
        onChange={handleSuratJalanCapture}
      />
      <label
        htmlFor="suratJalanInput"
        className="text-gray-600 cursor-pointer select-none"
      >
        <IconButton
          color="primary"
          aria-label="upload picture"
          component="span"
        >
          <PendingActions fontSize="large" />
        </IconButton>
        <br />
        Foto Surat Jalan
      </label>
    </div>
  );
};

export default SjCamera;