You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.tsx 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 Panel from '../base/feature-panel'
  9. import OperationBtn from '../base/operation-btn'
  10. import VarIcon from '../base/icons/var-icon'
  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 Tooltip from '@/app/components/base/tooltip'
  16. import type { PromptVariable } from '@/models/debug'
  17. import { DEFAULT_VALUE_MAX_LEN, getMaxVarNameLength } from '@/config'
  18. import { checkKeys, getNewVar } from '@/utils/var'
  19. import Switch from '@/app/components/base/switch'
  20. import Toast from '@/app/components/base/toast'
  21. export type IConfigVarProps = {
  22. promptVariables: PromptVariable[]
  23. readonly?: boolean
  24. onPromptVariablesChange?: (promptVariables: PromptVariable[]) => void
  25. }
  26. let conflictTimer: Timeout
  27. const ConfigVar: FC<IConfigVarProps> = ({ promptVariables, readonly, onPromptVariablesChange }) => {
  28. const { t } = useTranslation()
  29. const hasVar = promptVariables.length > 0
  30. const promptVariableObj = (() => {
  31. const obj: Record<string, boolean> = {}
  32. promptVariables.forEach((item) => {
  33. obj[item.key] = true
  34. })
  35. return obj
  36. })()
  37. const updatePromptVariable = (key: string, updateKey: string, newValue: string | boolean) => {
  38. const newPromptVariables = promptVariables.map((item) => {
  39. if (item.key === key) {
  40. return {
  41. ...item,
  42. [updateKey]: newValue,
  43. }
  44. }
  45. return item
  46. })
  47. onPromptVariablesChange?.(newPromptVariables)
  48. }
  49. const batchUpdatePromptVariable = (key: string, updateKeys: string[], newValues: any[]) => {
  50. const newPromptVariables = promptVariables.map((item) => {
  51. if (item.key === key) {
  52. const newItem: any = { ...item }
  53. updateKeys.forEach((updateKey, i) => {
  54. newItem[updateKey] = newValues[i]
  55. })
  56. return newItem
  57. }
  58. return item
  59. })
  60. onPromptVariablesChange?.(newPromptVariables)
  61. }
  62. const updatePromptKey = (index: number, newKey: string) => {
  63. clearTimeout(conflictTimer)
  64. const { isValid, errorKey, errorMessageKey } = checkKeys([newKey], true)
  65. if (!isValid) {
  66. Toast.notify({
  67. type: 'error',
  68. message: t(`appDebug.varKeyError.${errorMessageKey}`, { key: errorKey }),
  69. })
  70. return
  71. }
  72. const newPromptVariables = promptVariables.map((item, i) => {
  73. if (i === index) {
  74. return {
  75. ...item,
  76. key: newKey,
  77. }
  78. }
  79. return item
  80. })
  81. conflictTimer = setTimeout(() => {
  82. const isKeyExists = promptVariables.some(item => item.key.trim() === newKey.trim())
  83. if (isKeyExists) {
  84. Toast.notify({
  85. type: 'error',
  86. message: t('appDebug.varKeyError.keyAlreadyExists', { key: newKey }),
  87. })
  88. }
  89. }, 1000)
  90. onPromptVariablesChange?.(newPromptVariables)
  91. }
  92. const updatePromptNameIfNameEmpty = (index: number, newKey: string) => {
  93. if (!newKey)
  94. return
  95. const newPromptVariables = promptVariables.map((item, i) => {
  96. if (i === index && !item.name) {
  97. return {
  98. ...item,
  99. name: newKey,
  100. }
  101. }
  102. return item
  103. })
  104. onPromptVariablesChange?.(newPromptVariables)
  105. }
  106. const handleAddVar = () => {
  107. const newVar = getNewVar('')
  108. onPromptVariablesChange?.([...promptVariables, newVar])
  109. }
  110. const handleRemoveVar = (index: number) => {
  111. onPromptVariablesChange?.(promptVariables.filter((_, i) => i !== index))
  112. }
  113. const [currKey, setCurrKey] = useState<string | null>(null)
  114. const currItem = currKey ? promptVariables.find(item => item.key === currKey) : null
  115. const [isShowEditModal, { setTrue: showEditModal, setFalse: hideEditModal }] = useBoolean(false)
  116. const handleConfig = (key: string) => {
  117. setCurrKey(key)
  118. showEditModal()
  119. }
  120. return (
  121. <Panel
  122. className="mt-4"
  123. headerIcon={
  124. <VarIcon />
  125. }
  126. title={
  127. <div className='flex items-center gap-2'>
  128. <div>{t('appDebug.variableTitle')}</div>
  129. {!readonly && (
  130. <Tooltip htmlContent={<div className='w-[180px]'>
  131. {t('appDebug.variableTip')}
  132. </div>} selector='config-var-tooltip'>
  133. <svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">
  134. <path d="M8.66667 11.1667H8V8.5H7.33333M8 5.83333H8.00667M14 8.5C14 9.28793 13.8448 10.0681 13.5433 10.7961C13.2417 11.5241 12.7998 12.1855 12.2426 12.7426C11.6855 13.2998 11.0241 13.7417 10.2961 14.0433C9.56815 14.3448 8.78793 14.5 8 14.5C7.21207 14.5 6.43185 14.3448 5.7039 14.0433C4.97595 13.7417 4.31451 13.2998 3.75736 12.7426C3.20021 12.1855 2.75825 11.5241 2.45672 10.7961C2.15519 10.0681 2 9.28793 2 8.5C2 6.9087 2.63214 5.38258 3.75736 4.25736C4.88258 3.13214 6.4087 2.5 8 2.5C9.5913 2.5 11.1174 3.13214 12.2426 4.25736C13.3679 5.38258 14 6.9087 14 8.5Z" stroke="#9CA3AF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
  135. </svg>
  136. </Tooltip>
  137. )}
  138. </div>
  139. }
  140. headerRight={!readonly ? <OperationBtn type="add" onClick={handleAddVar} /> : null}
  141. >
  142. {!hasVar && (
  143. <div className='pt-2 pb-1 text-xs text-gray-500'>{t('appDebug.notSetVar')}</div>
  144. )}
  145. {hasVar && (
  146. <div className='rounded-lg border border-gray-200 bg-white'>
  147. <table className={`${s.table} w-full border-collapse border-0 rounded-lg text-sm`}>
  148. <thead className="border-b border-gray-200 text-gray-500 text-xs font-medium">
  149. <tr className='uppercase'>
  150. <td>{t('appDebug.variableTable.key')}</td>
  151. <td>{t('appDebug.variableTable.name')}</td>
  152. {!readonly && (
  153. <>
  154. <td>{t('appDebug.variableTable.optional')}</td>
  155. <td>{t('appDebug.variableTable.action')}</td>
  156. </>
  157. )}
  158. </tr>
  159. </thead>
  160. <tbody className="text-gray-700">
  161. {promptVariables.map(({ key, name, type, required }, index) => (
  162. <tr key={index} className="h-9 leading-9">
  163. <td className="w-[160px] border-b border-gray-100 pl-3">
  164. <div className='flex items-center space-x-1'>
  165. <IconTypeIcon type={type as IInputTypeIconProps['type']} />
  166. {!readonly
  167. ? (
  168. <input
  169. type="text"
  170. placeholder="key"
  171. value={key}
  172. onChange={e => updatePromptKey(index, e.target.value)}
  173. onBlur={e => updatePromptNameIfNameEmpty(index, e.target.value)}
  174. maxLength={getMaxVarNameLength(name)}
  175. 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"
  176. />
  177. )
  178. : (
  179. <div className='h-6 leading-6 text-[13px] text-gray-700'>{key}</div>
  180. )}
  181. </div>
  182. </td>
  183. <td className="py-1 border-b border-gray-100">
  184. {!readonly
  185. ? (
  186. <input
  187. type="text"
  188. placeholder={key}
  189. value={name}
  190. onChange={e => updatePromptVariable(key, 'name', e.target.value)}
  191. maxLength={getMaxVarNameLength(name)}
  192. 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"
  193. />)
  194. : (
  195. <div className='h-6 leading-6 text-[13px] text-gray-700'>{name}</div>
  196. )}
  197. </td>
  198. {!readonly && (
  199. <>
  200. <td className='w-[84px] border-b border-gray-100'>
  201. <div className='flex items-center h-full'>
  202. <Switch defaultValue={!required} size='md' onChange={value => updatePromptVariable(key, 'required', !value)} />
  203. </div>
  204. </td>
  205. <td className='w-20 border-b border-gray-100'>
  206. <div className='flex h-full items-center space-x-1'>
  207. <div className='flex items-center justify-items-center w-6 h-6 text-gray-500 cursor-pointer' onClick={() => handleConfig(key)}>
  208. <Cog8ToothIcon width={16} height={16} />
  209. </div>
  210. <div className='flex items-center justify-items-center w-6 h-6 text-gray-500 cursor-pointer' onClick={() => handleRemoveVar(index)} >
  211. <TrashIcon width={16} height={16} />
  212. </div>
  213. </div>
  214. </td>
  215. </>
  216. )}
  217. </tr>
  218. ))}
  219. </tbody>
  220. </table>
  221. </div>
  222. )}
  223. {isShowEditModal && (
  224. <EditModal
  225. payload={currItem as PromptVariable}
  226. isShow={isShowEditModal}
  227. onClose={hideEditModal}
  228. onConfirm={({ type, value }) => {
  229. if (type === 'string')
  230. batchUpdatePromptVariable(currKey as string, ['type', 'max_length'], [type, value || DEFAULT_VALUE_MAX_LEN])
  231. else
  232. batchUpdatePromptVariable(currKey as string, ['type', 'options'], [type, value || []])
  233. hideEditModal()
  234. }}
  235. />
  236. )}
  237. </Panel>
  238. )
  239. }
  240. export default React.memo(ConfigVar)