Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

external-data-tool-modal.tsx 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. import { noop } from 'lodash-es'
  23. const systemTypes = ['api']
  24. type ExternalDataToolModalProps = {
  25. data: ExternalDataTool
  26. onCancel: () => void
  27. onSave: (externalDataTool: ExternalDataTool) => void
  28. onValidateBeforeSave?: (externalDataTool: ExternalDataTool) => boolean
  29. }
  30. type Provider = {
  31. key: string
  32. name: string
  33. form_schema?: CodeBasedExtensionItem['form_schema']
  34. }
  35. const ExternalDataToolModal: FC<ExternalDataToolModalProps> = ({
  36. data,
  37. onCancel,
  38. onSave,
  39. onValidateBeforeSave,
  40. }) => {
  41. const { t } = useTranslation()
  42. const { notify } = useToastContext()
  43. const { locale } = useContext(I18n)
  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: locale !== LanguagesSupported[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: locale !== LanguagesSupported[1] ? currentProvider.form_schema[i].label['en-US'] : currentProvider.form_schema[i].label['zh-Hans'] }),
  153. })
  154. return
  155. }
  156. }
  157. }
  158. const formattedData = formatData(localeData)
  159. if (onValidateBeforeSave && !onValidateBeforeSave(formattedData))
  160. return
  161. onSave(formatData(formattedData))
  162. }
  163. const action = data.type ? t('common.operation.edit') : t('common.operation.add')
  164. return (
  165. <Modal
  166. isShow
  167. onClose={noop}
  168. className='!w-[640px] !max-w-none !p-8 !pb-6'
  169. >
  170. <div className='mb-2 text-xl font-semibold text-gray-900'>
  171. {`${action} ${t('appDebug.variableConfig.apiBasedVar')}`}
  172. </div>
  173. <div className='py-2'>
  174. <div className='text-sm font-medium leading-9 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='text-sm font-medium leading-9 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='mr-2 block h-9 grow appearance-none rounded-lg bg-gray-100 px-3 text-sm text-gray-900 outline-none'
  197. placeholder={t('appDebug.feature.tools.modal.name.placeholder') || ''}
  198. />
  199. <AppIcon size='large'
  200. onClick={() => { setShowEmojiPicker(true) }}
  201. className='!h-9 !w-9 cursor-pointer rounded-lg border-[0.5px] border-black/5 '
  202. icon={localeData.icon}
  203. background={localeData.icon_background}
  204. />
  205. </div>
  206. </div>
  207. <div className='py-2'>
  208. <div className='text-sm font-medium leading-9 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 h-9 w-full appearance-none rounded-lg bg-gray-100 px-3 text-sm text-gray-900 outline-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 h-9 items-center justify-between 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 h-3 w-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='mt-6 flex items-center justify-end'>
  251. <Button
  252. onClick={onCancel}
  253. className='mr-2'
  254. >
  255. {t('common.operation.cancel')}
  256. </Button>
  257. <Button
  258. variant='primary'
  259. onClick={handleSave}
  260. >
  261. {t('common.operation.save')}
  262. </Button>
  263. </div>
  264. {
  265. showEmojiPicker && (
  266. <EmojiPicker
  267. onSelect={(icon, icon_background) => {
  268. handleValueChange({ icon, icon_background })
  269. setShowEmojiPicker(false)
  270. }}
  271. onClose={() => {
  272. handleValueChange({ icon: '', icon_background: '' })
  273. setShowEmojiPicker(false)
  274. }}
  275. />
  276. )
  277. }
  278. </Modal>
  279. )
  280. }
  281. export default ExternalDataToolModal