external-data-tool-modal.tsx 10 KB

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