index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. 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. <Drawer
  164. isShow
  165. positionCenter={isAdd && !positionLeft}
  166. onHide={onHide}
  167. title={t(`tools.createTool.${isAdd ? 'title' : 'editTitle'}`)!}
  168. panelClassName='mt-2 !w-[630px]'
  169. maxWidthClassName='!max-w-[630px]'
  170. height='calc(100vh - 16px)'
  171. headerClassName='!border-b-black/5'
  172. body={
  173. <div className='flex flex-col h-full'>
  174. <div className='grow h-0 overflow-y-auto px-6 py-3 space-y-4'>
  175. <div>
  176. <div className={fieldNameClassNames}>{t('tools.createTool.name')} <span className='ml-1 text-red-500'>*</span></div>
  177. <div className='flex items-center justify-between gap-3'>
  178. <AppIcon size='large' onClick={() => { setShowEmojiPicker(true) }} className='cursor-pointer' icon={emoji.content} background={emoji.background} />
  179. <input
  180. className='h-10 px-3 text-sm font-normal bg-gray-100 rounded-lg grow' placeholder={t('tools.createTool.toolNamePlaceHolder')!}
  181. value={customCollection.provider}
  182. onChange={(e) => {
  183. const newCollection = produce(customCollection, (draft) => {
  184. draft.provider = e.target.value
  185. })
  186. setCustomCollection(newCollection)
  187. }}
  188. />
  189. </div>
  190. </div>
  191. {/* Schema */}
  192. <div className='select-none'>
  193. <div className='flex justify-between items-center'>
  194. <div className='flex items-center'>
  195. <div className={fieldNameClassNames}>{t('tools.createTool.schema')}<span className='ml-1 text-red-500'>*</span></div>
  196. <div className='mx-2 w-px h-3 bg-black/5'></div>
  197. <a
  198. href="https://swagger.io/specification/"
  199. target='_blank' rel='noopener noreferrer'
  200. className='flex items-center h-[18px] space-x-1 text-[#155EEF]'
  201. >
  202. <div className='text-xs font-normal'>{t('tools.createTool.viewSchemaSpec')}</div>
  203. <LinkExternal02 className='w-3 h-3' />
  204. </a>
  205. </div>
  206. <GetSchema onChange={setSchema} />
  207. </div>
  208. <textarea
  209. value={schema}
  210. onChange={e => setSchema(e.target.value)}
  211. 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'
  212. placeholder={t('tools.createTool.schemaPlaceHolder')!}
  213. ></textarea>
  214. </div>
  215. {/* Available Tools */}
  216. <div>
  217. <div className={fieldNameClassNames}>{t('tools.createTool.availableTools.title')}</div>
  218. <div className='rounded-lg border border-gray-200 w-full overflow-x-auto'>
  219. <table className='w-full leading-[18px] text-xs text-gray-700 font-normal'>
  220. <thead className='text-gray-500 uppercase'>
  221. <tr className={cn(paramsSchemas.length > 0 && 'border-b', 'border-gray-200')}>
  222. <th className="p-2 pl-3 font-medium">{t('tools.createTool.availableTools.name')}</th>
  223. <th className="p-2 pl-3 font-medium w-[236px]">{t('tools.createTool.availableTools.description')}</th>
  224. <th className="p-2 pl-3 font-medium">{t('tools.createTool.availableTools.method')}</th>
  225. <th className="p-2 pl-3 font-medium">{t('tools.createTool.availableTools.path')}</th>
  226. <th className="p-2 pl-3 font-medium w-[54px]">{t('tools.createTool.availableTools.action')}</th>
  227. </tr>
  228. </thead>
  229. <tbody>
  230. {paramsSchemas.map((item, index) => (
  231. <tr key={index} className='border-b last:border-0 border-gray-200'>
  232. <td className="p-2 pl-3">{item.operation_id}</td>
  233. <td className="p-2 pl-3 text-gray-500 w-[236px]">{item.summary}</td>
  234. <td className="p-2 pl-3">{item.method}</td>
  235. <td className="p-2 pl-3">{getPath(item.server_url)}</td>
  236. <td className="p-2 pl-3 w-[62px]">
  237. <Button
  238. size='small'
  239. onClick={() => {
  240. setCurrTool(item)
  241. setIsShowTestApi(true)
  242. }}
  243. >
  244. {t('tools.createTool.availableTools.test')}
  245. </Button>
  246. </td>
  247. </tr>
  248. ))}
  249. </tbody>
  250. </table>
  251. </div>
  252. </div>
  253. {/* Authorization method */}
  254. <div>
  255. <div className={fieldNameClassNames}>{t('tools.createTool.authMethod.title')}</div>
  256. <div className='flex items-center h-9 justify-between px-2.5 bg-gray-100 rounded-lg cursor-pointer' onClick={() => setCredentialsModalShow(true)}>
  257. <div className='text-sm font-normal text-gray-900'>{t(`tools.createTool.authMethod.types.${credential.auth_type}`)}</div>
  258. <Settings01 className='w-4 h-4 text-gray-700 opacity-60' />
  259. </div>
  260. </div>
  261. {/* Labels */}
  262. <div>
  263. <div className='py-2 leading-5 text-sm font-medium text-gray-900'>{t('tools.createTool.toolInput.label')}</div>
  264. <LabelSelector value={labels} onChange={handleLabelSelect} />
  265. </div>
  266. {/* Privacy Policy */}
  267. <div>
  268. <div className={fieldNameClassNames}>{t('tools.createTool.privacyPolicy')}</div>
  269. <input
  270. value={customCollection.privacy_policy}
  271. onChange={(e) => {
  272. const newCollection = produce(customCollection, (draft) => {
  273. draft.privacy_policy = e.target.value
  274. })
  275. setCustomCollection(newCollection)
  276. }}
  277. className='w-full h-10 px-3 text-sm font-normal bg-gray-100 rounded-lg grow' placeholder={t('tools.createTool.privacyPolicyPlaceholder') || ''} />
  278. </div>
  279. <div>
  280. <div className={fieldNameClassNames}>{t('tools.createTool.customDisclaimer')}</div>
  281. <input
  282. value={customCollection.custom_disclaimer}
  283. onChange={(e) => {
  284. const newCollection = produce(customCollection, (draft) => {
  285. draft.custom_disclaimer = e.target.value
  286. })
  287. setCustomCollection(newCollection)
  288. }}
  289. className='w-full h-10 px-3 text-sm font-normal bg-gray-100 rounded-lg grow' placeholder={t('tools.createTool.customDisclaimerPlaceholder') || ''} />
  290. </div>
  291. </div>
  292. <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')} >
  293. {
  294. isEdit && (
  295. <Button onClick={onRemove} className='text-red-500 border-red-50 hover:border-red-500'>{t('common.operation.delete')}</Button>
  296. )
  297. }
  298. <div className='flex space-x-2 '>
  299. <Button onClick={onHide}>{t('common.operation.cancel')}</Button>
  300. <Button variant='primary' onClick={handleSave}>{t('common.operation.save')}</Button>
  301. </div>
  302. </div>
  303. {showEmojiPicker && <EmojiPicker
  304. onSelect={(icon, icon_background) => {
  305. setEmoji({ content: icon, background: icon_background })
  306. setShowEmojiPicker(false)
  307. }}
  308. onClose={() => {
  309. setShowEmojiPicker(false)
  310. }}
  311. />}
  312. {credentialsModalShow && (
  313. <ConfigCredentials
  314. positionCenter={isAdd}
  315. credential={credential}
  316. onChange={setCredential}
  317. onHide={() => setCredentialsModalShow(false)}
  318. />)
  319. }
  320. {isShowTestApi && (
  321. <TestApi
  322. positionCenter={isAdd}
  323. tool={currTool as CustomParamSchema}
  324. customCollection={customCollection}
  325. onHide={() => setIsShowTestApi(false)}
  326. />
  327. )}
  328. </div>
  329. }
  330. isShowMask={true}
  331. clickOutsideNotOpen={true}
  332. />
  333. </>
  334. )
  335. }
  336. export default React.memo(EditCustomCollectionModal)