signal-desktop/ts/components/AvatarIconEditor.tsx

85 lines
2.1 KiB
TypeScript
Raw Normal View History

2021-08-06 00:17:05 +00:00
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import React, { useCallback, useEffect, useState } from 'react';
import { AvatarColorPicker } from './AvatarColorPicker';
import type { AvatarColorType } from '../types/Colors';
import type { AvatarDataType } from '../types/Avatar';
2021-08-06 00:17:05 +00:00
import { AvatarModalButtons } from './AvatarModalButtons';
import { AvatarPreview } from './AvatarPreview';
import type { LocalizerType } from '../types/Util';
2021-09-24 00:49:05 +00:00
import { avatarDataToBytes } from '../util/avatarDataToBytes';
2021-08-06 00:17:05 +00:00
export type PropsType = {
avatarData: AvatarDataType;
i18n: LocalizerType;
onClose: (avatarData?: AvatarDataType) => unknown;
};
2022-11-18 00:45:19 +00:00
export function AvatarIconEditor({
2021-08-06 00:17:05 +00:00
avatarData: initialAvatarData,
i18n,
onClose,
2022-11-18 00:45:19 +00:00
}: PropsType): JSX.Element {
2021-09-24 00:49:05 +00:00
const [avatarBuffer, setAvatarBuffer] = useState<Uint8Array | undefined>();
2021-11-11 22:43:05 +00:00
const [avatarData, setAvatarData] =
useState<AvatarDataType>(initialAvatarData);
2021-08-06 00:17:05 +00:00
const onColorSelected = useCallback(
(color: AvatarColorType) => {
setAvatarData({
...avatarData,
color,
});
},
[avatarData]
);
useEffect(() => {
let shouldCancel = false;
async function loadAvatar() {
2021-09-24 00:49:05 +00:00
const buffer = await avatarDataToBytes(avatarData);
2021-08-06 00:17:05 +00:00
if (!shouldCancel) {
setAvatarBuffer(buffer);
}
}
void loadAvatar();
2021-08-06 00:17:05 +00:00
return () => {
shouldCancel = true;
};
}, [avatarData, setAvatarBuffer]);
const hasChanges = avatarData !== initialAvatarData;
return (
<>
<AvatarPreview
avatarColor={avatarData.color}
avatarValue={avatarBuffer}
conversationTitle={avatarData.text}
i18n={i18n}
/>
<hr className="AvatarEditor__divider" />
2021-08-06 21:35:25 +00:00
<AvatarColorPicker
i18n={i18n}
onColorSelected={onColorSelected}
selectedColor={avatarData.color}
/>
2021-08-06 00:17:05 +00:00
<AvatarModalButtons
hasChanges={hasChanges}
i18n={i18n}
onCancel={onClose}
onSave={() =>
onClose({
...avatarData,
buffer: avatarBuffer,
})
}
/>
</>
);
2022-11-18 00:45:19 +00:00
}