| 1 | "use client"; |
| 2 | |
| 3 | import { useAuth } from |
| 4 | import { Upload } |
| 5 | import { type ChangeEvent, |
| 6 | import { toast } |
| 7 | |
| 8 | import { Button } |
| 9 | import { Card } |
| 10 | import { |
| 11 | Item, |
| 12 | ItemActions, |
| 13 | ItemContent, |
| 14 | ItemDescription, |
| 15 | ItemMedia, |
| 16 | } from "@/components/ui/item"; |
| 17 | import { Spinner } |
| 18 | import { ProfileAvatar } |
| 19 | import { deleteImage, putImage |
| 20 | |
| 21 | /** Upload or remove a picture an API path stores, such as an organization's logo. Uploads are resized to the same square as account avatars before they are sent. */ |
| 22 | export function ImageSetting({ |
| 23 | title, |
| 24 | hint, |
| 25 | name, |
| 26 | image, |
| 27 | path, |
| 28 | disabled, |
| 29 | onChanged, |
| 30 | }: { |
| 31 | title: string |
| 32 | hint: ReactNode |
| 33 | /** Initials drawn when there is no picture. */ |
| 34 | name: string |
| 35 | image: string |
| 36 | path: string |
| 37 | disabled?: boolean |
| 38 | onChanged: () |
| 39 | }) { |
| 40 | const { avatar |
| 41 | const fileInput = |
| 42 | const [busy, |
| 43 | |
| 44 | async function run |
| 45 | setBusy(true); |
| 46 | try { |
| 47 | await action(); |
| 48 | toast.success(done |
| 49 | await onChanged(); |
| 50 | } catch (error) |
| 51 | toast.error( |
| 52 | error instanceof Error |
| 53 | ); |
| 54 | } finally { |
| 55 | setBusy(false); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | async function upload |
| 60 | const file = |
| 61 | event.target.value |
| 62 | if (!file) |
| 63 | |
| 64 | const resized = |
| 65 | (await avatar.resize |
| 66 | await run(() |
| 67 | } |
| 68 | |
| 69 | return ( |
| 70 | <section> |
| 71 | <h2 className="mb-3 text-sm font-semibold |
| 72 | <Card className=" |
| 73 | <Item> |
| 74 | <ItemMedia> |
| 75 | <ProfileAvatar |
| 76 | name={name} |
| 77 | image={image} |
| 78 | className="size-16 rounded-xl" |
| 79 | fallbackClassName="text-lg" |
| 80 | /> |
| 81 | </ItemMedia> |
| 82 | <ItemContent> |
| 83 | <ItemDescription>{hint} |
| 84 | </ItemContent> |
| 85 | <ItemActions> |
| 86 | <input |
| 87 | ref={fileInput} |
| 88 | type="file" |
| 89 | accept="image/png,image/jpeg" |
| 90 | className="hidden" |
| 91 | onChange={upload} |
| 92 | /> |
| 93 | <Button |
| 94 | size="sm" |
| 95 | variant="outline" |
| 96 | disabled={disabled || |
| 97 | onClick={() => |
| 98 | > |
| 99 | {busy ? <Spinner |
| 100 | Upload |
| 101 | </Button> |
| 102 | {image && ( |
| 103 | <Button |
| 104 | size="sm" |
| 105 | variant="ghost" |
| 106 | disabled={busy} |
| 107 | onClick={() => |
| 108 | > |
| 109 | Remove |
| 110 | </Button> |
| 111 | )} |
| 112 | </ItemActions> |
| 113 | </Item> |
| 114 | </Card> |
| 115 | </section> |
| 116 | ); |
| 117 | } |