index.tsx 12 KB

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