index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 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. const fieldNameClassNames = 'py-2 leading-5 text-sm font-medium text-gray-900'
  22. type Props = {
  23. positionLeft?: boolean
  24. payload: any
  25. onHide: () => void
  26. onAdd?: (payload: CustomCollectionBackend) => void
  27. onRemove?: () => void
  28. onEdit?: (payload: CustomCollectionBackend) => void
  29. }
  30. // Add and Edit
  31. const EditCustomCollectionModal: FC<Props> = ({
  32. positionLeft,
  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: string) => {
  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. const customCollection = getCustomCollection()
  86. try {
  87. const { parameters_schema, schema_type } = await parseParamsSchema(debouncedSchema)
  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 newCollection = produce(customCollection, (draft) => {
  96. draft.schema_type = ''
  97. })
  98. setCustomCollection(newCollection)
  99. setParamsSchemas([])
  100. }
  101. })()
  102. }, [debouncedSchema])
  103. const [credentialsModalShow, setCredentialsModalShow] = useState(false)
  104. const credential = customCollection.credentials
  105. const setCredential = (credential: Credential) => {
  106. const newCollection = produce(customCollection, (draft) => {
  107. draft.credentials = credential
  108. })
  109. setCustomCollection(newCollection)
  110. }
  111. const [currTool, setCurrTool] = useState<CustomParamSchema | null>(null)
  112. const [isShowTestApi, setIsShowTestApi] = useState(false)
  113. const [labels, setLabels] = useState<string[]>(payload?.labels || [])
  114. const handleLabelSelect = (value: string[]) => {
  115. setLabels(value)
  116. }
  117. const handleSave = () => {
  118. // const postData = clone(customCollection)
  119. const postData = produce(customCollection, (draft) => {
  120. delete draft.tools
  121. if (draft.credentials.auth_type === AuthType.none) {
  122. delete draft.credentials.api_key_header
  123. delete draft.credentials.api_key_header_prefix
  124. delete draft.credentials.api_key_value
  125. }
  126. draft.labels = labels
  127. })
  128. let errorMessage = ''
  129. if (!postData.provider)
  130. errorMessage = t('common.errorMsg.fieldRequired', { field: t('tools.createTool.name') })
  131. if (!postData.schema)
  132. errorMessage = t('common.errorMsg.fieldRequired', { field: t('tools.createTool.schema') })
  133. if (errorMessage) {
  134. Toast.notify({
  135. type: 'error',
  136. message: errorMessage,
  137. })
  138. return
  139. }
  140. if (isAdd) {
  141. onAdd?.(postData)
  142. return
  143. }
  144. onEdit?.({
  145. ...postData,
  146. original_provider: originalProvider,
  147. })
  148. }
  149. const getPath = (url: string) => {
  150. if (!url)
  151. return ''
  152. try {
  153. const path = new URL(url).pathname
  154. return path || ''
  155. }
  156. catch (e) {
  157. return url
  158. }
  159. }
  160. return (
  161. <>
  162. <Drawer
  163. isShow
  164. positionCenter={isAdd && !positionLeft}
  165. onHide={onHide}
  166. title={t(`tools.createTool.${isAdd ? 'title' : 'editTitle'}`)!}
  167. panelClassName='mt-2 !w-[630px]'
  168. maxWidthClassName='!max-w-[630px]'
  169. height='calc(100vh - 16px)'
  170. headerClassName='!border-b-black/5'
  171. body={
  172. <div className='flex flex-col h-full'>
  173. <div className='grow h-0 overflow-y-auto px-6 py-3 space-y-4'>
  174. <div>
  175. <div className={fieldNameClassNames}>{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 px-3 text-sm font-normal bg-gray-100 rounded-lg 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={fieldNameClassNames}>{t('tools.createTool.schema')}<span className='ml-1 text-red-500'>*</span></div>
  195. <div className='mx-2 w-px h-3 bg-black/5'></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-[#155EEF]'
  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. value={schema}
  209. onChange={e => setSchema(e.target.value)}
  210. className='w-full h-[240px] px-3 py-2 leading-4 text-xs font-normal text-gray-900 bg-gray-100 rounded-lg overflow-y-auto'
  211. placeholder={t('tools.createTool.schemaPlaceHolder')!}
  212. ></textarea>
  213. </div>
  214. {/* Available Tools */}
  215. <div>
  216. <div className={fieldNameClassNames}>{t('tools.createTool.availableTools.title')}</div>
  217. <div className='rounded-lg border border-gray-200 w-full overflow-x-auto'>
  218. <table className='w-full leading-[18px] text-xs text-gray-700 font-normal'>
  219. <thead className='text-gray-500 uppercase'>
  220. <tr className={cn(paramsSchemas.length > 0 && 'border-b', 'border-gray-200')}>
  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-gray-200'>
  231. <td className="p-2 pl-3">{item.operation_id}</td>
  232. <td className="p-2 pl-3 text-gray-500 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={fieldNameClassNames}>{t('tools.createTool.authMethod.title')}</div>
  255. <div className='flex items-center h-9 justify-between px-2.5 bg-gray-100 rounded-lg cursor-pointer' onClick={() => setCredentialsModalShow(true)}>
  256. <div className='text-sm font-normal text-gray-900'>{t(`tools.createTool.authMethod.types.${credential.auth_type}`)}</div>
  257. <Settings01 className='w-4 h-4 text-gray-700 opacity-60' />
  258. </div>
  259. </div>
  260. {/* Labels */}
  261. <div>
  262. <div className='py-2 leading-5 text-sm font-medium text-gray-900'>{t('tools.createTool.toolInput.label')}</div>
  263. <LabelSelector value={labels} onChange={handleLabelSelect} />
  264. </div>
  265. {/* Privacy Policy */}
  266. <div>
  267. <div className={fieldNameClassNames}>{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='w-full h-10 px-3 text-sm font-normal bg-gray-100 rounded-lg grow' placeholder={t('tools.createTool.privacyPolicyPlaceholder') || ''} />
  277. </div>
  278. <div>
  279. <div className={fieldNameClassNames}>{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='w-full h-10 px-3 text-sm font-normal bg-gray-100 rounded-lg 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-gray-50 border-t border-black/5')} >
  292. {
  293. isEdit && (
  294. <Button onClick={onRemove} className='text-red-500 border-red-50 hover:border-red-500'>{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. </div>
  303. }
  304. isShowMask={true}
  305. clickOutsideNotOpen={true}
  306. />
  307. {showEmojiPicker && <EmojiPicker
  308. onSelect={(icon, icon_background) => {
  309. setEmoji({ content: icon, background: icon_background })
  310. setShowEmojiPicker(false)
  311. }}
  312. onClose={() => {
  313. setShowEmojiPicker(false)
  314. }}
  315. />}
  316. {credentialsModalShow && (
  317. <ConfigCredentials
  318. positionCenter={isAdd}
  319. credential={credential}
  320. onChange={setCredential}
  321. onHide={() => setCredentialsModalShow(false)}
  322. />)
  323. }
  324. {isShowTestApi && (
  325. <TestApi
  326. positionCenter={isAdd}
  327. tool={currTool as CustomParamSchema}
  328. customCollection={customCollection}
  329. onHide={() => setIsShowTestApi(false)}
  330. />
  331. )}
  332. </>
  333. )
  334. }
  335. export default React.memo(EditCustomCollectionModal)