|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { useRouter } from "next/navigation"; |
| 4 | +import { useRef } from "react"; |
| 5 | + |
| 6 | +import { useImageUploadContext } from "@/app/story/register/_contexts"; |
| 7 | +import { imageFileSchema } from "@/app/story/register/_schemas"; |
| 8 | + |
| 9 | +export const Story = () => { |
| 10 | + const router = useRouter(); |
| 11 | + const { setUpload } = useImageUploadContext(); |
| 12 | + const fileInputRef = useRef<HTMLInputElement | null>(null); |
| 13 | + |
| 14 | + const handleOpenPhotoGallery = () => { |
| 15 | + fileInputRef.current?.click(); |
| 16 | + }; |
| 17 | + |
| 18 | + const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => { |
| 19 | + const file = e.target.files?.[0]; |
| 20 | + if (!file) return; |
| 21 | + |
| 22 | + const validationResult = imageFileSchema.safeParse(file); |
| 23 | + |
| 24 | + if (!validationResult.success) { |
| 25 | + const errorMessage = validationResult.error.errors[0]?.message; |
| 26 | + // TODO: Toast 변경 |
| 27 | + alert(errorMessage || "올바르지 않은 파일입니다."); |
| 28 | + |
| 29 | + if (fileInputRef.current) { |
| 30 | + fileInputRef.current.value = ""; |
| 31 | + } |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + const previewUrl = URL.createObjectURL(file); |
| 36 | + setUpload(file, previewUrl); |
| 37 | + |
| 38 | + router.push("/story/register"); |
| 39 | + }; |
| 40 | + return ( |
| 41 | + <> |
| 42 | + <button onClick={handleOpenPhotoGallery}>스토리 사진 선택</button> |
| 43 | + <input |
| 44 | + ref={fileInputRef} |
| 45 | + type='file' |
| 46 | + accept='image/jpeg,image/jpg,image/png' |
| 47 | + onChange={handleFileChange} |
| 48 | + hidden |
| 49 | + /> |
| 50 | + </> |
| 51 | + ); |
| 52 | +}; |
0 commit comments