(props: SelfInfoProps)
| 25 | } |
| 26 | |
| 27 | function SelfInfo(props: SelfInfoProps) { |
| 28 | const { visible, onClose } = props; |
| 29 | |
| 30 | const action = useAction(); |
| 31 | const userId = useSelector((state: State) => state.user?._id); |
| 32 | const avatar = useSelector((state: State) => state.user?.avatar); |
| 33 | const primaryColor = useSelector( |
| 34 | (state: State) => state.status.primaryColor, |
| 35 | ); |
| 36 | const [loading, toggleLoading] = useState(false); |
| 37 | const [cropper, setCropper] = useState({ |
| 38 | enable: false, |
| 39 | src: '', |
| 40 | ext: '', |
| 41 | }); |
| 42 | const $cropper = useRef(null); |
| 43 | |
| 44 | async function uploadAvatar(blob: Blob, ext = 'png') { |
| 45 | toggleLoading(true); |
| 46 | |
| 47 | try { |
| 48 | const avatarUrl = await uploadFile( |
| 49 | blob, |
| 50 | `Avatar/${userId}_${Date.now()}.${ext}`, |
| 51 | ); |
| 52 | const isSuccess = await changeAvatar(avatarUrl); |
| 53 | if (isSuccess) { |
| 54 | action.setAvatar(URL.createObjectURL(blob)); |
| 55 | Message.success('修改头像成功'); |
| 56 | } |
| 57 | } catch (err) { |
| 58 | console.error(err); |
| 59 | Message.error('上传头像失败'); |
| 60 | } finally { |
| 61 | toggleLoading(false); |
| 62 | setCropper({ enable: false, src: '', ext: '' }); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | async function selectAvatar() { |
| 67 | const file = await readDiskFile( |
| 68 | 'blob', |
| 69 | 'image/png,image/jpeg,image/gif', |
| 70 | ); |
| 71 | if (!file) { |
| 72 | return; |
| 73 | } |
| 74 | if (file.length > config.maxAvatarSize) { |
| 75 | // eslint-disable-next-line consistent-return |
| 76 | return Message.error('设置头像失败, 请选择小于1.5MB的图片'); |
| 77 | } |
| 78 | |
| 79 | // gif头像不需要裁剪 |
| 80 | if (file.ext === 'gif') { |
| 81 | uploadAvatar(file.result as Blob, file.ext); |
| 82 | } else { |
| 83 | // 显示头像裁剪 |
| 84 | const reader = new FileReader(); |
nothing calls this directly
no test coverage detected