feat: frontend multi models support (#804)
Co-authored-by: StyleZhang <jasonapring2015@outlook.com> Co-authored-by: Joel <iamjoel007@gmail.com>
This commit is contained in:
@@ -0,0 +1,177 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { Dispatch, FC, SetStateAction } from 'react'
|
||||
import { useContext } from 'use-context-selector'
|
||||
import type { Field, FormValue, ProviderConfigModal } from '../declarations'
|
||||
import { useValidate } from '../../key-validator/hooks'
|
||||
import { ValidatingTip } from '../../key-validator/ValidateStatus'
|
||||
import { validateModelProviderFn } from '../utils'
|
||||
import Input from './Input'
|
||||
import I18n from '@/context/i18n'
|
||||
import { SimpleSelect } from '@/app/components/base/select'
|
||||
|
||||
type FormProps = {
|
||||
modelModal?: ProviderConfigModal
|
||||
initValue?: FormValue
|
||||
fields: Field[]
|
||||
onChange: (v: FormValue) => void
|
||||
onValidatedError: (v: string) => void
|
||||
mode: string
|
||||
cleared: boolean
|
||||
onClearedChange: Dispatch<SetStateAction<boolean>>
|
||||
onValidating: (validating: boolean) => void
|
||||
}
|
||||
|
||||
const nameClassName = `
|
||||
py-2 text-sm text-gray-900
|
||||
`
|
||||
|
||||
const Form: FC<FormProps> = ({
|
||||
modelModal,
|
||||
initValue = {},
|
||||
fields,
|
||||
onChange,
|
||||
onValidatedError,
|
||||
mode,
|
||||
cleared,
|
||||
onClearedChange,
|
||||
onValidating,
|
||||
}) => {
|
||||
const { locale } = useContext(I18n)
|
||||
const [value, setValue] = useState(initValue)
|
||||
const [validate, validating, validatedStatusState] = useValidate(value)
|
||||
const [changeKey, setChangeKey] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
onValidatedError(validatedStatusState.message || '')
|
||||
}, [validatedStatusState, onValidatedError])
|
||||
useEffect(() => {
|
||||
onValidating(validating)
|
||||
}, [validating, onValidating])
|
||||
|
||||
const updateValue = (v: FormValue) => {
|
||||
setValue(v)
|
||||
onChange(v)
|
||||
}
|
||||
|
||||
const handleMultiFormChange = (v: FormValue, newChangeKey: string) => {
|
||||
updateValue(v)
|
||||
setChangeKey(newChangeKey)
|
||||
|
||||
const validateKeys = (typeof modelModal?.validateKeys === 'function' ? modelModal?.validateKeys(v) : modelModal?.validateKeys) || []
|
||||
if (validateKeys.length) {
|
||||
validate({
|
||||
before: () => {
|
||||
for (let i = 0; i < validateKeys.length; i++) {
|
||||
if (!v[validateKeys[i]])
|
||||
return false
|
||||
}
|
||||
return true
|
||||
},
|
||||
run: () => {
|
||||
return validateModelProviderFn(modelModal!.key, v)
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleClear = (saveValue?: FormValue) => {
|
||||
const needClearFields = modelModal?.fields.filter(field => field.type !== 'radio')
|
||||
const newValue: Record<string, string> = {}
|
||||
needClearFields?.forEach((field) => {
|
||||
newValue[field.key] = ''
|
||||
})
|
||||
updateValue({ ...value, ...newValue, ...saveValue })
|
||||
onClearedChange(true)
|
||||
}
|
||||
|
||||
const handleFormChange = (k: string, v: string) => {
|
||||
if (mode === 'edit' && !cleared)
|
||||
handleClear({ [k]: v })
|
||||
else
|
||||
handleMultiFormChange({ ...value, [k]: v }, k)
|
||||
}
|
||||
|
||||
const handleFocus = () => {
|
||||
if (mode === 'edit' && !cleared)
|
||||
handleClear()
|
||||
}
|
||||
|
||||
const renderField = (field: Field) => {
|
||||
const hidden = typeof field.hidden === 'function' ? field.hidden(value) : field.hidden
|
||||
|
||||
if (hidden)
|
||||
return null
|
||||
|
||||
if (field.type === 'text') {
|
||||
return (
|
||||
<div key={field.key} className='py-3'>
|
||||
<div className={nameClassName}>{field.label[locale]}</div>
|
||||
<Input
|
||||
field={field}
|
||||
value={value}
|
||||
onChange={v => handleMultiFormChange(v, field.key)}
|
||||
onFocus={handleFocus}
|
||||
validatedStatusState={validatedStatusState}
|
||||
/>
|
||||
{validating && changeKey === field.key && <ValidatingTip />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (field.type === 'radio') {
|
||||
const options = typeof field.options === 'function' ? field.options(value) : field.options
|
||||
return (
|
||||
<div key={field.key} className='py-3'>
|
||||
<div className={nameClassName}>{field.label[locale]}</div>
|
||||
<div className='grid grid-cols-2 gap-3'>
|
||||
{
|
||||
options?.map(option => (
|
||||
<div
|
||||
className={`
|
||||
flex items-center px-3 h-9 rounded-lg border border-gray-100 bg-gray-25 cursor-pointer
|
||||
${value?.[field.key] === option.key && 'bg-white border-[1.5px] border-primary-400 shadow-sm'}
|
||||
`}
|
||||
onClick={() => handleFormChange(field.key, option.key)}
|
||||
key={`${field.key}-${option.key}`}
|
||||
>
|
||||
<div className={`
|
||||
flex justify-center items-center mr-2 w-4 h-4 border border-gray-300 rounded-full
|
||||
${value?.[field.key] === option.key && 'border-[5px] border-primary-600'}
|
||||
`} />
|
||||
<div className='text-sm text-gray-900'>{option.label[locale]}</div>
|
||||
</div>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
{validating && changeKey === field.key && <ValidatingTip />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (field.type === 'select') {
|
||||
const options = typeof field.options === 'function' ? field.options(value) : field.options
|
||||
|
||||
return (
|
||||
<div key={field.key} className='py-3'>
|
||||
<div className={nameClassName}>{field.label[locale]}</div>
|
||||
<SimpleSelect
|
||||
defaultValue={value[field.key]}
|
||||
items={options!.map(option => ({ value: option.key, name: option.label[locale] }))}
|
||||
onSelect={item => handleFormChange(field.key, item.value as string)}
|
||||
/>
|
||||
{validating && changeKey === field.key && <ValidatingTip />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{
|
||||
fields.map(field => renderField(field))
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Form
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { FC } from 'react'
|
||||
import { useContext } from 'use-context-selector'
|
||||
import type { Field, FormValue } from '../declarations'
|
||||
import { ValidatedSuccessIcon } from '../../key-validator/ValidateStatus'
|
||||
import { ValidatedStatus } from '../../key-validator/declarations'
|
||||
import type { ValidatedStatusState } from '../../key-validator/declarations'
|
||||
import I18n from '@/context/i18n'
|
||||
|
||||
type InputProps = {
|
||||
field: Field
|
||||
value: FormValue
|
||||
onChange: (v: FormValue) => void
|
||||
onFocus: () => void
|
||||
validatedStatusState: ValidatedStatusState
|
||||
}
|
||||
const Input: FC<InputProps> = ({
|
||||
field,
|
||||
value,
|
||||
onChange,
|
||||
onFocus,
|
||||
validatedStatusState,
|
||||
}) => {
|
||||
const { locale } = useContext(I18n)
|
||||
const showValidatedIcon = validatedStatusState.status === ValidatedStatus.Success && value[field.key]
|
||||
|
||||
const getValidatedIcon = () => {
|
||||
if (showValidatedIcon)
|
||||
return <div className='absolute top-2.5 right-2.5'><ValidatedSuccessIcon /></div>
|
||||
}
|
||||
|
||||
const handleChange = (v: string) => {
|
||||
const newFormValue = { ...value, [field.key]: v }
|
||||
onChange(newFormValue)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='relative'>
|
||||
<input
|
||||
tabIndex={-1}
|
||||
className={`
|
||||
block px-3 w-full h-9 bg-gray-100 text-sm rounded-lg border border-transparent
|
||||
appearance-none outline-none caret-primary-600
|
||||
hover:border-[rgba(0,0,0,0.08)] hover:bg-gray-50
|
||||
focus:bg-white focus:border-gray-300 focus:shadow-xs
|
||||
placeholder:text-sm placeholder:text-gray-400
|
||||
${showValidatedIcon && 'pr-[30px]'}
|
||||
`}
|
||||
placeholder={field?.placeholder?.[locale] || ''}
|
||||
onChange={e => handleChange(e.target.value)}
|
||||
onFocus={onFocus}
|
||||
value={value[field.key] || ''}
|
||||
/>
|
||||
{getValidatedIcon()}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Input
|
||||
@@ -0,0 +1,165 @@
|
||||
import { useCallback, useState } from 'react'
|
||||
import type { FC } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useContext } from 'use-context-selector'
|
||||
import { Portal } from '@headlessui/react'
|
||||
import type { FormValue, ProviderConfigModal } from '../declarations'
|
||||
import { ConfigurableProviders } from '../utils'
|
||||
import Form from './Form'
|
||||
import I18n from '@/context/i18n'
|
||||
import Button from '@/app/components/base/button'
|
||||
import { Lock01 } from '@/app/components/base/icons/src/vender/solid/security'
|
||||
import { LinkExternal02 } from '@/app/components/base/icons/src/vender/line/general'
|
||||
import { AlertCircle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'
|
||||
import { useEventEmitterContextContext } from '@/context/event-emitter'
|
||||
|
||||
type ModelModalProps = {
|
||||
isShow: boolean
|
||||
onCancel: () => void
|
||||
modelModal?: ProviderConfigModal
|
||||
onSave: (v?: FormValue) => void
|
||||
mode: string
|
||||
}
|
||||
|
||||
const ModelModal: FC<ModelModalProps> = ({
|
||||
isShow,
|
||||
onCancel,
|
||||
modelModal,
|
||||
onSave,
|
||||
mode,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const { locale } = useContext(I18n)
|
||||
const { eventEmitter } = useEventEmitterContextContext()
|
||||
const [value, setValue] = useState<FormValue | undefined>()
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [errorMessage, setErrorMessage] = useState('')
|
||||
const [cleared, setCleared] = useState(false)
|
||||
const [prevIsShow, setPrevIsShow] = useState(isShow)
|
||||
const [validating, setValidating] = useState(false)
|
||||
|
||||
if (prevIsShow !== isShow) {
|
||||
setCleared(false)
|
||||
setPrevIsShow(isShow)
|
||||
}
|
||||
|
||||
eventEmitter?.useSubscription((v) => {
|
||||
if (v === 'provider-save')
|
||||
setLoading(true)
|
||||
else
|
||||
setLoading(false)
|
||||
})
|
||||
const handleValidatedError = useCallback((newErrorMessage: string) => {
|
||||
setErrorMessage(newErrorMessage)
|
||||
}, [])
|
||||
const handleValidating = useCallback((newValidating: boolean) => {
|
||||
setValidating(newValidating)
|
||||
}, [])
|
||||
const validateRequiredValue = () => {
|
||||
const validateValue = value || modelModal?.defaultValue
|
||||
if (modelModal) {
|
||||
const { fields } = modelModal
|
||||
const requiredFields = fields.filter(field => !(typeof field.hidden === 'function' ? field.hidden(validateValue) : field.hidden) && field.required)
|
||||
|
||||
for (let i = 0; i < requiredFields.length; i++) {
|
||||
const currentField = requiredFields[i]
|
||||
if (!validateValue?.[currentField.key]) {
|
||||
setErrorMessage(t('appDebug.errorMessage.valueOfVarRequired', { key: currentField.label[locale] }) || '')
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
const handleSave = () => {
|
||||
if (validateRequiredValue())
|
||||
onSave(value || modelModal?.defaultValue)
|
||||
}
|
||||
|
||||
const renderTitlePrefix = () => {
|
||||
let prefix
|
||||
if (mode === 'edit')
|
||||
prefix = t('common.operation.edit')
|
||||
else
|
||||
prefix = ConfigurableProviders.includes(modelModal!.key) ? t('common.operation.create') : t('common.operation.setup')
|
||||
|
||||
return `${prefix} ${modelModal?.title[locale]}`
|
||||
}
|
||||
|
||||
if (!isShow)
|
||||
return null
|
||||
|
||||
return (
|
||||
<Portal>
|
||||
<div className='fixed inset-0 flex items-center justify-center bg-black/[.25]'>
|
||||
<div className='w-[640px] max-h-screen bg-white shadow-xl rounded-2xl overflow-y-auto'>
|
||||
<div className='px-8 pt-8'>
|
||||
<div className='flex justify-between items-center mb-2'>
|
||||
<div className='text-xl font-semibold text-gray-900'>{renderTitlePrefix()}</div>
|
||||
{modelModal?.icon}
|
||||
</div>
|
||||
<Form
|
||||
modelModal={modelModal}
|
||||
fields={modelModal?.fields || []}
|
||||
initValue={modelModal?.defaultValue}
|
||||
onChange={newValue => setValue(newValue)}
|
||||
onValidatedError={handleValidatedError}
|
||||
mode={mode}
|
||||
cleared={cleared}
|
||||
onClearedChange={setCleared}
|
||||
onValidating={handleValidating}
|
||||
/>
|
||||
<div className='flex justify-between items-center py-6'>
|
||||
<a
|
||||
href={modelModal?.link.href}
|
||||
target='_blank'
|
||||
className='inline-flex items-center text-xs text-primary-600'
|
||||
>
|
||||
{modelModal?.link.label[locale]}
|
||||
<LinkExternal02 className='ml-1 w-3 h-3' />
|
||||
</a>
|
||||
<div>
|
||||
<Button className='mr-2 !h-9 !text-sm font-medium text-gray-700' onClick={onCancel}>{t('common.operation.cancel')}</Button>
|
||||
<Button
|
||||
className='!h-9 !text-sm font-medium'
|
||||
type='primary'
|
||||
onClick={handleSave}
|
||||
disabled={loading || (mode === 'edit' && !cleared) || validating}
|
||||
>
|
||||
{t('common.operation.save')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className='border-t-[0.5px] border-t-[rgba(0,0,0,0.05)]'>
|
||||
{
|
||||
errorMessage
|
||||
? (
|
||||
<div className='flex px-[10px] py-3 bg-[#FEF3F2] text-xs text-[#D92D20]'>
|
||||
<AlertCircle className='mt-[1px] mr-2 w-[14px] h-[14px]' />
|
||||
{errorMessage}
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
<div className='flex justify-center items-center py-3 bg-gray-50 text-xs text-gray-500'>
|
||||
<Lock01 className='mr-1 w-3 h-3 text-gray-500' />
|
||||
{t('common.modelProvider.encrypted.front')}
|
||||
<a
|
||||
className='text-primary-600 mx-1'
|
||||
target={'_blank'}
|
||||
href='https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html'
|
||||
>
|
||||
PKCS1_OAEP
|
||||
</a>
|
||||
{t('common.modelProvider.encrypted.back')}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export default ModelModal
|
||||
Reference in New Issue
Block a user