index.tsx 14 KB

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