-
Notifications
You must be signed in to change notification settings - Fork 84
/
EmojiPicker.tsx
433 lines (401 loc) · 13.2 KB
/
EmojiPicker.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import { useTheme } from "@emotion/react";
import styled from "@emotion/styled";
import {
AddReaction,
AutoAwesome,
Edit,
EmojiEmotions,
RemoveCircleOutline,
} from "@mui/icons-material";
import {
Alert,
Avatar,
Badge,
Box,
Button,
CircularProgress,
Dialog,
DialogActions,
DialogContent,
Tooltip,
} from "@mui/material";
import { Emoji, EmojiClickData, EmojiStyle, SuggestionMode, Theme } from "emoji-picker-react";
import {
CSSProperties,
Dispatch,
SetStateAction,
Suspense,
lazy,
useContext,
useEffect,
useState,
} from "react";
import { UserContext } from "../contexts/UserContext";
import { useOnlineStatus } from "../hooks/useOnlineStatus";
import { DialogBtn, fadeIn } from "../styles";
import { ColorPalette } from "../theme/themeConfig";
import { getFontColor, showToast, systemInfo } from "../utils";
import { CATEGORY_NAME_MAX_LENGTH, TASK_NAME_MAX_LENGTH } from "../constants";
import { AITextSession } from "../types/ai";
import { CustomDialogTitle } from "./DialogTitle";
const EmojiPicker = lazy(() => import("emoji-picker-react"));
interface EmojiPickerProps {
emoji?: string;
setEmoji: Dispatch<SetStateAction<string | null>>;
color?: string;
name?: string;
type?: "task" | "category";
}
export const CustomEmojiPicker = ({ emoji, setEmoji, color, name, type }: EmojiPickerProps) => {
const { user, setUser } = useContext(UserContext);
const { emojisStyle, settings } = user;
const [showEmojiPicker, setShowEmojiPicker] = useState<boolean>(false);
const [currentEmoji, setCurrentEmoji] = useState<string | null>(emoji || null);
const isOnline = useOnlineStatus();
const emotionTheme = useTheme();
interface EmojiItem {
unified: string;
original: string;
count: number;
}
const getFrequentlyUsedEmojis = (): string[] => {
const frequentlyUsedEmojis: EmojiItem[] | null = JSON.parse(
localStorage.getItem("epr_suggested") || "null",
);
if (!frequentlyUsedEmojis) {
return [];
}
frequentlyUsedEmojis.sort((a, b) => b.count - a.count);
const topEmojis: EmojiItem[] = frequentlyUsedEmojis.slice(0, 6);
const topUnified: string[] = topEmojis.map((item) => item.unified);
return topUnified;
};
// When the currentEmoji state changes, update the parent component's emoji state
useEffect(() => {
setEmoji(currentEmoji);
}, [currentEmoji, setEmoji]);
// When the emoji prop changes to an empty string, set the currentEmoji state to undefined
useEffect(() => {
if (emoji === "") {
setCurrentEmoji(null);
}
}, [emoji]);
// Function to toggle the visibility of the EmojiPicker
const toggleEmojiPicker = () => {
setShowEmojiPicker((prevState) => !prevState);
};
// Handler function for when an emoji is clicked in the EmojiPicker
const handleEmojiClick = (e: EmojiClickData) => {
toggleEmojiPicker();
setCurrentEmoji(e.unified);
console.log(e);
};
const handleRemoveEmoji = () => {
toggleEmojiPicker();
setCurrentEmoji(null);
};
const [isAILoading, setIsAILoading] = useState<boolean>(false);
const [session, setSession] = useState<AITextSession | null>(null);
// Create Session on component mount for faster first load
useEffect(() => {
const createSession = async () => {
if (window.ai) {
const session = await window.ai.createTextSession();
setSession(session);
}
};
createSession();
}, []);
// ‼ This feature works only in Chrome (Dev / Canary) version 127 or higher with some flags enabled
// https://afficone.com/blog/window-ai-new-chrome-feature-api/
async function useAI(): Promise<void> {
const start = new Date().getTime();
setIsAILoading(true);
try {
const sessionInstance: AITextSession = session || (await window.ai.createTextSession());
const response = await sessionInstance.prompt(
`Choose a single emoji that best represents the ${
type || "task"
}: ${name}. (For example: 🖥️ for coding, 📝 for writing, 🎨 for design, 📱 for mobile development) Please use the actual emoji, do not use shortcodes. Type 'none' if not applicable.`,
);
console.log("Full AI response:", response);
// Map to replace emoji shortcodes with actual emojis due to AI occasionally returning shortcodes.
const emojiMap: {
[key: string]: string;
} = {
":joy:": "😄",
":smile:": "😄",
":heart:": "❤️",
"<3": "❤️",
":sunglasses:": "😎",
":thinking_head:": "🤔",
":technology:": "💻",
":tech:": "💻",
":ml:": "🧠",
":wave:": "👋",
":O": "😮",
"☮": "✌️",
"🎙": "🎙️",
"🗣": "🗣️",
"✈": "✈️",
};
let emojiResponse = response.trim();
if (emojiMap[emojiResponse]) {
emojiResponse = emojiMap[emojiResponse];
}
// Validate if userInput is a valid emoji
const emojiRegex = /[\p{Emoji}]/u;
const unified = emojiToUnified(emojiResponse.replaceAll(":", ""));
if (emojiRegex.test(emojiResponse)) {
setIsAILoading(false);
console.log("Emoji unified:", unified);
setCurrentEmoji(unified);
} else {
setCurrentEmoji(null);
showToast(`Invalid emoji. Please try again with different ${type} name.`, {
type: "error",
});
console.error("Invalid emoji.", unified);
}
} catch (error) {
setIsAILoading(false);
console.error(error);
showToast(`${error}`, { type: "error" });
} finally {
setIsAILoading(false);
const end = new Date().getTime();
console.log(
`%cTook ${end - start}ms to generate.`,
`color: ${end - start > 600 ? "orange" : "lime"}`,
);
}
}
const emojiToUnified = (emoji: string): string =>
[...emoji]
.map((char) => (char ? (char.codePointAt(0)?.toString(16).toUpperCase() ?? "") : ""))
.join("-")
.toLowerCase();
// end of AI experimental feature code
// Function to render the content of the Avatar based on whether an emoji is selected or not
const renderAvatarContent = () => {
const fontColor = color ? getFontColor(color) : ColorPalette.fontLight;
if (isAILoading) {
return <CircularProgress size={40} thickness={5} sx={{ color: fontColor }} />;
}
if (currentEmoji) {
const emojiSize =
emojisStyle === EmojiStyle.NATIVE && systemInfo.os === "iOS"
? 64
: emojisStyle === EmojiStyle.NATIVE
? 48
: 64;
return (
<EmojiElement key={currentEmoji}>
<Emoji size={emojiSize} emojiStyle={emojisStyle} unified={currentEmoji} />
</EmojiElement>
);
} else {
return (
<AddReaction
sx={{
fontSize: "52px",
color: fontColor,
transition: ".3s all",
}}
/>
);
}
};
return (
<>
<EmojiContainer>
<Badge
overlap="circular"
anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
badgeContent={
<EditBadge onClick={toggleEmojiPicker}>
<Edit />
</EditBadge>
}
>
<EmojiAvatar clr={color} onClick={toggleEmojiPicker}>
{renderAvatarContent()}
</EmojiAvatar>
</Badge>
</EmojiContainer>
{"ai" in window && name !== undefined && (
<Tooltip title={!name ? `Enter a name for the ${type} to find emoji` : undefined}>
<div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
<Button
onClick={useAI}
disabled={
name?.length < 3 ||
(type === "task"
? name.length > TASK_NAME_MAX_LENGTH
: name.length > CATEGORY_NAME_MAX_LENGTH)
}
style={{ marginBottom: "4px" }}
>
<AutoAwesome /> Find emoji with AI
</Button>
</div>
</Tooltip>
)}
{/* Simple Emoji Picker */}
{showEmojiPicker && settings.simpleEmojiPicker && (
<SimplePickerContainer>
<Suspense fallback={<CircularProgress size={40} thickness={5} />}>
<EmojiPicker
style={{ border: "none" }}
reactionsDefaultOpen
lazyLoadEmojis
reactions={getFrequentlyUsedEmojis()}
emojiStyle={emojisStyle}
onReactionClick={handleEmojiClick}
allowExpandReactions={false}
theme={emotionTheme.darkmode ? Theme.DARK : Theme.LIGHT}
autoFocusSearch={false}
/>
</Suspense>
</SimplePickerContainer>
)}
{showEmojiPicker && !settings.simpleEmojiPicker && (
<>
<Dialog
open={showEmojiPicker}
onClose={toggleEmojiPicker}
PaperProps={{
style: {
padding: "12px",
borderRadius: "24px",
minWidth: "400px",
},
}}
>
<CustomDialogTitle
title="Choose Emoji"
subTitle={`Choose the perfect emoji for your ${type}.`}
onClose={toggleEmojiPicker}
icon={<AddReaction />}
/>
<DialogContent sx={{ p: 0, m: 0 }}>
{!isOnline && emojisStyle !== EmojiStyle.NATIVE && (
<Box sx={{ mx: "14px", mb: "16px" }}>
<Alert severity="warning">
Emojis may not load correctly when offline. Try switching to the native emoji
style.
</Alert>
<Button
variant="outlined"
color="warning"
fullWidth
sx={{ mt: "14px" }}
onClick={() => {
setUser((prevUser) => ({
...prevUser,
emojisStyle: EmojiStyle.NATIVE,
}));
// setShowEmojiPicker(false);
}}
>
<EmojiEmotions /> Switch to Native Emoji
</Button>
</Box>
)}
<EmojiPickerContainer>
<Suspense
fallback={
!settings.simpleEmojiPicker && (
<PickerLoader
pickerTheme={emotionTheme.darkmode ? "dark" : "light"}
></PickerLoader>
)
}
>
<EmojiPicker
width="100vw"
height="550px"
reactionsDefaultOpen={
settings.simpleEmojiPicker && getFrequentlyUsedEmojis().length !== 0
}
reactions={getFrequentlyUsedEmojis()}
emojiStyle={emojisStyle}
theme={emotionTheme.darkmode ? Theme.DARK : Theme.LIGHT}
suggestedEmojisMode={SuggestionMode.FREQUENT}
autoFocusSearch={false}
onEmojiClick={handleEmojiClick}
searchPlaceHolder="Search emoji"
previewConfig={{
defaultEmoji: "1f4dd",
defaultCaption: `Choose the perfect emoji for your ${type}`,
}}
/>
</Suspense>
</EmojiPickerContainer>
</DialogContent>
<DialogActions>
{currentEmoji && (
<DialogBtn color="error" onClick={handleRemoveEmoji}>
<RemoveCircleOutline /> Remove Emoji
</DialogBtn>
)}
<DialogBtn onClick={toggleEmojiPicker}>Cancel</DialogBtn>
</DialogActions>
</Dialog>
</>
)}
</>
);
};
const EmojiContainer = styled.div`
display: flex;
justify-content: center;
align-items: center;
margin: 14px;
`;
const EmojiPickerContainer = styled(DialogContent)`
display: flex;
justify-content: center;
align-items: center;
margin: 8px 16px;
animation: ${fadeIn} 0.4s ease-in;
padding: 0;
`;
const SimplePickerContainer = styled.div`
display: flex;
justify-content: center;
align-items: center;
margin: 16px;
animation: ${fadeIn} 0.4s ease-in;
padding: 0;
`;
const EmojiAvatar = styled(Avatar)<{ clr: string | undefined }>`
background: ${({ clr, theme }) => clr || theme.primary};
transition: 0.3s all;
cursor: pointer;
width: 96px;
height: 96px;
`;
const EditBadge = styled(Avatar)`
background: #9c9c9c81;
backdrop-filter: blur(6px);
cursor: pointer;
`;
const PickerLoader = styled.div<{
pickerTheme: "light" | "dark" | undefined;
width?: CSSProperties["width"] | undefined;
}>`
display: flex;
align-items: center;
justify-content: center;
width: ${({ width }) => width || "350px"};
height: 500px;
width: 100vw;
padding: 8px;
border-radius: 20px;
background: transparent;
border: ${({ pickerTheme }) => `1px solid ${pickerTheme === "dark" ? "#151617" : "#e7e7e7"}`};
`;
const EmojiElement = styled.div`
animation: ${fadeIn} 0.4s ease-in;
`;