external-data-tool-modal.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import type { FC } from 'react'
  2. import { useState } from 'react'
  3. import useSWR from 'swr'
  4. import { useContext } from 'use-context-selector'
  5. import { useTranslation } from 'react-i18next'
  6. import FormGeneration from '../toolbox/moderation/form-generation'
  7. import Modal from '@/app/components/base/modal'
  8. import Button from '@/app/components/base/button'
  9. import EmojiPicker from '@/app/components/base/emoji-picker'
  10. import ApiBasedExtensionSelector from '@/app/components/header/account-setting/api-based-extension-page/selector'
  11. import { BookOpen01 } from '@/app/components/base/icons/src/vender/line/education'
  12. import { fetchCodeBasedExtensionList } from '@/service/common'
  13. import { SimpleSelect } from '@/app/components/base/select'
  14. import I18n from '@/context/i18n'
  15. import { LanguagesSupportedUnderscore, getModelRuntimeSupported } from '@/utils/language'
  16. import type {
  17. CodeBasedExtensionItem,
  18. ExternalDataTool,
  19. } from '@/models/common'
  20. import { useToastContext } from '@/app/components/base/toast'
  21. import AppIcon from '@/app/components/base/app-icon'
  22. const systemTypes = ['api']
  23. type ExternalDataToolModalProps = {
  24. data: ExternalDataTool
  25. onCancel: () => void
  26. onSave: (externalDataTool: ExternalDataTool) => void
  27. onValidateBeforeSave?: (externalDataTool: ExternalDataTool) => boolean
  28. }
  29. type Provider = {
  30. key: string
  31. name: string
  32. form_schema?: CodeBasedExtensionItem['form_schema']
  33. }
  34. const ExternalDataToolModal: FC<ExternalDataToolModalProps> = ({
  35. data,
  36. onCancel,
  37. onSave,
  38. onValidateBeforeSave,
  39. }) => {
  40. const { t } = useTranslation()
  41. const { notify } = useToastContext()
  42. const { locale } = useContext(I18n)
  43. const language = getModelRuntimeSupported(locale)
  44. const [localeData, setLocaleData] = useState(data.type ? data : { ...data, type: 'api' })
  45. const [showEmojiPicker, setShowEmojiPicker] = useState(false)
  46. const { data: codeBasedExtensionList } = useSWR(
  47. '/code-based-extension?module=external_data_tool',
  48. fetchCodeBasedExtensionList,
  49. )
  50. const providers: Provider[] = [
  51. {
  52. key: 'api',
  53. name: t('common.apiBasedExtension.selector.title'),
  54. },
  55. ...(
  56. codeBasedExtensionList
  57. ? codeBasedExtensionList.data.map((item) => {
  58. return {
  59. key: item.name,
  60. name: locale === 'zh-Hans' ? item.label['zh-Hans'] : item.label['en-US'],
  61. form_schema: item.form_schema,
  62. }
  63. })
  64. : []
  65. ),
  66. ]
  67. const currentProvider = providers.find(provider => provider.key === localeData.type)
  68. const handleDataTypeChange = (type: string) => {
  69. let config: undefined | Record<string, any>
  70. const currProvider = providers.find(provider => provider.key === type)
  71. if (systemTypes.findIndex(t => t === type) < 0 && currProvider?.form_schema) {
  72. config = currProvider?.form_schema.reduce((prev, next) => {
  73. prev[next.variable] = next.default
  74. return prev
  75. }, {} as Record<string, any>)
  76. }
  77. setLocaleData({
  78. ...localeData,
  79. type,
  80. config,
  81. })
  82. }
  83. const handleDataExtraChange = (extraValue: Record<string, string>) => {
  84. setLocaleData({
  85. ...localeData,
  86. config: {
  87. ...localeData.config,
  88. ...extraValue,
  89. },
  90. })
  91. }
  92. const handleValueChange = (value: Record<string, string>) => {
  93. setLocaleData({
  94. ...localeData,
  95. ...value,
  96. })
  97. }
  98. const handleDataApiBasedChange = (apiBasedExtensionId: string) => {
  99. setLocaleData({
  100. ...localeData,
  101. config: {
  102. ...localeData.config,
  103. api_based_extension_id: apiBasedExtensionId,
  104. },
  105. })
  106. }
  107. const formatData = (originData: ExternalDataTool) => {
  108. const { type, config } = originData
  109. const params: Record<string, string | undefined> = {}
  110. if (type === 'api')
  111. params.api_based_extension_id = config?.api_based_extension_id
  112. if (systemTypes.findIndex(t => t === type) < 0 && currentProvider?.form_schema) {
  113. currentProvider.form_schema.forEach((form) => {
  114. params[form.variable] = config?.[form.variable]
  115. })
  116. }
  117. return {
  118. ...originData,
  119. type,
  120. enabled: data.type ? data.enabled : true,
  121. config: {
  122. ...params,
  123. },
  124. }
  125. }
  126. const handleSave = () => {
  127. if (!localeData.type) {
  128. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: t('appDebug.feature.tools.modal.toolType.title') }) })
  129. return
  130. }
  131. if (!localeData.label) {
  132. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: t('appDebug.feature.tools.modal.name.title') }) })
  133. return
  134. }
  135. if (!localeData.variable) {
  136. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: t('appDebug.feature.tools.modal.variableName.title') }) })
  137. return
  138. }
  139. if (localeData.variable && !/[a-zA-Z_][a-zA-Z0-9_]{0,29}/g.test(localeData.variable)) {
  140. notify({ type: 'error', message: t('appDebug.varKeyError.notValid', { key: t('appDebug.feature.tools.modal.variableName.title') }) })
  141. return
  142. }
  143. if (localeData.type === 'api' && !localeData.config?.api_based_extension_id) {
  144. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: language !== LanguagesSupportedUnderscore[1] ? 'API Extension' : 'API 扩展' }) })
  145. return
  146. }
  147. if (systemTypes.findIndex(t => t === localeData.type) < 0 && currentProvider?.form_schema) {
  148. for (let i = 0; i < currentProvider.form_schema.length; i++) {
  149. if (!localeData.config?.[currentProvider.form_schema[i].variable] && currentProvider.form_schema[i].required) {
  150. notify({
  151. type: 'error',
  152. message: t('appDebug.errorMessage.valueOfVarRequired', { key: language !== LanguagesSupportedUnderscore[1] ? currentProvider.form_schema[i].label['en-US'] : currentProvider.form_schema[i].label['zh-Hans'] }),
  153. })
  154. return
  155. }
  156. }
  157. }
  158. const formatedData = formatData(localeData)
  159. if (onValidateBeforeSave && !onValidateBeforeSave(formatedData))
  160. return
  161. onSave(formatData(formatedData))
  162. }
  163. const action = data.type ? t('common.operation.edit') : t('common.operation.add')
  164. return (
  165. <Modal
  166. isShow
  167. onClose={() => { }}
  168. wrapperClassName='z-[101]'
  169. className='!p-8 !pb-6 !max-w-none !w-[640px]'
  170. >
  171. <div className='mb-2 text-xl font-semibold text-gray-900'>
  172. {`${action} ${t('appDebug.feature.tools.modal.title')}`}
  173. </div>
  174. <div className='py-2'>
  175. <div className='leading-9 text-sm font-medium text-gray-900'>
  176. {t('appDebug.feature.tools.modal.toolType.title')}
  177. </div>
  178. <SimpleSelect
  179. defaultValue={localeData.type}
  180. items={providers.map((option) => {
  181. return {
  182. value: option.key,
  183. name: option.name,
  184. }
  185. })}
  186. onSelect={item => handleDataTypeChange(item.value as string)}
  187. />
  188. </div>
  189. <div className='py-2'>
  190. <div className='leading-9 text-sm font-medium text-gray-900'>
  191. {t('appDebug.feature.tools.modal.name.title')}
  192. </div>
  193. <div className='flex items-center'>
  194. <input
  195. value={localeData.label || ''}
  196. onChange={e => handleValueChange({ label: e.target.value })}
  197. className='grow block mr-2 px-3 h-9 bg-gray-100 rounded-lg text-sm text-gray-900 outline-none appearance-none'
  198. placeholder={t('appDebug.feature.tools.modal.name.placeholder') || ''}
  199. />
  200. <AppIcon size='large'
  201. onClick={() => { setShowEmojiPicker(true) }}
  202. className='!w-9 !h-9 rounded-lg border-[0.5px] border-black/5 cursor-pointer '
  203. icon={localeData.icon}
  204. background={localeData.icon_background}
  205. />
  206. </div>
  207. </div>
  208. <div className='py-2'>
  209. <div className='leading-9 text-sm font-medium text-gray-900'>
  210. {t('appDebug.feature.tools.modal.variableName.title')}
  211. </div>
  212. <input
  213. value={localeData.variable || ''}
  214. onChange={e => handleValueChange({ variable: e.target.value })}
  215. className='block px-3 w-full h-9 bg-gray-100 rounded-lg text-sm text-gray-900 outline-none appearance-none'
  216. placeholder={t('appDebug.feature.tools.modal.variableName.placeholder') || ''}
  217. />
  218. </div>
  219. {
  220. localeData.type === 'api' && (
  221. <div className='py-2'>
  222. <div className='flex justify-between items-center h-9 text-sm font-medium text-gray-900'>
  223. {t('common.apiBasedExtension.selector.title')}
  224. <a
  225. href={t('common.apiBasedExtension.linkUrl') || '/'}
  226. target='_blank'
  227. className='group flex items-center text-xs font-normal text-gray-500 hover:text-primary-600'
  228. >
  229. <BookOpen01 className='mr-1 w-3 h-3 text-gray-500 group-hover:text-primary-600' />
  230. {t('common.apiBasedExtension.link')}
  231. </a>
  232. </div>
  233. <ApiBasedExtensionSelector
  234. value={localeData.config?.api_based_extension_id || ''}
  235. onChange={handleDataApiBasedChange}
  236. />
  237. </div>
  238. )
  239. }
  240. {
  241. systemTypes.findIndex(t => t === localeData.type) < 0
  242. && currentProvider?.form_schema
  243. && (
  244. <FormGeneration
  245. forms={currentProvider?.form_schema}
  246. value={localeData.config}
  247. onChange={handleDataExtraChange}
  248. />
  249. )
  250. }
  251. <div className='flex items-center justify-end mt-6'>
  252. <Button
  253. onClick={onCancel}
  254. className='mr-2 text-sm font-medium'
  255. >
  256. {t('common.operation.cancel')}
  257. </Button>
  258. <Button
  259. type='primary'
  260. className='text-sm font-medium'
  261. onClick={handleSave}
  262. >
  263. {t('common.operation.save')}
  264. </Button>
  265. </div>
  266. {
  267. showEmojiPicker && (
  268. <EmojiPicker
  269. className='!z-[200]'
  270. onSelect={(icon, icon_background) => {
  271. handleValueChange({ icon, icon_background })
  272. setShowEmojiPicker(false)
  273. }}
  274. onClose={() => {
  275. handleValueChange({ icon: '', icon_background: '' })
  276. setShowEmojiPicker(false)
  277. }}
  278. />
  279. )
  280. }
  281. </Modal>
  282. )
  283. }
  284. export default ExternalDataToolModal