-
-
Notifications
You must be signed in to change notification settings - Fork 11.8k
Expand file tree
/
Copy pathedit-profile.tsx
More file actions
381 lines (348 loc) · 15.9 KB
/
Copy pathedit-profile.tsx
File metadata and controls
381 lines (348 loc) · 15.9 KB
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
import React, {ChangeEvent, useEffect, useRef, useState} from 'react';
import {Account} from '@src/api/activitypub';
import {Button, DialogClose, DialogFooter, Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, Input, LoadingIndicator, Textarea} from '@tryghost/shade/components';
import {FILE_SIZE_ERROR_MESSAGE, MAX_FILE_SIZE, SQUARE_IMAGE_ERROR_MESSAGE, isSquareImage} from '@utils/image';
import {LucideIcon} from '@tryghost/shade/utils';
import {toast} from 'sonner';
import {uploadFile} from '@hooks/use-activity-pub-queries';
import {useForm} from 'react-hook-form';
import {useUpdateAccountMutationForUser} from '@hooks/use-activity-pub-queries';
import {z} from 'zod';
import {zodResolver} from '@hookform/resolvers/zod';
const decodeHTMLEntities = (text: string): string => {
const textarea = document.createElement('textarea');
textarea.innerHTML = text;
return textarea.value;
};
const FormSchema = z.object({
profileImage: z.string().optional(),
coverImage: z.string().optional(),
name: z.string()
.nonempty({
message: 'Display name is required.'
})
.max(64, {
message: 'Display name must be less than 64 characters.'
}),
handle: z.string()
.min(2, {
message: 'Handle must be at least 2 characters.'
})
.max(100, {
message: 'Handle must be less than 100 characters.'
})
.regex(/^[a-zA-Z0-9_]+$/, {
message: 'Handle must contain only letters, numbers, and underscores.'
}),
bio: z.string()
.max(250, {
message: 'Bio must be less than 250 characters.'
})
.optional()
});
type EditProfileProps = {
account: Account,
setIsEditingProfile: (value: boolean) => void;
}
const EditProfile: React.FC<EditProfileProps> = ({account, setIsEditingProfile}) => {
const [profileImagePreview, setProfileImagePreview] = useState<string | null>(account.avatarUrl || null);
const profileImageInputRef = useRef<HTMLInputElement>(null);
const [isProfileImageUploading, setIsProfileImageUploading] = useState(false);
const [coverImagePreview, setCoverImagePreview] = useState<string | null>(account.bannerImageUrl || null);
const coverImageInputRef = useRef<HTMLInputElement>(null);
const [isCoverImageUploading, setIsCoverImageUploading] = useState(false);
const [handleDomain, setHandleDomain] = useState<string>('');
const [isSubmitting, setIsSubmitting] = useState(false);
const {mutate: updateAccount} = useUpdateAccountMutationForUser(account?.handle || '');
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: {
profileImage: account.avatarUrl,
coverImage: account.bannerImageUrl || '',
name: account.name,
handle: '',
bio: account.bio ? decodeHTMLEntities(account.bio) : ''
}
});
const hasNameError = !!form.formState.errors.name;
const hasHandleError = !!form.formState.errors.handle;
useEffect(() => {
if (account.handle) {
const match = account.handle.match(/@([^@]+)@(.+)/);
if (match) {
form.setValue('handle', match[1]);
setHandleDomain(match[2]);
}
}
}, [account.handle, form]);
const triggerProfileImageInput = () => {
profileImageInputRef.current?.click();
};
const handleProfileImageUpload = async (file: File) => {
try {
setIsProfileImageUploading(true);
const uploadedImageUrl = await uploadFile(file);
return uploadedImageUrl;
} catch (error) {
setProfileImagePreview(null);
form.setValue('profileImage', '');
let errorMessage = 'Failed to upload image. Try again.';
if (error && typeof error === 'object' && 'statusCode' in error) {
switch (error.statusCode) {
case 413:
errorMessage = 'Image size exceeds limit.';
break;
case 415:
errorMessage = 'The file type is not supported.';
break;
default:
// Use the default error message
}
}
toast.error(errorMessage);
} finally {
setIsProfileImageUploading(false);
}
};
const handleProfileImageChange = async (e: ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (files && files.length > 0) {
const file = files[0];
if (file.size > MAX_FILE_SIZE) {
toast.error(FILE_SIZE_ERROR_MESSAGE);
e.target.value = '';
return;
}
const isSquare = await isSquareImage(file);
if (!isSquare) {
toast.error(SQUARE_IMAGE_ERROR_MESSAGE);
e.target.value = '';
return;
}
const previewUrl = URL.createObjectURL(file);
setProfileImagePreview(previewUrl);
const uploadedUrl = await handleProfileImageUpload(file);
form.setValue('profileImage', uploadedUrl);
}
};
const triggerCoverImageInput = () => {
coverImageInputRef.current?.click();
};
const handleCoverImageUpload = async (file: File) => {
try {
setIsCoverImageUploading(true);
const uploadedImageUrl = await uploadFile(file);
return uploadedImageUrl;
} catch (error) {
setCoverImagePreview(null);
form.setValue('coverImage', '');
let errorMessage = 'Failed to upload image. Try again.';
if (error && typeof error === 'object' && 'statusCode' in error) {
switch (error.statusCode) {
case 413:
errorMessage = 'Image size exceeds limit.';
break;
case 415:
errorMessage = 'The file type is not supported.';
break;
default:
// Use the default error message
}
}
toast.error(errorMessage);
} finally {
setIsCoverImageUploading(false);
}
};
const handleCoverImageChange = async (e: ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (files && files.length > 0) {
const file = files[0];
if (file.size > MAX_FILE_SIZE) {
toast.error(FILE_SIZE_ERROR_MESSAGE);
e.target.value = '';
return;
}
const previewUrl = URL.createObjectURL(file);
setCoverImagePreview(previewUrl);
const uploadedUrl = await handleCoverImageUpload(file);
form.setValue('coverImage', uploadedUrl);
}
};
function onSubmit(data: z.infer<typeof FormSchema>) {
setIsSubmitting(true);
const decodedBio = account.bio ? decodeHTMLEntities(account.bio) : '';
if (
data.name === account.name &&
data.handle === account.handle.split('@')[1] &&
data.bio === decodedBio &&
data.profileImage === account.avatarUrl &&
data.coverImage === account.bannerImageUrl
) {
setIsSubmitting(false);
setIsEditingProfile(false);
return;
}
updateAccount({
name: data.name || account.name,
username: data.handle || account.handle,
bio: data.bio ?? '',
avatarUrl: data.profileImage || '',
bannerImageUrl: data.coverImage || ''
}, {
onSettled() {
setIsSubmitting(false);
setIsEditingProfile(false);
}
});
}
return (
<Form {...form}>
<form
className="flex flex-col gap-5"
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
form.handleSubmit(onSubmit)();
}
}}
onSubmit={form.handleSubmit(onSubmit)}
>
<div className='relative mb-2'>
<div className='group relative flex h-[180px] cursor-pointer items-center justify-center bg-gray-100 dark:bg-gray-950' onClick={triggerCoverImageInput}>
{coverImagePreview ?
<>
<img className={`size-full object-cover ${isCoverImageUploading && 'opacity-10'}`} src={coverImagePreview} />
{isCoverImageUploading &&
<div className='absolute leading-[0]'>
<LoadingIndicator size='md' />
</div>
}
<Button className='absolute top-3 right-3 size-8 bg-black/60 opacity-0 group-hover:opacity-100 hover:bg-black/80 dark:text-white' onClick={(e) => {
e.stopPropagation();
setCoverImagePreview(null);
form.setValue('coverImage', '');
}}><LucideIcon.Trash2 /></Button>
</> :
<Button className='pointer-events-none absolute right-3 bottom-3 bg-gray-200 group-hover:bg-gray-300 dark:bg-black/40 dark:text-white dark:group-hover:bg-black/60' variant='secondary'>Upload cover image</Button>
}
</div>
<div className='group absolute -bottom-10 left-4 flex size-20 cursor-pointer items-center justify-center rounded-full border-2 border-white bg-gray-100 dark:border-surface-elevated-2 dark:bg-gray-950' onClick={triggerProfileImageInput}>
{profileImagePreview ?
<>
<img className={`size-full rounded-full object-cover ${isProfileImageUploading && 'opacity-10'}`} src={profileImagePreview} />
{isProfileImageUploading &&
<div className='absolute leading-[0]'>
<LoadingIndicator size='md' />
</div>
}
<Button className='absolute -top-2 -right-2 h-8 w-10 rounded-full bg-black/80 opacity-0 group-hover:opacity-100 hover:bg-black/90 dark:text-white' onClick={(e) => {
e.stopPropagation();
setProfileImagePreview(null);
form.setValue('profileImage', '');
}}><LucideIcon.Trash2 /></Button>
</> :
<LucideIcon.UserRoundPlus size={32} strokeWidth={1.5} />
}
</div>
</div>
<FormField
control={form.control}
name="profileImage"
render={() => (
<FormItem>
<FormControl>
<Input
ref={profileImageInputRef}
accept="image/*"
className='hidden'
type="file"
onChange={handleProfileImageChange}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="coverImage"
render={() => (
<FormItem>
<FormControl>
<Input
ref={coverImageInputRef}
accept="image/*"
className='hidden'
type="file"
onChange={handleCoverImageChange}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="name"
render={({field}) => (
<FormItem>
<FormLabel>Display name</FormLabel>
<FormControl>
<Input placeholder="Jamie Larson" {...field} />
</FormControl>
{!hasNameError && (
<FormDescription>
The name shown to your followers in the Inbox and Feed
</FormDescription>
)}
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="handle"
render={({field}) => (
<FormItem>
<FormLabel>Handle</FormLabel>
<FormControl>
<div className='relative flex items-center justify-stretch gap-1 rounded-md border border-transparent bg-gray-100 px-3 transition-colors focus-within:border-(--color-focus-ring) focus-within:bg-transparent focus-within:shadow-[(--color-focus-ring)] focus-within:outline-hidden dark:bg-gray-950'>
<LucideIcon.AtSign className='w-4 min-w-4 text-gray-700' size={16} />
<Input className='w-auto grow border-none! bg-transparent px-0 shadow-none! outline-hidden!' placeholder="index" {...field} />
<span className='max-w-[200px] truncate text-right whitespace-nowrap text-gray-700 max-sm:hidden' title={`@${handleDomain}`}>@{handleDomain}</span>
</div>
</FormControl>
{!hasHandleError && (
<FormDescription>
Your social web handle that others can follow. Works just like an email address. <a className='font-medium text-purple' href="https://ghost.org/help/social-web/" rel="noreferrer" target='_blank'>Learn more</a>
</FormDescription>
)}
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="bio"
render={({field}) => (
<FormItem>
<FormLabel>Bio</FormLabel>
<FormControl>
<Textarea {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter className='max-sm:gap-2'>
<DialogClose asChild>
<Button variant='outline'>Cancel</Button>
</DialogClose>
<Button disabled={isSubmitting || isProfileImageUploading || isCoverImageUploading} type="submit">Save</Button>
</DialogFooter>
</form>
</Form>
);
};
export default EditProfile;