variable-modal.tsx 15 KB

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