2022-10-09 08:33:43 +03:00
|
|
|
import React, { FC, useEffect, useRef, useState } from 'react';
|
2022-05-27 04:59:16 +03:00
|
|
|
import { createPicker } from 'picmo';
|
2022-05-06 00:43:40 +03:00
|
|
|
|
2022-05-27 04:59:16 +03:00
|
|
|
const CUSTOM_EMOJI_URL = '/api/emoji';
|
2022-10-09 08:33:43 +03:00
|
|
|
export type EmojiPickerProps = {
|
2022-05-12 09:31:31 +03:00
|
|
|
onEmojiSelect: (emoji: string) => void;
|
2022-10-09 08:33:43 +03:00
|
|
|
onCustomEmojiSelect: (name: string, url: string) => void;
|
|
|
|
};
|
2022-05-12 09:31:31 +03:00
|
|
|
|
2022-10-09 08:33:43 +03:00
|
|
|
export const EmojiPicker: FC<EmojiPickerProps> = ({ onEmojiSelect, onCustomEmojiSelect }) => {
|
2022-05-27 04:59:16 +03:00
|
|
|
const [customEmoji, setCustomEmoji] = useState([]);
|
2022-05-06 00:43:40 +03:00
|
|
|
const ref = useRef();
|
|
|
|
|
2022-05-27 04:59:16 +03:00
|
|
|
const getCustomEmoji = async () => {
|
|
|
|
try {
|
|
|
|
const response = await fetch(CUSTOM_EMOJI_URL);
|
|
|
|
const emoji = await response.json();
|
|
|
|
setCustomEmoji(emoji);
|
|
|
|
} catch (e) {
|
|
|
|
console.error('cannot fetch custom emoji', e);
|
|
|
|
}
|
|
|
|
};
|
2022-05-06 00:43:40 +03:00
|
|
|
|
2022-05-27 04:59:16 +03:00
|
|
|
// Fetch the custom emoji on component mount.
|
|
|
|
useEffect(() => {
|
|
|
|
getCustomEmoji();
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
// Recreate the emoji picker when the custom emoji changes.
|
|
|
|
useEffect(() => {
|
2022-09-07 03:52:02 +03:00
|
|
|
const e = customEmoji.map(emoji => ({
|
|
|
|
emoji: emoji.name,
|
|
|
|
label: emoji.name,
|
|
|
|
url: emoji.url,
|
|
|
|
}));
|
|
|
|
|
|
|
|
const picker = createPicker({
|
|
|
|
rootElement: ref.current,
|
|
|
|
custom: e,
|
|
|
|
initialCategory: 'custom',
|
|
|
|
showPreview: false,
|
|
|
|
showRecents: true,
|
|
|
|
});
|
2022-05-27 04:59:16 +03:00
|
|
|
picker.addEventListener('emoji:select', event => {
|
2022-09-07 03:52:02 +03:00
|
|
|
if (event.url) {
|
2023-06-26 21:37:34 +03:00
|
|
|
onCustomEmojiSelect(event.label, event.url);
|
2022-09-07 03:52:02 +03:00
|
|
|
} else {
|
2022-10-09 08:33:43 +03:00
|
|
|
onEmojiSelect(event.emoji);
|
2022-09-07 03:52:02 +03:00
|
|
|
}
|
2022-05-27 04:59:16 +03:00
|
|
|
});
|
|
|
|
}, [customEmoji]);
|
2022-05-06 00:43:40 +03:00
|
|
|
|
2022-05-09 23:44:11 +03:00
|
|
|
return <div ref={ref} />;
|
2022-09-07 10:00:28 +03:00
|
|
|
};
|