index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useState } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import { Cog8ToothIcon, TrashIcon } from '@heroicons/react/24/outline'
  6. import { useBoolean } from 'ahooks'
  7. import type { Timeout } from 'ahooks/lib/useRequest/src/types'
  8. import { useContext } from 'use-context-selector'
  9. import Panel from '../base/feature-panel'
  10. import OperationBtn from '../base/operation-btn'
  11. import EditModal from './config-modal'
  12. import IconTypeIcon from './input-type-icon'
  13. import type { IInputTypeIconProps } from './input-type-icon'
  14. import s from './style.module.css'
  15. import { BracketsX as VarIcon } from '@/app/components/base/icons/src/vender/line/development'
  16. import Tooltip from '@/app/components/base/tooltip'
  17. import type { PromptVariable } from '@/models/debug'
  18. import { DEFAULT_VALUE_MAX_LEN, getMaxVarNameLength } from '@/config'
  19. import { checkKeys, getNewVar } from '@/utils/var'
  20. import Switch from '@/app/components/base/switch'
  21. import Toast from '@/app/components/base/toast'
  22. import { HelpCircle } from '@/app/components/base/icons/src/vender/line/general'
  23. import ConfirmModal from '@/app/components/base/confirm/common'
  24. import ConfigContext from '@/context/debug-configuration'
  25. import { AppType } from '@/types/app'
  26. export type IConfigVarProps = {
  27. promptVariables: PromptVariable[]
  28. readonly?: boolean
  29. onPromptVariablesChange?: (promptVariables: PromptVariable[]) => void
  30. }
  31. let conflictTimer: Timeout
  32. const ConfigVar: FC<IConfigVarProps> = ({ promptVariables, readonly, onPromptVariablesChange }) => {
  33. const { t } = useTranslation()
  34. const {
  35. mode,
  36. dataSets,
  37. } = useContext(ConfigContext)
  38. const hasVar = promptVariables.length > 0
  39. const promptVariableObj = (() => {
  40. const obj: Record<string, boolean> = {}
  41. promptVariables.forEach((item) => {
  42. obj[item.key] = true
  43. })
  44. return obj
  45. })()
  46. const updatePromptVariable = (key: string, updateKey: string, newValue: string | boolean) => {
  47. const newPromptVariables = promptVariables.map((item) => {
  48. if (item.key === key) {
  49. return {
  50. ...item,
  51. [updateKey]: newValue,
  52. }
  53. }
  54. return item
  55. })
  56. onPromptVariablesChange?.(newPromptVariables)
  57. }
  58. const batchUpdatePromptVariable = (key: string, updateKeys: string[], newValues: any[], isParagraph?: boolean) => {
  59. const newPromptVariables = promptVariables.map((item) => {
  60. if (item.key === key) {
  61. const newItem: any = { ...item }
  62. updateKeys.forEach((updateKey, i) => {
  63. newItem[updateKey] = newValues[i]
  64. })
  65. if (isParagraph) {
  66. delete newItem.max_length
  67. delete newItem.options
  68. }
  69. return newItem
  70. }
  71. return item
  72. })
  73. onPromptVariablesChange?.(newPromptVariables)
  74. }
  75. const updatePromptKey = (index: number, newKey: string) => {
  76. clearTimeout(conflictTimer)
  77. const { isValid, errorKey, errorMessageKey } = checkKeys([newKey], true)
  78. if (!isValid) {
  79. Toast.notify({
  80. type: 'error',
  81. message: t(`appDebug.varKeyError.${errorMessageKey}`, { key: errorKey }),
  82. })
  83. return
  84. }
  85. const newPromptVariables = promptVariables.map((item, i) => {
  86. if (i === index) {
  87. return {
  88. ...item,
  89. key: newKey,
  90. }
  91. }
  92. return item
  93. })
  94. conflictTimer = setTimeout(() => {
  95. const isKeyExists = promptVariables.some(item => item.key.trim() === newKey.trim())
  96. if (isKeyExists) {
  97. Toast.notify({
  98. type: 'error',
  99. message: t('appDebug.varKeyError.keyAlreadyExists', { key: newKey }),
  100. })
  101. }
  102. }, 1000)
  103. onPromptVariablesChange?.(newPromptVariables)
  104. }
  105. const updatePromptNameIfNameEmpty = (index: number, newKey: string) => {
  106. if (!newKey)
  107. return
  108. const newPromptVariables = promptVariables.map((item, i) => {
  109. if (i === index && !item.name) {
  110. return {
  111. ...item,
  112. name: newKey,
  113. }
  114. }
  115. return item
  116. })
  117. onPromptVariablesChange?.(newPromptVariables)
  118. }
  119. const handleAddVar = () => {
  120. const newVar = getNewVar('')
  121. onPromptVariablesChange?.([...promptVariables, newVar])
  122. }
  123. const [isShowDeleteContextVarModal, { setTrue: showDeleteContextVarModal, setFalse: hideDeleteContextVarModal }] = useBoolean(false)
  124. const [removeIndex, setRemoveIndex] = useState<number | null>(null)
  125. const didRemoveVar = (index: number) => {
  126. onPromptVariablesChange?.(promptVariables.filter((_, i) => i !== index))
  127. }
  128. const handleRemoveVar = (index: number) => {
  129. const removeVar = promptVariables[index]
  130. if (mode === AppType.completion && dataSets.length > 0 && removeVar.is_context_var) {
  131. showDeleteContextVarModal()
  132. setRemoveIndex(index)
  133. return
  134. }
  135. didRemoveVar(index)
  136. }
  137. const [currKey, setCurrKey] = useState<string | null>(null)
  138. const currItem = currKey ? promptVariables.find(item => item.key === currKey) : null
  139. const [isShowEditModal, { setTrue: showEditModal, setFalse: hideEditModal }] = useBoolean(false)
  140. const handleConfig = (key: string) => {
  141. setCurrKey(key)
  142. showEditModal()
  143. }
  144. return (
  145. <Panel
  146. className="mt-4"
  147. headerIcon={
  148. <VarIcon className='w-4 h-4 text-primary-500'/>
  149. }
  150. title={
  151. <div className='flex items-center'>
  152. <div className='mr-1'>{t('appDebug.variableTitle')}</div>
  153. {!readonly && (
  154. <Tooltip htmlContent={<div className='w-[180px]'>
  155. {t('appDebug.variableTip')}
  156. </div>} selector='config-var-tooltip'>
  157. <HelpCircle className='w-[14px] h-[14px] text-gray-400' />
  158. </Tooltip>
  159. )}
  160. </div>
  161. }
  162. headerRight={!readonly ? <OperationBtn type="add" onClick={handleAddVar} /> : null}
  163. >
  164. {!hasVar && (
  165. <div className='pt-2 pb-1 text-xs text-gray-500'>{t('appDebug.notSetVar')}</div>
  166. )}
  167. {hasVar && (
  168. <div className='rounded-lg border border-gray-200 bg-white'>
  169. <table className={`${s.table} w-full border-collapse border-0 rounded-lg text-sm`}>
  170. <thead className="border-b border-gray-200 text-gray-500 text-xs font-medium">
  171. <tr className='uppercase'>
  172. <td>{t('appDebug.variableTable.key')}</td>
  173. <td>{t('appDebug.variableTable.name')}</td>
  174. {!readonly && (
  175. <>
  176. <td>{t('appDebug.variableTable.optional')}</td>
  177. <td>{t('appDebug.variableTable.action')}</td>
  178. </>
  179. )}
  180. </tr>
  181. </thead>
  182. <tbody className="text-gray-700">
  183. {promptVariables.map(({ key, name, type, required }, index) => (
  184. <tr key={index} className="h-9 leading-9">
  185. <td className="w-[160px] border-b border-gray-100 pl-3">
  186. <div className='flex items-center space-x-1'>
  187. <IconTypeIcon type={type as IInputTypeIconProps['type']} className='text-gray-400' />
  188. {!readonly
  189. ? (
  190. <input
  191. type="text"
  192. placeholder="key"
  193. value={key}
  194. onChange={e => updatePromptKey(index, e.target.value)}
  195. onBlur={e => updatePromptNameIfNameEmpty(index, e.target.value)}
  196. maxLength={getMaxVarNameLength(name)}
  197. className="h-6 leading-6 block w-full rounded-md border-0 py-1.5 text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200"
  198. />
  199. )
  200. : (
  201. <div className='h-6 leading-6 text-[13px] text-gray-700'>{key}</div>
  202. )}
  203. </div>
  204. </td>
  205. <td className="py-1 border-b border-gray-100">
  206. {!readonly
  207. ? (
  208. <input
  209. type="text"
  210. placeholder={key}
  211. value={name}
  212. onChange={e => updatePromptVariable(key, 'name', e.target.value)}
  213. maxLength={getMaxVarNameLength(name)}
  214. className="h-6 leading-6 block w-full rounded-md border-0 py-1.5 text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200"
  215. />)
  216. : (
  217. <div className='h-6 leading-6 text-[13px] text-gray-700'>{name}</div>
  218. )}
  219. </td>
  220. {!readonly && (
  221. <>
  222. <td className='w-[84px] border-b border-gray-100'>
  223. <div className='flex items-center h-full'>
  224. <Switch defaultValue={!required} size='md' onChange={value => updatePromptVariable(key, 'required', !value)} />
  225. </div>
  226. </td>
  227. <td className='w-20 border-b border-gray-100'>
  228. <div className='flex h-full items-center space-x-1'>
  229. <div className='flex items-center justify-items-center w-6 h-6 text-gray-500 cursor-pointer' onClick={() => handleConfig(key)}>
  230. <Cog8ToothIcon width={16} height={16} />
  231. </div>
  232. <div className='flex items-center justify-items-center w-6 h-6 text-gray-500 cursor-pointer' onClick={() => handleRemoveVar(index)} >
  233. <TrashIcon width={16} height={16} />
  234. </div>
  235. </div>
  236. </td>
  237. </>
  238. )}
  239. </tr>
  240. ))}
  241. </tbody>
  242. </table>
  243. </div>
  244. )}
  245. {isShowEditModal && (
  246. <EditModal
  247. payload={currItem as PromptVariable}
  248. isShow={isShowEditModal}
  249. onClose={hideEditModal}
  250. onConfirm={({ type, value }) => {
  251. if (type === 'string')
  252. batchUpdatePromptVariable(currKey as string, ['type', 'max_length'], [type, value || DEFAULT_VALUE_MAX_LEN])
  253. else
  254. batchUpdatePromptVariable(currKey as string, ['type', 'options'], [type, value || []], type === 'paragraph')
  255. hideEditModal()
  256. }}
  257. />
  258. )}
  259. {isShowDeleteContextVarModal && (
  260. <ConfirmModal
  261. isShow={isShowDeleteContextVarModal}
  262. title={t('appDebug.feature.dataSet.queryVariable.deleteContextVarTitle', { varName: promptVariables[removeIndex as number]?.name })}
  263. desc={t('appDebug.feature.dataSet.queryVariable.deleteContextVarTip') as string}
  264. confirmBtnClassName='bg-[#B42318] hover:bg-[#B42318]'
  265. onConfirm={() => {
  266. didRemoveVar(removeIndex as number)
  267. hideDeleteContextVarModal()
  268. }}
  269. onCancel={hideDeleteContextVarModal}
  270. />
  271. )}
  272. </Panel>
  273. )
  274. }
  275. export default React.memo(ConfigVar)