aboutsummaryrefslogtreecommitdiff
path: root/src/components/BackdropUpload.tsx
blob: 87fafb14c15c70f92c880f4bd84a1a494953c36e (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
import React, { useRef } from "react";
import { useStore } from "../store/store.ts";

export const BackdropUpload: React.FC = () => {
  const backdropUrl = useStore((state) => state.backdropUrl);
  const setBackdrop = useStore((state) => state.setBackdrop);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      if (backdropUrl) {
        URL.revokeObjectURL(backdropUrl);
      }
      const url = URL.createObjectURL(file);
      setBackdrop(url);
    }
  };

  const handleClear = () => {
    if (backdropUrl) {
      URL.revokeObjectURL(backdropUrl);
    }
    setBackdrop(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  const handleButtonClick = () => {
    fileInputRef.current?.click();
  };

  return (
    <div className="backdrop-upload">
      <input
        ref={fileInputRef}
        type="file"
        accept="image/png,image/jpeg,image/jpg,image/webp,image/gif"
        onChange={handleFileChange}
        style={{ display: "none" }}
      />
      <button className="upload-backdrop" onClick={handleButtonClick}>
        {backdropUrl ? "Change Backdrop" : "Upload Backdrop"}
      </button>
      {backdropUrl && (
        <button className="clear-backdrop" onClick={handleClear}>
          Clear
        </button>
      )}
    </div>
  );
};