|
| 1 | +import { FileTrigger, type FileTriggerProps, InputContext } from "react-aria-components"; |
| 2 | +import { Avatar } from "./Avatar"; |
| 3 | +import { Button } from "./Button"; |
| 4 | +import { useMemo, useState } from "react"; |
| 5 | + |
| 6 | +type AvatarImageFieldProps = { |
| 7 | + name: string; |
| 8 | + label?: string; |
| 9 | + placeholder: string; |
| 10 | + avatarUrl?: string; |
| 11 | + initials: string; |
| 12 | + isRound?: boolean; |
| 13 | +} & Omit<FileTriggerProps, "onSelect">; |
| 14 | + |
| 15 | +export function AvatarImageField({ |
| 16 | + name, |
| 17 | + label, |
| 18 | + placeholder = "Upload an image", |
| 19 | + avatarUrl, |
| 20 | + initials, |
| 21 | + isRound = true, |
| 22 | + acceptedFileTypes = ["image/png"], |
| 23 | + ...props |
| 24 | +}: Readonly<AvatarImageFieldProps>) { |
| 25 | + const [previewUrl, setPreviewUrl] = useState<string | null>(null); |
| 26 | + const [filename, setFilename] = useState<string | null>(null); |
| 27 | + const inputContext = useMemo(() => ({ name: filename ? name : undefined }), [filename, name]); |
| 28 | + |
| 29 | + return ( |
| 30 | + <div className="flex flex-col gap-3"> |
| 31 | + {label && <label>{label}</label>} |
| 32 | + <InputContext.Provider value={inputContext}> |
| 33 | + <div className="flex flex-row gap-4 items-center"> |
| 34 | + <FileTrigger |
| 35 | + {...props} |
| 36 | + acceptedFileTypes={acceptedFileTypes} |
| 37 | + onSelect={(e) => { |
| 38 | + if (e) { |
| 39 | + const files = Array.from(e); |
| 40 | + const file = files[0]; |
| 41 | + setFilename(file.name); |
| 42 | + setPreviewUrl(URL.createObjectURL(file)); |
| 43 | + } |
| 44 | + }} |
| 45 | + > |
| 46 | + <Button variant="icon" className={isRound ? "rounded-full" : "rounded-md"}> |
| 47 | + <Avatar avatarUrl={previewUrl ?? avatarUrl} initials={initials} isRound={isRound} size="md" /> |
| 48 | + </Button> |
| 49 | + </FileTrigger> |
| 50 | + {filename ?? placeholder ?? ""} |
| 51 | + </div> |
| 52 | + </InputContext.Provider> |
| 53 | + </div> |
| 54 | + ); |
| 55 | +} |
0 commit comments