index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import type { FC } from 'react'
  2. import {
  3. memo,
  4. useCallback,
  5. useEffect,
  6. useMemo,
  7. useState,
  8. } from 'react'
  9. import { useTranslation } from 'react-i18next'
  10. import type {
  11. CredentialFormSchema,
  12. CredentialFormSchemaRadio,
  13. CredentialFormSchemaSelect,
  14. CustomConfigrationModelFixedFields,
  15. FormValue,
  16. ModelProvider,
  17. } from '../declarations'
  18. import {
  19. ConfigurateMethodEnum,
  20. CustomConfigurationStatusEnum,
  21. FormTypeEnum,
  22. } from '../declarations'
  23. import {
  24. genModelNameFormSchema,
  25. genModelTypeFormSchema,
  26. removeCredentials,
  27. saveCredentials,
  28. } from '../utils'
  29. import {
  30. useLanguage,
  31. useProviderCrenditialsFormSchemasValue,
  32. } from '../hooks'
  33. import ProviderIcon from '../provider-icon'
  34. import { useValidate } from '../../key-validator/hooks'
  35. import { ValidatedStatus } from '../../key-validator/declarations'
  36. import Form from './Form'
  37. import Button from '@/app/components/base/button'
  38. import { Lock01 } from '@/app/components/base/icons/src/vender/solid/security'
  39. import { LinkExternal02 } from '@/app/components/base/icons/src/vender/line/general'
  40. import { AlertCircle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'
  41. import {
  42. PortalToFollowElem,
  43. PortalToFollowElemContent,
  44. } from '@/app/components/base/portal-to-follow-elem'
  45. import { useToastContext } from '@/app/components/base/toast'
  46. import ConfirmCommon from '@/app/components/base/confirm/common'
  47. type ModelModalProps = {
  48. provider: ModelProvider
  49. configurateMethod: ConfigurateMethodEnum
  50. currentCustomConfigrationModelFixedFields?: CustomConfigrationModelFixedFields
  51. onCancel: () => void
  52. onSave: () => void
  53. }
  54. const ModelModal: FC<ModelModalProps> = ({
  55. provider,
  56. configurateMethod,
  57. currentCustomConfigrationModelFixedFields,
  58. onCancel,
  59. onSave,
  60. }) => {
  61. const providerFormSchemaPredefined = configurateMethod === ConfigurateMethodEnum.predefinedModel
  62. const formSchemasValue = useProviderCrenditialsFormSchemasValue(
  63. provider.provider,
  64. configurateMethod,
  65. providerFormSchemaPredefined && provider.custom_configuration.status === CustomConfigurationStatusEnum.active,
  66. currentCustomConfigrationModelFixedFields,
  67. )
  68. const isEditMode = !!formSchemasValue
  69. const { t } = useTranslation()
  70. const { notify } = useToastContext()
  71. const language = useLanguage()
  72. const [loading, setLoading] = useState(false)
  73. const [showConfirm, setShowConfirm] = useState(false)
  74. const formSchemas = useMemo(() => {
  75. return providerFormSchemaPredefined
  76. ? provider.provider_credential_schema.credential_form_schemas
  77. : [
  78. genModelTypeFormSchema(provider.supported_model_types),
  79. genModelNameFormSchema(provider.model_credential_schema?.model),
  80. ...provider.model_credential_schema.credential_form_schemas,
  81. ]
  82. }, [
  83. providerFormSchemaPredefined,
  84. provider.provider_credential_schema?.credential_form_schemas,
  85. provider.supported_model_types,
  86. provider.model_credential_schema?.credential_form_schemas,
  87. provider.model_credential_schema?.model,
  88. ])
  89. const [
  90. requiredFormSchemas,
  91. secretFormSchemas,
  92. defaultFormSchemaValue,
  93. showOnVariableMap,
  94. ] = useMemo(() => {
  95. const requiredFormSchemas: CredentialFormSchema[] = []
  96. const secretFormSchemas: CredentialFormSchema[] = []
  97. const defaultFormSchemaValue: Record<string, string | number> = {}
  98. const showOnVariableMap: Record<string, string[]> = {}
  99. formSchemas.forEach((formSchema) => {
  100. if (formSchema.required)
  101. requiredFormSchemas.push(formSchema)
  102. if (formSchema.type === FormTypeEnum.secretInput)
  103. secretFormSchemas.push(formSchema)
  104. if (formSchema.default)
  105. defaultFormSchemaValue[formSchema.variable] = formSchema.default
  106. if (formSchema.show_on.length) {
  107. formSchema.show_on.forEach((showOnItem) => {
  108. if (!showOnVariableMap[showOnItem.variable])
  109. showOnVariableMap[showOnItem.variable] = []
  110. if (!showOnVariableMap[showOnItem.variable].includes(formSchema.variable))
  111. showOnVariableMap[showOnItem.variable].push(formSchema.variable)
  112. })
  113. }
  114. if (formSchema.type === FormTypeEnum.select || formSchema.type === FormTypeEnum.radio) {
  115. (formSchema as (CredentialFormSchemaRadio | CredentialFormSchemaSelect)).options.forEach((option) => {
  116. if (option.show_on.length) {
  117. option.show_on.forEach((showOnItem) => {
  118. if (!showOnVariableMap[showOnItem.variable])
  119. showOnVariableMap[showOnItem.variable] = []
  120. if (!showOnVariableMap[showOnItem.variable].includes(formSchema.variable))
  121. showOnVariableMap[showOnItem.variable].push(formSchema.variable)
  122. })
  123. }
  124. })
  125. }
  126. })
  127. return [
  128. requiredFormSchemas,
  129. secretFormSchemas,
  130. defaultFormSchemaValue,
  131. showOnVariableMap,
  132. ]
  133. }, [formSchemas])
  134. const initialFormSchemasValue = useMemo(() => {
  135. return {
  136. ...defaultFormSchemaValue,
  137. ...formSchemasValue,
  138. }
  139. }, [formSchemasValue, defaultFormSchemaValue])
  140. const [value, setValue] = useState(initialFormSchemasValue)
  141. useEffect(() => {
  142. setValue(initialFormSchemasValue)
  143. }, [initialFormSchemasValue])
  144. const [validate, validating, validatedStatusState] = useValidate(value)
  145. const filteredRequiredFormSchemas = requiredFormSchemas.filter((requiredFormSchema) => {
  146. if (requiredFormSchema.show_on.length && requiredFormSchema.show_on.every(showOnItem => value[showOnItem.variable] === showOnItem.value))
  147. return true
  148. if (!requiredFormSchema.show_on.length)
  149. return true
  150. return false
  151. })
  152. const getSecretValues = useCallback((v: FormValue) => {
  153. return secretFormSchemas.reduce((prev, next) => {
  154. if (v[next.variable] === initialFormSchemasValue[next.variable])
  155. prev[next.variable] = '[__HIDDEN__]'
  156. return prev
  157. }, {} as Record<string, string>)
  158. }, [initialFormSchemasValue, secretFormSchemas])
  159. const handleValueChange = (v: FormValue) => {
  160. setValue(v)
  161. }
  162. const handleSave = async () => {
  163. try {
  164. setLoading(true)
  165. const res = await saveCredentials(
  166. providerFormSchemaPredefined,
  167. provider.provider,
  168. {
  169. ...value,
  170. ...getSecretValues(value),
  171. },
  172. )
  173. if (res.result === 'success') {
  174. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  175. onSave()
  176. onCancel()
  177. }
  178. }
  179. finally {
  180. setLoading(false)
  181. }
  182. }
  183. const handleRemove = async () => {
  184. try {
  185. setLoading(true)
  186. const res = await removeCredentials(
  187. providerFormSchemaPredefined,
  188. provider.provider,
  189. value,
  190. )
  191. if (res.result === 'success') {
  192. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  193. onSave()
  194. onCancel()
  195. }
  196. }
  197. finally {
  198. setLoading(false)
  199. }
  200. }
  201. const renderTitlePrefix = () => {
  202. const prefix = configurateMethod === ConfigurateMethodEnum.customizableModel ? t('common.operation.add') : t('common.operation.setup')
  203. return `${prefix} ${provider.label[language]}`
  204. }
  205. return (
  206. <PortalToFollowElem open>
  207. <PortalToFollowElemContent className='w-full h-full z-[60]'>
  208. <div className='fixed inset-0 flex items-center justify-center bg-black/[.25]'>
  209. <div className='mx-2 w-[640px] max-h-[calc(100vh-120px)] bg-white shadow-xl rounded-2xl overflow-y-auto'>
  210. <div className='px-8 pt-8'>
  211. <div className='flex justify-between items-center mb-2'>
  212. <div className='text-xl font-semibold text-gray-900'>{renderTitlePrefix()}</div>
  213. <ProviderIcon provider={provider} />
  214. </div>
  215. <Form
  216. value={value}
  217. onChange={handleValueChange}
  218. formSchemas={formSchemas}
  219. validating={validating}
  220. validatedSuccess={validatedStatusState.status === ValidatedStatus.Success}
  221. showOnVariableMap={showOnVariableMap}
  222. isEditMode={isEditMode}
  223. />
  224. <div className='sticky bottom-0 flex justify-between items-center py-6 flex-wrap gap-y-2 bg-white'>
  225. {
  226. (provider.help && (provider.help.title || provider.help.url))
  227. ? (
  228. <a
  229. href={provider.help?.url[language]}
  230. target='_blank'
  231. className='inline-flex items-center text-xs text-primary-600'
  232. onClick={e => !provider.help.url && e.preventDefault()}
  233. >
  234. {provider.help.title?.[language] || provider.help.url[language]}
  235. <LinkExternal02 className='ml-1 w-3 h-3' />
  236. </a>
  237. )
  238. : <div />
  239. }
  240. <div>
  241. {
  242. isEditMode && (
  243. <Button
  244. className='mr-2 h-9 text-sm font-medium text-[#D92D20]'
  245. onClick={() => setShowConfirm(true)}
  246. >
  247. {t('common.operation.remove')}
  248. </Button>
  249. )
  250. }
  251. <Button
  252. className='mr-2 h-9 text-sm font-medium text-gray-700'
  253. onClick={onCancel}
  254. >
  255. {t('common.operation.cancel')}
  256. </Button>
  257. <Button
  258. className='h-9 text-sm font-medium'
  259. type='primary'
  260. onClick={handleSave}
  261. disabled={loading || filteredRequiredFormSchemas.some(item => value[item.variable] === undefined)}
  262. >
  263. {t('common.operation.save')}
  264. </Button>
  265. </div>
  266. </div>
  267. </div>
  268. <div className='border-t-[0.5px] border-t-black/5'>
  269. {
  270. (validatedStatusState.status === ValidatedStatus.Error && validatedStatusState.message)
  271. ? (
  272. <div className='flex px-[10px] py-3 bg-[#FEF3F2] text-xs text-[#D92D20]'>
  273. <AlertCircle className='mt-[1px] mr-2 w-[14px] h-[14px]' />
  274. {validatedStatusState.message}
  275. </div>
  276. )
  277. : (
  278. <div className='flex justify-center items-center py-3 bg-gray-50 text-xs text-gray-500'>
  279. <Lock01 className='mr-1 w-3 h-3 text-gray-500' />
  280. {t('common.modelProvider.encrypted.front')}
  281. <a
  282. className='text-primary-600 mx-1'
  283. target={'_blank'}
  284. href='https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html'
  285. >
  286. PKCS1_OAEP
  287. </a>
  288. {t('common.modelProvider.encrypted.back')}
  289. </div>
  290. )
  291. }
  292. </div>
  293. </div>
  294. {
  295. showConfirm && (
  296. <ConfirmCommon
  297. title={t('common.modelProvider.confirmDelete')}
  298. isShow={showConfirm}
  299. onCancel={() => setShowConfirm(false)}
  300. onConfirm={handleRemove}
  301. confirmWrapperClassName='z-[70]'
  302. />
  303. )
  304. }
  305. </div>
  306. </PortalToFollowElemContent>
  307. </PortalToFollowElem>
  308. )
  309. }
  310. export default memo(ModelModal)