modal.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useEffect, useState } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import { useDebounce, useGetState } from 'ahooks'
  6. import produce from 'immer'
  7. import { LinkExternal02, Settings01 } from '../../base/icons/src/vender/line/general'
  8. import type { Credential, CustomCollectionBackend, CustomParamSchema, Emoji } from '../types'
  9. import { AuthHeaderPrefix, AuthType } from '../types'
  10. import GetSchema from './get-schema'
  11. import ConfigCredentials from './config-credentials'
  12. import TestApi from './test-api'
  13. import cn from '@/utils/classnames'
  14. import Input from '@/app/components/base/input'
  15. import Textarea from '@/app/components/base/textarea'
  16. import EmojiPicker from '@/app/components/base/emoji-picker'
  17. import AppIcon from '@/app/components/base/app-icon'
  18. import { parseParamsSchema } from '@/service/tools'
  19. import LabelSelector from '@/app/components/tools/labels/selector'
  20. import Toast from '@/app/components/base/toast'
  21. import Modal from '../../base/modal'
  22. import Button from '@/app/components/base/button'
  23. type Props = {
  24. positionLeft?: boolean
  25. payload: any
  26. onHide: () => void
  27. onAdd?: (payload: CustomCollectionBackend) => void
  28. onRemove?: () => void
  29. onEdit?: (payload: CustomCollectionBackend) => void
  30. }
  31. // Add and Edit
  32. const EditCustomCollectionModal: FC<Props> = ({
  33. payload,
  34. onHide,
  35. onAdd,
  36. onEdit,
  37. onRemove,
  38. }) => {
  39. const { t } = useTranslation()
  40. const isAdd = !payload
  41. const isEdit = !!payload
  42. const [editFirst, setEditFirst] = useState(!isAdd)
  43. const [paramsSchemas, setParamsSchemas] = useState<CustomParamSchema[]>(payload?.tools || [])
  44. const [customCollection, setCustomCollection, getCustomCollection] = useGetState<CustomCollectionBackend>(isAdd
  45. ? {
  46. provider: '',
  47. credentials: {
  48. auth_type: AuthType.none,
  49. api_key_header: 'Authorization',
  50. api_key_header_prefix: AuthHeaderPrefix.basic,
  51. },
  52. icon: {
  53. content: '🕵️',
  54. background: '#FEF7C3',
  55. },
  56. schema_type: '',
  57. schema: '',
  58. }
  59. : payload)
  60. const originalProvider = isEdit ? payload.provider : ''
  61. const [showEmojiPicker, setShowEmojiPicker] = useState(false)
  62. const emoji = customCollection.icon
  63. const setEmoji = (emoji: Emoji) => {
  64. const newCollection = produce(customCollection, (draft) => {
  65. draft.icon = emoji
  66. })
  67. setCustomCollection(newCollection)
  68. }
  69. const schema = customCollection.schema
  70. const debouncedSchema = useDebounce(schema, { wait: 500 })
  71. const setSchema = (schema: any) => {
  72. const newCollection = produce(customCollection, (draft) => {
  73. draft.schema = schema
  74. })
  75. setCustomCollection(newCollection)
  76. }
  77. useEffect(() => {
  78. if (!debouncedSchema)
  79. return
  80. if (isEdit && editFirst) {
  81. setEditFirst(false)
  82. return
  83. }
  84. (async () => {
  85. try {
  86. const { parameters_schema, schema_type } = await parseParamsSchema(debouncedSchema)
  87. const customCollection = getCustomCollection()
  88. const newCollection = produce(customCollection, (draft) => {
  89. draft.schema_type = schema_type
  90. })
  91. setCustomCollection(newCollection)
  92. setParamsSchemas(parameters_schema)
  93. }
  94. catch (e) {
  95. const customCollection = getCustomCollection()
  96. const newCollection = produce(customCollection, (draft) => {
  97. draft.schema_type = ''
  98. })
  99. setCustomCollection(newCollection)
  100. setParamsSchemas([])
  101. }
  102. })()
  103. }, [debouncedSchema])
  104. const [credentialsModalShow, setCredentialsModalShow] = useState(false)
  105. const credential = customCollection.credentials
  106. const setCredential = (credential: Credential) => {
  107. const newCollection = produce(customCollection, (draft) => {
  108. draft.credentials = credential
  109. })
  110. setCustomCollection(newCollection)
  111. }
  112. const [currTool, setCurrTool] = useState<CustomParamSchema | null>(null)
  113. const [isShowTestApi, setIsShowTestApi] = useState(false)
  114. const [labels, setLabels] = useState<string[]>(payload?.labels || [])
  115. const handleLabelSelect = (value: string[]) => {
  116. setLabels(value)
  117. }
  118. const handleSave = () => {
  119. // const postData = clone(customCollection)
  120. const postData = produce(customCollection, (draft) => {
  121. delete draft.tools
  122. if (draft.credentials.auth_type === AuthType.none) {
  123. delete draft.credentials.api_key_header
  124. delete draft.credentials.api_key_header_prefix
  125. delete draft.credentials.api_key_value
  126. }
  127. draft.labels = labels
  128. })
  129. let errorMessage = ''
  130. if (!postData.provider)
  131. errorMessage = t('common.errorMsg.fieldRequired', { field: t('tools.createTool.name') })
  132. if (!postData.schema)
  133. errorMessage = t('common.errorMsg.fieldRequired', { field: t('tools.createTool.schema') })
  134. if (errorMessage) {
  135. Toast.notify({
  136. type: 'error',
  137. message: errorMessage,
  138. })
  139. return
  140. }
  141. if (isAdd) {
  142. onAdd?.(postData)
  143. return
  144. }
  145. onEdit?.({
  146. ...postData,
  147. original_provider: originalProvider,
  148. })
  149. }
  150. const getPath = (url: string) => {
  151. if (!url)
  152. return ''
  153. try {
  154. const path = decodeURI(new URL(url).pathname)
  155. return path || ''
  156. }
  157. catch (e) {
  158. return url
  159. }
  160. }
  161. return (
  162. <>
  163. <Modal
  164. isShow
  165. onClose={onHide}
  166. closable
  167. className='!p-0 !max-w-[630px] !h-[calc(100vh-16px)]'
  168. >
  169. <div className='flex flex-col h-full'>
  170. <div className='ml-6 mt-6 text-base font-semibold text-text-primary'>
  171. {t('tools.createTool.title')}
  172. </div>
  173. <div className='grow h-0 overflow-y-auto px-6 py-3 space-y-4'>
  174. <div>
  175. <div className='py-2 system-sm-medium text-text-primary'>{t('tools.createTool.name')} <span className='ml-1 text-red-500'>*</span></div>
  176. <div className='flex items-center justify-between gap-3'>
  177. <AppIcon size='large' onClick={() => { setShowEmojiPicker(true) }} className='cursor-pointer' icon={emoji.content} background={emoji.background} />
  178. <Input
  179. className='h-10 grow' placeholder={t('tools.createTool.toolNamePlaceHolder')!}
  180. value={customCollection.provider}
  181. onChange={(e) => {
  182. const newCollection = produce(customCollection, (draft) => {
  183. draft.provider = e.target.value
  184. })
  185. setCustomCollection(newCollection)
  186. }}
  187. />
  188. </div>
  189. </div>
  190. {/* Schema */}
  191. <div className='select-none'>
  192. <div className='flex justify-between items-center'>
  193. <div className='flex items-center'>
  194. <div className='py-2 system-sm-medium text-text-primary'>{t('tools.createTool.schema')}<span className='ml-1 text-red-500'>*</span></div>
  195. <div className='mx-2 w-px h-3 bg-divider-regular'></div>
  196. <a
  197. href="https://swagger.io/specification/"
  198. target='_blank' rel='noopener noreferrer'
  199. className='flex items-center h-[18px] space-x-1 text-text-accent'
  200. >
  201. <div className='text-xs font-normal'>{t('tools.createTool.viewSchemaSpec')}</div>
  202. <LinkExternal02 className='w-3 h-3' />
  203. </a>
  204. </div>
  205. <GetSchema onChange={setSchema} />
  206. </div>
  207. <Textarea
  208. className='h-[240px] resize-none'
  209. value={schema}
  210. onChange={e => setSchema(e.target.value)}
  211. placeholder={t('tools.createTool.schemaPlaceHolder')!}
  212. />
  213. </div>
  214. {/* Available Tools */}
  215. <div>
  216. <div className='py-2 system-sm-medium text-text-primary'>{t('tools.createTool.availableTools.title')}</div>
  217. <div className='rounded-lg border border-divider-regular w-full overflow-x-auto'>
  218. <table className='w-full system-xs-regular text-text-secondary'>
  219. <thead className='text-text-tertiary uppercase'>
  220. <tr className={cn(paramsSchemas.length > 0 && 'border-b', 'border-divider-regular')}>
  221. <th className="p-2 pl-3 font-medium">{t('tools.createTool.availableTools.name')}</th>
  222. <th className="p-2 pl-3 font-medium w-[236px]">{t('tools.createTool.availableTools.description')}</th>
  223. <th className="p-2 pl-3 font-medium">{t('tools.createTool.availableTools.method')}</th>
  224. <th className="p-2 pl-3 font-medium">{t('tools.createTool.availableTools.path')}</th>
  225. <th className="p-2 pl-3 font-medium w-[54px]">{t('tools.createTool.availableTools.action')}</th>
  226. </tr>
  227. </thead>
  228. <tbody>
  229. {paramsSchemas.map((item, index) => (
  230. <tr key={index} className='border-b last:border-0 border-divider-regular'>
  231. <td className="p-2 pl-3">{item.operation_id}</td>
  232. <td className="p-2 pl-3 w-[236px]">{item.summary}</td>
  233. <td className="p-2 pl-3">{item.method}</td>
  234. <td className="p-2 pl-3">{getPath(item.server_url)}</td>
  235. <td className="p-2 pl-3 w-[62px]">
  236. <Button
  237. size='small'
  238. onClick={() => {
  239. setCurrTool(item)
  240. setIsShowTestApi(true)
  241. }}
  242. >
  243. {t('tools.createTool.availableTools.test')}
  244. </Button>
  245. </td>
  246. </tr>
  247. ))}
  248. </tbody>
  249. </table>
  250. </div>
  251. </div>
  252. {/* Authorization method */}
  253. <div>
  254. <div className='py-2 system-sm-medium text-text-primary'>{t('tools.createTool.authMethod.title')}</div>
  255. <div className='flex items-center h-9 justify-between px-2.5 bg-components-input-bg-normal rounded-lg cursor-pointer' onClick={() => setCredentialsModalShow(true)}>
  256. <div className='system-xs-regular text-text-primary'>{t(`tools.createTool.authMethod.types.${credential.auth_type}`)}</div>
  257. <Settings01 className='w-4 h-4 text-text-secondary' />
  258. </div>
  259. </div>
  260. {/* Labels */}
  261. <div>
  262. <div className='py-2 system-sm-medium text-text-primary'>{t('tools.createTool.toolInput.label')}</div>
  263. <LabelSelector value={labels} onChange={handleLabelSelect} />
  264. </div>
  265. {/* Privacy Policy */}
  266. <div>
  267. <div className='py-2 system-sm-medium text-text-primary'>{t('tools.createTool.privacyPolicy')}</div>
  268. <Input
  269. value={customCollection.privacy_policy}
  270. onChange={(e) => {
  271. const newCollection = produce(customCollection, (draft) => {
  272. draft.privacy_policy = e.target.value
  273. })
  274. setCustomCollection(newCollection)
  275. }}
  276. className='h-10 grow' placeholder={t('tools.createTool.privacyPolicyPlaceholder') || ''} />
  277. </div>
  278. <div>
  279. <div className='py-2 system-sm-medium text-text-primary'>{t('tools.createTool.customDisclaimer')}</div>
  280. <Input
  281. value={customCollection.custom_disclaimer}
  282. onChange={(e) => {
  283. const newCollection = produce(customCollection, (draft) => {
  284. draft.custom_disclaimer = e.target.value
  285. })
  286. setCustomCollection(newCollection)
  287. }}
  288. className='h-10 grow' placeholder={t('tools.createTool.customDisclaimerPlaceholder') || ''} />
  289. </div>
  290. </div>
  291. <div className={cn(isEdit ? 'justify-between' : 'justify-end', 'mt-2 shrink-0 flex py-4 px-6 rounded-b-[10px] bg-background-section-burn border-t border-divider-regular')} >
  292. {
  293. isEdit && (
  294. <Button variant='warning' onClick={onRemove}>{t('common.operation.delete')}</Button>
  295. )
  296. }
  297. <div className='flex space-x-2 '>
  298. <Button onClick={onHide}>{t('common.operation.cancel')}</Button>
  299. <Button variant='primary' onClick={handleSave}>{t('common.operation.save')}</Button>
  300. </div>
  301. </div>
  302. {showEmojiPicker && <EmojiPicker
  303. onSelect={(icon, icon_background) => {
  304. setEmoji({ content: icon, background: icon_background })
  305. setShowEmojiPicker(false)
  306. }}
  307. onClose={() => {
  308. setShowEmojiPicker(false)
  309. }}
  310. />}
  311. {credentialsModalShow && (
  312. <ConfigCredentials
  313. positionCenter={isAdd}
  314. credential={credential}
  315. onChange={setCredential}
  316. onHide={() => setCredentialsModalShow(false)}
  317. />)
  318. }
  319. {isShowTestApi && (
  320. <TestApi
  321. positionCenter={isAdd}
  322. tool={currTool as CustomParamSchema}
  323. customCollection={customCollection}
  324. onHide={() => setIsShowTestApi(false)}
  325. />
  326. )}
  327. </div>
  328. </Modal>
  329. </>
  330. )
  331. }
  332. export default React.memo(EditCustomCollectionModal)