"use client"; import { useCallback, useEffect, useRef, useState, type ChangeEvent, type RefObject, } from "react"; import { fetchAuthSession } from "../../../../lib/create/api"; import { COMMUNITY_AVATAR_ACCEPT, messageKeyForCreateFlowUploadReason, validateCreateFlowUploadFile, } from "../../../../lib/create/createFlowUploadValidation"; import { clearPendingCommunityAvatarFile, storePendingCommunityAvatarFile, } from "../../../../lib/create/pendingCommunityAvatarUpload"; import { createFlowUploadFailureMessageKey, uploadCreateFlowFile, } from "../../../../lib/create/uploadToServer"; import { useMessages, useTranslation } from "../../../contexts/MessagesContext"; import { useCreateFlow } from "../context/CreateFlowContext"; function hasCommunityAvatarUrl(url: string | undefined): boolean { return typeof url === "string" && url.trim().length > 0; } /** * Pick and store a community logo for the create flow. Signed-in users upload * immediately; guests keep the file in IndexedDB until they sign in. * * @example * const avatar = useCommunityAvatarUpload(); * */ export function useCommunityAvatarUpload(): { fileInputRef: RefObject; accept: string; busy: boolean; errorMessage: string | null; displaySrc: string | null; fileName: string | undefined; handlePickFile: () => void; handleFileChange: (_event: ChangeEvent) => Promise; } { const m = useMessages(); const u = m.create.community.communityUpload; const tUpload = useTranslation("create.upload"); const { markCreateFlowInteraction, state, updateState } = useCreateFlow(); const fileInputRef = useRef(null); const [signedIn, setSignedIn] = useState(null); const [localPreviewUrl, setLocalPreviewUrl] = useState(null); const [localFileName, setLocalFileName] = useState(null); const [busy, setBusy] = useState(false); const [errorMessage, setErrorMessage] = useState(null); useEffect(() => { let cancelled = false; void fetchAuthSession().then(({ user }) => { if (!cancelled) setSignedIn(Boolean(user)); }); return () => { cancelled = true; }; }, []); useEffect( () => () => { if (localPreviewUrl) URL.revokeObjectURL(localPreviewUrl); }, [localPreviewUrl], ); const serverAvatarUrl = hasCommunityAvatarUrl(state.communityAvatarUrl) ? state.communityAvatarUrl!.trim() : null; useEffect(() => { if (serverAvatarUrl) { setLocalPreviewUrl((prev) => { if (prev) URL.revokeObjectURL(prev); return null; }); } }, [serverAvatarUrl]); const resolveUploadError = useCallback( (err: unknown) => { const key = createFlowUploadFailureMessageKey(err); if (key === "errors.tooLarge") return u.fileTooLarge; return tUpload(key); }, [tUpload, u.fileTooLarge], ); const handleFileChange = useCallback( async (e: ChangeEvent) => { const file = e.target.files?.[0]; e.target.value = ""; if (!file) return; markCreateFlowInteraction(); setErrorMessage(null); if (signedIn === true) { setBusy(true); try { const { url } = await uploadCreateFlowFile(file, "communityAvatar"); setLocalPreviewUrl((prev) => { if (prev) URL.revokeObjectURL(prev); return null; }); setLocalFileName(file.name); updateState({ communityAvatarUrl: url, communityAvatarFileName: file.name, }); } catch (err) { setErrorMessage(resolveUploadError(err)); } finally { setBusy(false); } return; } const validated = await validateCreateFlowUploadFile( file, "communityAvatar", ); if (validated.ok === false) { setErrorMessage( validated.reason === "tooLarge" ? u.fileTooLarge : tUpload(messageKeyForCreateFlowUploadReason(validated.reason)), ); return; } try { await storePendingCommunityAvatarFile(file); setLocalPreviewUrl((prev) => { if (prev) URL.revokeObjectURL(prev); return URL.createObjectURL(file); }); setLocalFileName(file.name); updateState({ communityAvatarFileName: file.name }); } catch { await clearPendingCommunityAvatarFile().catch(() => undefined); setErrorMessage(tUpload("errors.generic")); } }, [ markCreateFlowInteraction, resolveUploadError, signedIn, tUpload, u.fileTooLarge, updateState, ], ); const handlePickFile = useCallback(() => { if (!busy) fileInputRef.current?.click(); }, [busy]); const displaySrc = serverAvatarUrl ?? localPreviewUrl; const fileName = localFileName ?? (typeof state.communityAvatarFileName === "string" && state.communityAvatarFileName.trim().length > 0 ? state.communityAvatarFileName.trim() : undefined); return { fileInputRef, accept: COMMUNITY_AVATAR_ACCEPT, busy, errorMessage, displaySrc, fileName, handlePickFile, handleFileChange, }; }