external-data-tool-modal.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 { 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 formatedData = formatData(localeData)
  158. if (onValidateBeforeSave && !onValidateBeforeSave(formatedData))
  159. return
  160. onSave(formatData(formatedData))
  161. }
  162. const action = data.type ? t('common.operation.edit') : t('common.operation.add')
  163. return (
  164. <Modal
  165. isShow
  166. onClose={() => { }}
  167. wrapperClassName='z-[101]'
  168. className='!p-8 !pb-6 !max-w-none !w-[640px]'
  169. >
  170. <div className='mb-2 text-xl font-semibold text-gray-900'>
  171. {`${action} ${t('appDebug.variableConig.apiBasedVar')}`}
  172. </div>
  173. <div className='py-2'>
  174. <div className='leading-9 text-sm font-medium text-gray-900'>
  175. {t('common.apiBasedExtension.type')}
  176. </div>
  177. <SimpleSelect
  178. defaultValue={localeData.type}
  179. items={providers.map((option) => {
  180. return {
  181. value: option.key,
  182. name: option.name,
  183. }
  184. })}
  185. onSelect={item => handleDataTypeChange(item.value as string)}
  186. />
  187. </div>
  188. <div className='py-2'>
  189. <div className='leading-9 text-sm font-medium text-gray-900'>
  190. {t('appDebug.feature.tools.modal.name.title')}
  191. </div>
  192. <div className='flex items-center'>
  193. <input
  194. value={localeData.label || ''}
  195. onChange={e => handleValueChange({ label: e.target.value })}
  196. className='grow block mr-2 px-3 h-9 bg-gray-100 rounded-lg text-sm text-gray-900 outline-none appearance-none'
  197. placeholder={t('appDebug.feature.tools.modal.name.placeholder') || ''}
  198. />
  199. <AppIcon size='large'
  200. onClick={() => { setShowEmojiPicker(true) }}
  201. className='!w-9 !h-9 rounded-lg border-[0.5px] border-black/5 cursor-pointer '
  202. icon={localeData.icon}
  203. background={localeData.icon_background}
  204. />
  205. </div>
  206. </div>
  207. <div className='py-2'>
  208. <div className='leading-9 text-sm font-medium text-gray-900'>
  209. {t('appDebug.feature.tools.modal.variableName.title')}
  210. </div>
  211. <input
  212. value={localeData.variable || ''}
  213. onChange={e => handleValueChange({ variable: e.target.value })}
  214. className='block px-3 w-full h-9 bg-gray-100 rounded-lg text-sm text-gray-900 outline-none appearance-none'
  215. placeholder={t('appDebug.feature.tools.modal.variableName.placeholder') || ''}
  216. />
  217. </div>
  218. {
  219. localeData.type === 'api' && (
  220. <div className='py-2'>
  221. <div className='flex justify-between items-center h-9 text-sm font-medium text-gray-900'>
  222. {t('common.apiBasedExtension.selector.title')}
  223. <a
  224. href={t('common.apiBasedExtension.linkUrl') || '/'}
  225. target='_blank' rel='noopener noreferrer'
  226. className='group flex items-center text-xs font-normal text-gray-500 hover:text-primary-600'
  227. >
  228. <BookOpen01 className='mr-1 w-3 h-3 text-gray-500 group-hover:text-primary-600' />
  229. {t('common.apiBasedExtension.link')}
  230. </a>
  231. </div>
  232. <ApiBasedExtensionSelector
  233. value={localeData.config?.api_based_extension_id || ''}
  234. onChange={handleDataApiBasedChange}
  235. />
  236. </div>
  237. )
  238. }
  239. {
  240. systemTypes.findIndex(t => t === localeData.type) < 0
  241. && currentProvider?.form_schema
  242. && (
  243. <FormGeneration
  244. forms={currentProvider?.form_schema}
  245. value={localeData.config}
  246. onChange={handleDataExtraChange}
  247. />
  248. )
  249. }
  250. <div className='flex items-center justify-end mt-6'>
  251. <Button
  252. onClick={onCancel}
  253. className='mr-2 text-sm font-medium'
  254. >
  255. {t('common.operation.cancel')}
  256. </Button>
  257. <Button
  258. type='primary'
  259. className='text-sm font-medium'
  260. onClick={handleSave}
  261. >
  262. {t('common.operation.save')}
  263. </Button>
  264. </div>
  265. {
  266. showEmojiPicker && (
  267. <EmojiPicker
  268. className='!z-[200]'
  269. onSelect={(icon, icon_background) => {
  270. handleValueChange({ icon, icon_background })
  271. setShowEmojiPicker(false)
  272. }}
  273. onClose={() => {
  274. handleValueChange({ icon: '', icon_background: '' })
  275. setShowEmojiPicker(false)
  276. }}
  277. />
  278. )
  279. }
  280. </Modal>
  281. )
  282. }
  283. export default ExternalDataToolModal