-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAddBotForm.tsx
More file actions
363 lines (345 loc) · 12.9 KB
/
AddBotForm.tsx
File metadata and controls
363 lines (345 loc) · 12.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
import FormField from '@app/components/FormField/FormField'
import RichTextEditor from "@app/components/RichText/RichText"
import { errorStatus } from '@app/constants/common.constant'
import Button from '@app/mtb-ui/Button'
import MtbTypography from '@app/mtb-ui/Typography/Typography'
import {
CreateMezonAppRequest,
useMezonAppControllerCreateMezonAppMutation,
useMezonAppControllerUpdateMezonAppMutation
} from '@app/services/api/mezonApp/mezonApp'
import { RootState } from '@app/store'
import { ILinkTypeStore } from '@app/store/linkType'
import { ITagStore } from '@app/store/tag'
import { ApiError } from '@app/types/API.types'
import { IAddBotFormProps } from '@app/types/Botcard.types'
import { Checkbox, Form, Input, Select, TagProps } from 'antd'
import TextArea from 'antd/es/input/TextArea'
import { useMemo, useState } from 'react'
import { Controller, useFieldArray, useFormContext } from 'react-hook-form'
import { useSelector } from 'react-redux'
import { useNavigate, useParams } from 'react-router-dom'
import { toast } from 'react-toastify'
function AddBotForm({ isEdit }: IAddBotFormProps) {
const {
control,
handleSubmit,
setValue,
formState: { errors }
} = useFormContext<CreateMezonAppRequest>()
const [addBot] = useMezonAppControllerCreateMezonAppMutation()
const navigate = useNavigate()
const [updateBot] = useMezonAppControllerUpdateMezonAppMutation()
const { tagList } = useSelector<RootState, ITagStore>((s) => s.tag)
const { linkTypeList } = useSelector<RootState, ILinkTypeStore>((s) => s.link)
const [selectedSocialLink, setSelectedSocialLink] = useState<string>('') // holds selected link type id
const { fields: socialLinksData, append, remove } = useFieldArray({
control,
name: 'socialLinks'
});
const [socialLinkUrl, setSocialLinkUrl] = useState<string>('')
const [dropdownOpen, setDropdownOpen] = useState(false);
const { botId } = useParams()
const onSubmit = async (data: CreateMezonAppRequest) => {
try {
const formattedSocialLinks = socialLinksData.map((link) => {
const selectedLink = optionsLink?.find((item) => item.value === link.linkTypeId)
if (!selectedLink) return link
const siteName = selectedLink.siteName
return {
url: `${siteName}${link.url}`,
linkTypeId: selectedLink.value,
}
})
const { ...restData } = data
const addBotData = {
...restData,
socialLinks: formattedSocialLinks
}
if (!isEdit && !botId) {
const response = await addBot({ createMezonAppRequest: addBotData }).unwrap()
toast.success('Add new bot success')
if (response.id) {
navigate(`/bot/${response.id}`)
}
return
}
if (!botId) return
updateBot({ updateMezonAppRequest: { ...data, id: botId, socialLinks: formattedSocialLinks } })
toast.success('Edit bot success')
} catch (error: unknown) {
const err = error as ApiError
const message =
err?.data?.message && Array.isArray(err.data.message)
? err.data.message.join(', ')
: err?.data?.message || 'Something went wrong'
toast.error(message)
}
}
const options = useMemo(() => {
return tagList?.data?.map((tag) => ({
label: tag.name,
value: tag.id
}))
}, [tagList])
const tagRender = (props: TagProps & { label?: string }) => {
const { label, closable, onClose } = props
return (
<div className={`px-2 rounded-md inline-flex items-center mr-2 text-black capitalize !bg-gray-300`}>
<span>{label}</span>
{closable && (
<span onClick={onClose} className='ml-2 cursor-pointer font-bold'>
×
</span>
)}
</div>
)
}
const optionsLink = useMemo(() => {
return linkTypeList?.map((item) => ({
label: `${item.icon} ${item.name}`,
value: item.id,
icon: item.icon,
siteName: `https://${item.name.toLowerCase()}.com/`,
}))
}, [linkTypeList])
const addNewLink = () => {
// if (not selectedSocialLink or socialLinkUrl not valid) then return
const trimmedUrl = socialLinkUrl.trim()
if (!selectedSocialLink || !trimmedUrl) return
// get selectedLink in optionsLink
const selectedLink = optionsLink?.find((item) => item.value === selectedSocialLink)
if (!selectedLink) return
const defaultSocialLink = {
icon: selectedLink.icon,
url: `${trimmedUrl}`,
linkTypeId: selectedLink?.value,
}
// add new links to the links list
append(defaultSocialLink)
setSocialLinkUrl('')
setSelectedSocialLink('')
}
const handleSocialLinkUrlChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSocialLinkUrl(e.target.value)
}
const handleSelectTag = (value: string[]) => {
console.log(`selected ${value}`)
}
const handleSelectLink = (value: string) => {
console.log(`Link ${value}`)
}
return (
<div className='shadow-md p-8 rounded-md bg-white'>
<Form layout='vertical' onFinish={handleSubmit(onSubmit)}>
<MtbTypography variant='h4'>Your Bot Detail</MtbTypography>
<FormField label='Name' description='Name your bot' errorText={errors.name?.message}>
<Controller
control={control}
name='name'
render={({ field }) => <Input {...field} placeholder='MezonBot' status={errorStatus(errors.name)} />}
/>
</FormField>
<FormField
label='Headline'
description='Provide a short and catchy phrase that describes your bot.'
errorText={errors.headline?.message}
>
<Controller
control={control}
name='headline'
render={({ field }) => (
<TextArea
{...field}
placeholder='A powerful and multi-functional role bot.'
status={errorStatus(errors.headline)}
/>
)}
/>
</FormField>
<FormField
label='Full Description'
description='Tell us what your bot can do. We want to hear the whole story!'
errorText={errors.description?.message}
>
<Controller
control={control}
name='description'
render={({ field }) => (
<RichTextEditor
value={field.value || ""}
onChange={field.onChange}
customClass="custom-editor"
/>
)}
/>
</FormField>
<FormField label='Auto-publish?' customClass='!items-center'>
<Controller control={control} name='isAutoPublished' render={({ field }) => <Checkbox {...field} />} />
</FormField>
<FormField
label='Install Link'
description='A place where users can install your bot on their Mezon server.'
errorText={errors.installLink?.message}
>
<Controller
control={control}
name='installLink'
render={({ field }) => (
<Input
{...field}
placeholder='https://mezon.ai/oauth2/authorize?client_id=1261258962204889149&scope=bot'
status={errorStatus(errors.installLink)}
/>
)}
/>
</FormField>
<FormField
label='Prefix'
description='What keyword or phrase does your bot react to?'
errorText={errors.prefix?.message}
>
<Controller
control={control}
name='prefix'
render={({ field }) => <Input {...field} placeholder='*' status={errorStatus(errors.prefix)} />}
/>
</FormField>
<FormField
label='Tags'
description='Select the top 12 categories that best represent your community.'
errorText={errors.tagIds?.message}
>
<Controller
control={control}
name='tagIds'
render={({ field }) => (
<>
<Select
{...field}
allowClear
value={field.value || []}
mode='multiple'
options={options}
placeholder='Search for tags'
tagRender={() => <></>} // Hides tags inside the field
status={errors?.tagIds?.message ? 'error' : ''}
open={dropdownOpen}
onDropdownVisibleChange={(visible) => setDropdownOpen(visible)}
onChange={(value) => {
field.onChange(value)
handleSelectTag(value)
setDropdownOpen(false); // Close the dropdown after selection
}}
/>
{(field.value ?? []).length > 0 && (
<div className='mt-2 flex flex-wrap gap-2'>
{(field.value ?? []).map((tag) => {
const tagOption = options.find((opt) => opt.value === tag)
// Call customTagRender manually outside Select
return tagRender({
label: tagOption?.label,
closable: true,
onClose: () => {
const updatedTags = (field.value ?? []).filter((t) => t !== tag)
field.onChange(updatedTags)
handleSelectTag(updatedTags)
}
})
})}
</div>
)}
</>
)}
/>
</FormField>
<FormField
label='Support URL'
description='People might have many questions about your bot, make sure you can answer them!'
errorText={errors.supportUrl?.message}
>
<Controller
control={control}
name='supportUrl'
render={({ field }) => (
<Input {...field} placeholder='https://mezon.ai/support' status={errorStatus(errors.supportUrl)} />
)}
/>
</FormField>
<FormField
label='Note'
description='If you have any important information for the reviewer, you can share it here'
errorText={errors.remark?.message}
>
<Controller
control={control}
name='remark'
render={({ field }) => (
<TextArea
{...field}
rows={4}
placeholder='Please share any important information or details about your bot that our reviewers should know'
status={errorStatus(errors.remark)}
/>
)}
/>
</FormField>
<FormField label='Social Links' description='Link your social channels'>
<div className='flex items-center gap-4 w-full'>
<div className='flex-1'>
<Select
options={optionsLink}
placeholder='Link Types'
className='w-full'
value={selectedSocialLink}
onChange={(value) => {
setSelectedSocialLink(value)
handleSelectLink(value)
}}
/>
</div>
<div className='flex-1'>
{/* TODO: remove hardcode prefix */}
<Input value={socialLinkUrl} prefix={selectedSocialLink ? `https://${linkTypeList.find(item => item.id === selectedSocialLink)?.name.toLocaleLowerCase() || ''}.com/` : ''} onChange={handleSocialLinkUrlChange} disabled={!selectedSocialLink} />
</div>
<div className='flex justify-end'>
<Button onClick={addNewLink} customClassName='!w-[70px]'>
Add
</Button>
</div>
</div>
{!!socialLinksData.length &&
socialLinksData.map((link, index) => {
const selectedLink = optionsLink?.find((item) => item.value === link.linkTypeId)
const siteName = selectedLink?.siteName || '';
return (
<div key={index} className='mt-4 flex gap-4'>
<Input
onChange={(e) => {
setValue(`socialLinks.${index}.url`, e.target.value)
}}
className='flex-1 border p-2 rounded'
value={link.url}
placeholder='Enter link'
prefix={`${link?.icon} ${siteName}`}
/>
<Button onClick={() => remove(index)} customClassName='!w-[70px]'>
Delete
</Button>
</div>
)
})}
</FormField>
<div className='flex !justify-end pt-8 gap-4 items-center'>
<Button color='default' customClassName='w-[200px] !text-blue-500'>
Preview
</Button>
<Button htmlType='submit' customClassName='w-[200px]'>
Save
</Button>
</div>
</Form>
</div>
)
}
export default AddBotForm