您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

variable-modal.tsx 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. import React, { useCallback, useEffect, useMemo } from 'react'
  2. import { useTranslation } from 'react-i18next'
  3. import { useContext } from 'use-context-selector'
  4. import { v4 as uuid4 } from 'uuid'
  5. import { RiCloseLine, RiDraftLine, RiInputField } from '@remixicon/react'
  6. import VariableTypeSelector from '@/app/components/workflow/panel/chat-variable-panel/components/variable-type-select'
  7. import ObjectValueList from '@/app/components/workflow/panel/chat-variable-panel/components/object-value-list'
  8. import { DEFAULT_OBJECT_VALUE } from '@/app/components/workflow/panel/chat-variable-panel/components/object-value-item'
  9. import ArrayValueList from '@/app/components/workflow/panel/chat-variable-panel/components/array-value-list'
  10. import Button from '@/app/components/base/button'
  11. import Input from '@/app/components/base/input'
  12. import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
  13. import { ToastContext } from '@/app/components/base/toast'
  14. import { useStore } from '@/app/components/workflow/store'
  15. import type { ConversationVariable } from '@/app/components/workflow/types'
  16. import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
  17. import { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'
  18. import cn from '@/utils/classnames'
  19. import { checkKeys } from '@/utils/var'
  20. export type ModalPropsType = {
  21. chatVar?: ConversationVariable
  22. onClose: () => void
  23. onSave: (chatVar: ConversationVariable) => void
  24. }
  25. type ObjectValueItem = {
  26. key: string
  27. type: ChatVarType
  28. value: string | number | undefined
  29. }
  30. const typeList = [
  31. ChatVarType.String,
  32. ChatVarType.Number,
  33. ChatVarType.Object,
  34. ChatVarType.ArrayString,
  35. ChatVarType.ArrayNumber,
  36. ChatVarType.ArrayObject,
  37. ]
  38. const objectPlaceholder = `# example
  39. # {
  40. # "name": "ray",
  41. # "age": 20
  42. # }`
  43. const arrayStringPlaceholder = `# example
  44. # [
  45. # "value1",
  46. # "value2"
  47. # ]`
  48. const arrayNumberPlaceholder = `# example
  49. # [
  50. # 100,
  51. # 200
  52. # ]`
  53. const arrayObjectPlaceholder = `# example
  54. # [
  55. # {
  56. # "name": "ray",
  57. # "age": 20
  58. # },
  59. # {
  60. # "name": "lily",
  61. # "age": 18
  62. # }
  63. # ]`
  64. const ChatVariableModal = ({
  65. chatVar,
  66. onClose,
  67. onSave,
  68. }: ModalPropsType) => {
  69. const { t } = useTranslation()
  70. const { notify } = useContext(ToastContext)
  71. const varList = useStore(s => s.conversationVariables)
  72. const [name, setName] = React.useState('')
  73. const [type, setType] = React.useState<ChatVarType>(ChatVarType.String)
  74. const [value, setValue] = React.useState<any>()
  75. const [objectValue, setObjectValue] = React.useState<ObjectValueItem[]>([DEFAULT_OBJECT_VALUE])
  76. const [editorContent, setEditorContent] = React.useState<string>()
  77. const [editInJSON, setEditInJSON] = React.useState(false)
  78. const [des, setDes] = React.useState<string>('')
  79. const editorMinHeight = useMemo(() => {
  80. if (type === ChatVarType.ArrayObject)
  81. return '240px'
  82. return '120px'
  83. }, [type])
  84. const placeholder = useMemo(() => {
  85. if (type === ChatVarType.ArrayString)
  86. return arrayStringPlaceholder
  87. if (type === ChatVarType.ArrayNumber)
  88. return arrayNumberPlaceholder
  89. if (type === ChatVarType.ArrayObject)
  90. return arrayObjectPlaceholder
  91. return objectPlaceholder
  92. }, [type])
  93. const getObjectValue = useCallback(() => {
  94. if (!chatVar || Object.keys(chatVar.value).length === 0)
  95. return [DEFAULT_OBJECT_VALUE]
  96. return Object.keys(chatVar.value).map((key) => {
  97. return {
  98. key,
  99. type: typeof chatVar.value[key] === 'string' ? ChatVarType.String : ChatVarType.Number,
  100. value: chatVar.value[key],
  101. }
  102. })
  103. }, [chatVar])
  104. const formatValueFromObject = useCallback((list: ObjectValueItem[]) => {
  105. return list.reduce((acc: any, curr) => {
  106. if (curr.key)
  107. acc[curr.key] = curr.value || null
  108. return acc
  109. }, {})
  110. }, [])
  111. const formatValue = (value: any) => {
  112. switch (type) {
  113. case ChatVarType.String:
  114. return value || ''
  115. case ChatVarType.Number:
  116. return value || 0
  117. case ChatVarType.Object:
  118. return formatValueFromObject(objectValue)
  119. case ChatVarType.ArrayString:
  120. case ChatVarType.ArrayNumber:
  121. case ChatVarType.ArrayObject:
  122. return value?.filter(Boolean) || []
  123. }
  124. }
  125. const checkVariableName = (value: string) => {
  126. const { isValid, errorMessageKey } = checkKeys([value], false)
  127. if (!isValid) {
  128. notify({
  129. type: 'error',
  130. message: t(`appDebug.varKeyError.${errorMessageKey}`, { key: t('workflow.env.modal.name') }),
  131. })
  132. return false
  133. }
  134. return true
  135. }
  136. const handleTypeChange = (v: ChatVarType) => {
  137. setValue(undefined)
  138. setEditorContent(undefined)
  139. if (v === ChatVarType.ArrayObject)
  140. setEditInJSON(true)
  141. if (v === ChatVarType.String || v === ChatVarType.Number || v === ChatVarType.Object)
  142. setEditInJSON(false)
  143. setType(v)
  144. }
  145. const handleEditorChange = (editInJSON: boolean) => {
  146. if (type === ChatVarType.Object) {
  147. if (editInJSON) {
  148. const newValue = !objectValue[0].key ? undefined : formatValueFromObject(objectValue)
  149. setValue(newValue)
  150. setEditorContent(JSON.stringify(newValue))
  151. }
  152. else {
  153. if (!editorContent) {
  154. setValue(undefined)
  155. setObjectValue([DEFAULT_OBJECT_VALUE])
  156. }
  157. else {
  158. try {
  159. const newValue = JSON.parse(editorContent)
  160. setValue(newValue)
  161. const newObjectValue = Object.keys(newValue).map((key) => {
  162. return {
  163. key,
  164. type: typeof newValue[key] === 'string' ? ChatVarType.String : ChatVarType.Number,
  165. value: newValue[key],
  166. }
  167. })
  168. setObjectValue(newObjectValue)
  169. }
  170. catch {
  171. // ignore JSON.parse errors
  172. }
  173. }
  174. }
  175. }
  176. if (type === ChatVarType.ArrayString || type === ChatVarType.ArrayNumber) {
  177. if (editInJSON) {
  178. const newValue = (value?.length && value.filter(Boolean).length) ? value.filter(Boolean) : undefined
  179. setValue(newValue)
  180. if (!editorContent)
  181. setEditorContent(JSON.stringify(newValue))
  182. }
  183. else {
  184. setValue(value?.length ? value : [undefined])
  185. }
  186. }
  187. setEditInJSON(editInJSON)
  188. }
  189. const handleEditorValueChange = (content: string) => {
  190. if (!content) {
  191. setEditorContent(content)
  192. return setValue(undefined)
  193. }
  194. else {
  195. setEditorContent(content)
  196. try {
  197. const newValue = JSON.parse(content)
  198. setValue(newValue)
  199. }
  200. catch {
  201. // ignore JSON.parse errors
  202. }
  203. }
  204. }
  205. const handleSave = () => {
  206. if (!checkVariableName(name))
  207. return
  208. if (!chatVar && varList.some(chatVar => chatVar.name === name))
  209. return notify({ type: 'error', message: 'name is existed' })
  210. // if (type !== ChatVarType.Object && !value)
  211. // return notify({ type: 'error', message: 'value can not be empty' })
  212. if (type === ChatVarType.Object && objectValue.some(item => !item.key && !!item.value))
  213. return notify({ type: 'error', message: 'object key can not be empty' })
  214. onSave({
  215. id: chatVar ? chatVar.id : uuid4(),
  216. name,
  217. value_type: type,
  218. value: formatValue(value),
  219. description: des,
  220. })
  221. onClose()
  222. }
  223. useEffect(() => {
  224. if (chatVar) {
  225. setName(chatVar.name)
  226. setType(chatVar.value_type)
  227. setValue(chatVar.value)
  228. setDes(chatVar.description)
  229. setObjectValue(getObjectValue())
  230. if (chatVar.value_type === ChatVarType.ArrayObject) {
  231. setEditorContent(JSON.stringify(chatVar.value))
  232. setEditInJSON(true)
  233. }
  234. else {
  235. setEditInJSON(false)
  236. }
  237. }
  238. }, [chatVar, getObjectValue])
  239. return (
  240. <div
  241. className={cn('flex h-full w-[360px] flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-2xl', type === ChatVarType.Object && 'w-[480px]')}
  242. >
  243. <div className='system-xl-semibold mb-3 flex shrink-0 items-center justify-between p-4 pb-0 text-text-primary'>
  244. {!chatVar ? t('workflow.chatVariable.modal.title') : t('workflow.chatVariable.modal.editTitle')}
  245. <div className='flex items-center'>
  246. <div
  247. className='flex h-6 w-6 cursor-pointer items-center justify-center'
  248. onClick={onClose}
  249. >
  250. <RiCloseLine className='h-4 w-4 text-text-tertiary' />
  251. </div>
  252. </div>
  253. </div>
  254. <div className='max-h-[480px] overflow-y-auto px-4 py-2'>
  255. {/* name */}
  256. <div className='mb-4'>
  257. <div className='system-sm-semibold mb-1 flex h-6 items-center text-text-secondary'>{t('workflow.chatVariable.modal.name')}</div>
  258. <div className='flex'>
  259. <Input
  260. placeholder={t('workflow.chatVariable.modal.namePlaceholder') || ''}
  261. value={name}
  262. onChange={e => setName(e.target.value || '')}
  263. onBlur={e => checkVariableName(e.target.value)}
  264. type='text'
  265. />
  266. </div>
  267. </div>
  268. {/* type */}
  269. <div className='mb-4'>
  270. <div className='system-sm-semibold mb-1 flex h-6 items-center text-text-secondary'>{t('workflow.chatVariable.modal.type')}</div>
  271. <div className='flex'>
  272. <VariableTypeSelector
  273. value={type}
  274. list={typeList}
  275. onSelect={handleTypeChange}
  276. popupClassName='w-[327px]'
  277. />
  278. </div>
  279. </div>
  280. {/* default value */}
  281. <div className='mb-4'>
  282. <div className='system-sm-semibold mb-1 flex h-6 items-center justify-between text-text-secondary'>
  283. <div>{t('workflow.chatVariable.modal.value')}</div>
  284. {(type === ChatVarType.ArrayString || type === ChatVarType.ArrayNumber) && (
  285. <Button
  286. variant='ghost'
  287. size='small'
  288. className='text-text-tertiary'
  289. onClick={() => handleEditorChange(!editInJSON)}
  290. >
  291. {editInJSON ? <RiInputField className='mr-1 h-3.5 w-3.5' /> : <RiDraftLine className='mr-1 h-3.5 w-3.5' />}
  292. {editInJSON ? t('workflow.chatVariable.modal.oneByOne') : t('workflow.chatVariable.modal.editInJSON')}
  293. </Button>
  294. )}
  295. {type === ChatVarType.Object && (
  296. <Button
  297. variant='ghost'
  298. size='small'
  299. className='text-text-tertiary'
  300. onClick={() => handleEditorChange(!editInJSON)}
  301. >
  302. {editInJSON ? <RiInputField className='mr-1 h-3.5 w-3.5' /> : <RiDraftLine className='mr-1 h-3.5 w-3.5' />}
  303. {editInJSON ? t('workflow.chatVariable.modal.editInForm') : t('workflow.chatVariable.modal.editInJSON')}
  304. </Button>
  305. )}
  306. </div>
  307. <div className='flex'>
  308. {type === ChatVarType.String && (
  309. // Input will remove \n\r, so use Textarea just like description area
  310. <textarea
  311. className='system-sm-regular placeholder:system-sm-regular block h-20 w-full resize-none appearance-none rounded-lg border border-transparent bg-components-input-bg-normal p-2 caret-primary-600 outline-none placeholder:text-components-input-text-placeholder hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs'
  312. value={value}
  313. placeholder={t('workflow.chatVariable.modal.valuePlaceholder') || ''}
  314. onChange={e => setValue(e.target.value)}
  315. />
  316. )}
  317. {type === ChatVarType.Number && (
  318. <Input
  319. placeholder={t('workflow.chatVariable.modal.valuePlaceholder') || ''}
  320. value={value}
  321. onChange={e => setValue(Number(e.target.value))}
  322. type='number'
  323. />
  324. )}
  325. {type === ChatVarType.Object && !editInJSON && (
  326. <ObjectValueList
  327. list={objectValue}
  328. onChange={setObjectValue}
  329. />
  330. )}
  331. {type === ChatVarType.ArrayString && !editInJSON && (
  332. <ArrayValueList
  333. isString
  334. list={value || [undefined]}
  335. onChange={setValue}
  336. />
  337. )}
  338. {type === ChatVarType.ArrayNumber && !editInJSON && (
  339. <ArrayValueList
  340. isString={false}
  341. list={value || [undefined]}
  342. onChange={setValue}
  343. />
  344. )}
  345. {editInJSON && (
  346. <div className='w-full rounded-[10px] bg-components-input-bg-normal py-2 pl-3 pr-1' style={{ height: editorMinHeight }}>
  347. <CodeEditor
  348. isExpand
  349. noWrapper
  350. language={CodeLanguage.json}
  351. value={editorContent}
  352. placeholder={<div className='whitespace-pre'>{placeholder}</div>}
  353. onChange={handleEditorValueChange}
  354. />
  355. </div>
  356. )}
  357. </div>
  358. </div>
  359. {/* description */}
  360. <div className=''>
  361. <div className='system-sm-semibold mb-1 flex h-6 items-center text-text-secondary'>{t('workflow.chatVariable.modal.description')}</div>
  362. <div className='flex'>
  363. <textarea
  364. className='system-sm-regular placeholder:system-sm-regular block h-20 w-full resize-none appearance-none rounded-lg border border-transparent bg-components-input-bg-normal p-2 caret-primary-600 outline-none placeholder:text-components-input-text-placeholder hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs'
  365. value={des}
  366. placeholder={t('workflow.chatVariable.modal.descriptionPlaceholder') || ''}
  367. onChange={e => setDes(e.target.value)}
  368. />
  369. </div>
  370. </div>
  371. </div>
  372. <div className='flex flex-row-reverse rounded-b-2xl p-4 pt-2'>
  373. <div className='flex gap-2'>
  374. <Button onClick={onClose}>{t('common.operation.cancel')}</Button>
  375. <Button variant='primary' onClick={handleSave}>{t('common.operation.save')}</Button>
  376. </div>
  377. </div>
  378. </div>
  379. )
  380. }
  381. export default ChatVariableModal