import { Show, createSignal } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { formatApiError } from "@/api/client"; import { getLimits } from "@/api/limits"; import { deleteMyAvatar, postMyAvatar } from "@/api/users"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { IconEdit, IconTrash, IconUploadCloud } from "@/components/ui/icons"; import { UserAvatar } from "@/components/users/user-avatar"; import { AVATAR_ACCEPT, AVATAR_CONTENT_TYPES, bumpAvatarRevision, formatBytes } from "@/lib/avatar"; import { useT } from "@/stores/preferences-context"; export function AvatarUpload(props: { userId: string; name: string; hasAvatar: boolean; /** Re-read the profile so `avatar` reflects what was just written. */ onChanged: () => void | Promise; }) { const t = useT(); const [limits] = createResource(() => getLimits()); const [busy, setBusy] = createSignal(false); const [error, setError] = createSignal(""); const [removeOpen, setRemoveOpen] = createSignal(false); let input: HTMLInputElement | undefined; const maxBytes = () => limits.latest?.file.default_max_file_bytes ?? 5 * 1024 * 1024; const pick = async (file: File) => { setError(""); if (!AVATAR_CONTENT_TYPES.includes(file.type)) { setError(t("avatar.typeInvalid")); return; } if (file.size > maxBytes()) { setError(t("avatar.tooLarge", { size: formatBytes(maxBytes()) })); return; } setBusy(true); try { await postMyAvatar(file); bumpAvatarRevision(); await props.onChanged(); } catch (err) { setError(formatApiError(err)); } finally { setBusy(false); } }; const remove = async () => { setError(""); setBusy(true); try { await deleteMyAvatar(); bumpAvatarRevision(); await props.onChanged(); } catch (err) { setError(formatApiError(err)); } finally { setBusy(false); } }; return (
{/* The photo controls hang off the avatar itself rather than sitting beside it as a row of buttons, so the header reads as a person, not as a form. */}
input?.click()}> {props.hasAvatar ? t("avatar.change") : t("avatar.upload")} setRemoveOpen(true)}> {t("avatar.remove")}

{t("avatar.hint", { size: formatBytes(maxBytes()) })}

{error()}

{ const file = e.currentTarget.files?.[0]; // Clear it before awaiting, so picking the same file twice in a row // still fires a change event. e.currentTarget.value = ""; if (file) void pick(file); }} />
); }