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.

variable-modal.tsx 15KB

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