variable-modal.tsx 15 KB

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