import { ImagePlus, Loader2, Upload, X } from "lucide-react"; import { useEffect, useState } from "react"; import { createPortal } from "react-dom"; import { api, errorMessage } from "../api"; import { Alert } from "./ui"; type AvatarModalKind = "user" | "channel"; // AvatarModal uploads a new photo for an account or a channel/supergroup. It // follows CreateStickerSetModal's shape (a single reason field + direct // execute, rather than ActionButton's JSON dry-run/confirm flow) since the // payload is a multipart file upload, not a plain JSON body. export function AvatarModal({ kind, id, onClose, onDone }: { kind: AvatarModalKind; id: number; onClose: () => void; onDone: () => void }) { const [file, setFile] = useState(null); const [previewURL, setPreviewURL] = useState(""); const [videoStartTs, setVideoStartTs] = useState("0"); const [reason, setReason] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); const isVideo = kind === "user" && !!file && file.type.startsWith("video/"); useEffect(() => { if (!file) { setPreviewURL(""); return; } const url = URL.createObjectURL(file); setPreviewURL(url); return () => URL.revokeObjectURL(url); }, [file]); async function submit() { if (!file) { setError("Choose an image or video file first."); return; } if (!reason.trim()) { setError("Please enter an operation reason"); return; } setBusy(true); setError(""); try { const idField = kind === "channel" ? "channel_id" : "user_id"; const form = new FormData(); const metadata: Record = { command_id: "", reason: reason.trim(), confirm: true, [idField]: id }; if (isVideo) { metadata.video_start_ts = Number(videoStartTs) || 0; } form.set("metadata", JSON.stringify(metadata)); form.set("file", file, file.name); const result = kind === "channel" ? await api.setChannelAvatar(form) : isVideo ? await api.setAccountAvatarVideo(form) : await api.setAccountAvatar(form); if (result.error) { setError(result.error); return; } onDone(); onClose(); } catch (err) { setError(errorMessage(err)); } finally { setBusy(false); } } const noun = kind === "channel" ? "Channel" : "Account"; return createPortal(
{noun}

{"Change avatar"}

{isVideo && ( )} {error && {error}}
, document.body ); }