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 type {
  16. CodeBasedExtensionItem,
  17. ExternalDataTool,
  18. } from '@/models/common'
  19. import { useToastContext } from '@/app/components/base/toast'
  20. import AppIcon from '@/app/components/base/app-icon'
  21. const systemTypes = ['api']
  22. type ExternalDataToolModalProps = {
  23. data: ExternalDataTool
  24. onCancel: () => void
  25. onSave: (externalDataTool: ExternalDataTool) => void
  26. onValidateBeforeSave?: (externalDataTool: ExternalDataTool) => boolean
  27. }
  28. type Provider = {
  29. key: string
  30. name: string
  31. form_schema?: CodeBasedExtensionItem['form_schema']
  32. }
  33. const ExternalDataToolModal: FC<ExternalDataToolModalProps> = ({
  34. data,
  35. onCancel,
  36. onSave,
  37. onValidateBeforeSave,
  38. }) => {
  39. const { t } = useTranslation()
  40. const { notify } = useToastContext()
  41. const { locale } = useContext(I18n)
  42. const [localeData, setLocaleData] = useState(data.type ? data : { ...data, type: 'api' })
  43. const [showEmojiPicker, setShowEmojiPicker] = useState(false)
  44. const { data: codeBasedExtensionList } = useSWR(
  45. '/code-based-extension?module=external_data_tool',
  46. fetchCodeBasedExtensionList,
  47. )
  48. const providers: Provider[] = [
  49. {
  50. key: 'api',
  51. name: t('common.apiBasedExtension.selector.title'),
  52. },
  53. ...(
  54. codeBasedExtensionList
  55. ? codeBasedExtensionList.data.map((item) => {
  56. return {
  57. key: item.name,
  58. name: locale === 'zh-Hans' ? item.label['zh-Hans'] : item.label['en-US'],
  59. form_schema: item.form_schema,
  60. }
  61. })
  62. : []
  63. ),
  64. ]
  65. const currentProvider = providers.find(provider => provider.key === localeData.type)
  66. const handleDataTypeChange = (type: string) => {
  67. let config: undefined | Record<string, any>
  68. const currProvider = providers.find(provider => provider.key === type)
  69. if (systemTypes.findIndex(t => t === type) < 0 && currProvider?.form_schema) {
  70. config = currProvider?.form_schema.reduce((prev, next) => {
  71. prev[next.variable] = next.default
  72. return prev
  73. }, {} as Record<string, any>)
  74. }
  75. setLocaleData({
  76. ...localeData,
  77. type,
  78. config,
  79. })
  80. }
  81. const handleDataExtraChange = (extraValue: Record<string, string>) => {
  82. setLocaleData({
  83. ...localeData,
  84. config: {
  85. ...localeData.config,
  86. ...extraValue,
  87. },
  88. })
  89. }
  90. const handleValueChange = (value: Record<string, string>) => {
  91. setLocaleData({
  92. ...localeData,
  93. ...value,
  94. })
  95. }
  96. const handleDataApiBasedChange = (apiBasedExtensionId: string) => {
  97. setLocaleData({
  98. ...localeData,
  99. config: {
  100. ...localeData.config,
  101. api_based_extension_id: apiBasedExtensionId,
  102. },
  103. })
  104. }
  105. const formatData = (originData: ExternalDataTool) => {
  106. const { type, config } = originData
  107. const params: Record<string, string | undefined> = {}
  108. if (type === 'api')
  109. params.api_based_extension_id = config?.api_based_extension_id
  110. if (systemTypes.findIndex(t => t === type) < 0 && currentProvider?.form_schema) {
  111. currentProvider.form_schema.forEach((form) => {
  112. params[form.variable] = config?.[form.variable]
  113. })
  114. }
  115. return {
  116. ...originData,
  117. type,
  118. enabled: data.type ? data.enabled : true,
  119. config: {
  120. ...params,
  121. },
  122. }
  123. }
  124. const handleSave = () => {
  125. if (!localeData.type) {
  126. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: t('appDebug.feature.tools.modal.toolType.title') }) })
  127. return
  128. }
  129. if (!localeData.label) {
  130. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: t('appDebug.feature.tools.modal.name.title') }) })
  131. return
  132. }
  133. if (!localeData.variable) {
  134. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: t('appDebug.feature.tools.modal.variableName.title') }) })
  135. return
  136. }
  137. if (localeData.variable && !/[a-zA-Z_][a-zA-Z0-9_]{0,29}/g.test(localeData.variable)) {
  138. notify({ type: 'error', message: t('appDebug.varKeyError.notValid', { key: t('appDebug.feature.tools.modal.variableName.title') }) })
  139. return
  140. }
  141. if (localeData.type === 'api' && !localeData.config?.api_based_extension_id) {
  142. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: locale === 'en' ? 'API Extension' : 'API 扩展' }) })
  143. return
  144. }
  145. if (systemTypes.findIndex(t => t === localeData.type) < 0 && currentProvider?.form_schema) {
  146. for (let i = 0; i < currentProvider.form_schema.length; i++) {
  147. if (!localeData.config?.[currentProvider.form_schema[i].variable] && currentProvider.form_schema[i].required) {
  148. notify({
  149. type: 'error',
  150. message: t('appDebug.errorMessage.valueOfVarRequired', { key: locale === 'en' ? currentProvider.form_schema[i].label['en-US'] : currentProvider.form_schema[i].label['zh-Hans'] }),
  151. })
  152. return
  153. }
  154. }
  155. }
  156. const formatedData = formatData(localeData)
  157. if (onValidateBeforeSave && !onValidateBeforeSave(formatedData))
  158. return
  159. onSave(formatData(formatedData))
  160. }
  161. const action = data.type ? t('common.operation.edit') : t('common.operation.add')
  162. return (
  163. <Modal
  164. isShow
  165. onClose={() => { }}
  166. wrapperClassName='z-[101]'
  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.feature.tools.modal.title')}`}
  171. </div>
  172. <div className='py-2'>
  173. <div className='leading-9 text-sm font-medium text-gray-900'>
  174. {t('appDebug.feature.tools.modal.toolType.title')}
  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'
  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 text-sm font-medium'
  253. >
  254. {t('common.operation.cancel')}
  255. </Button>
  256. <Button
  257. type='primary'
  258. className='text-sm font-medium'
  259. onClick={handleSave}
  260. >
  261. {t('common.operation.save')}
  262. </Button>
  263. </div>
  264. {
  265. showEmojiPicker && (
  266. <EmojiPicker
  267. className='!z-[200]'
  268. onSelect={(icon, icon_background) => {
  269. handleValueChange({ icon, icon_background })
  270. setShowEmojiPicker(false)
  271. }}
  272. onClose={() => {
  273. handleValueChange({ icon: '', icon_background: '' })
  274. setShowEmojiPicker(false)
  275. }}
  276. />
  277. )
  278. }
  279. </Modal>
  280. )
  281. }
  282. export default ExternalDataToolModal