variable-modal.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. setEditInJSON(false)
  226. setObjectValue(getObjectValue())
  227. }
  228. }, [chatVar, getObjectValue])
  229. return (
  230. <div
  231. 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]')}
  232. >
  233. <div className='shrink-0 flex items-center justify-between mb-3 p-4 pb-0 text-text-primary system-xl-semibold'>
  234. {!chatVar ? t('workflow.chatVariable.modal.title') : t('workflow.chatVariable.modal.editTitle')}
  235. <div className='flex items-center'>
  236. <div
  237. className='flex items-center justify-center w-6 h-6 cursor-pointer'
  238. onClick={onClose}
  239. >
  240. <RiCloseLine className='w-4 h-4 text-text-tertiary' />
  241. </div>
  242. </div>
  243. </div>
  244. <div className='px-4 py-2 max-h-[480px] overflow-y-auto'>
  245. {/* name */}
  246. <div className='mb-4'>
  247. <div className='mb-1 h-6 flex items-center text-text-secondary system-sm-semibold'>{t('workflow.chatVariable.modal.name')}</div>
  248. <div className='flex'>
  249. <input
  250. tabIndex={0}
  251. 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'
  252. placeholder={t('workflow.chatVariable.modal.namePlaceholder') || ''}
  253. value={name}
  254. onChange={e => handleNameChange(e.target.value)}
  255. type='text'
  256. />
  257. </div>
  258. </div>
  259. {/* type */}
  260. <div className='mb-4'>
  261. <div className='mb-1 h-6 flex items-center text-text-secondary system-sm-semibold'>{t('workflow.chatVariable.modal.type')}</div>
  262. <div className='flex'>
  263. <VariableTypeSelector
  264. value={type}
  265. list={typeList}
  266. onSelect={handleTypeChange}
  267. popupClassName='w-[327px]'
  268. />
  269. </div>
  270. </div>
  271. {/* default value */}
  272. <div className='mb-4'>
  273. <div className='mb-1 h-6 flex items-center justify-between text-text-secondary system-sm-semibold'>
  274. <div>{t('workflow.chatVariable.modal.value')}</div>
  275. {(type === ChatVarType.ArrayString || type === ChatVarType.ArrayNumber) && (
  276. <Button
  277. variant='ghost'
  278. size='small'
  279. className='text-text-tertiary'
  280. onClick={() => handleEditorChange(!editInJSON)}
  281. >
  282. {editInJSON ? <RiInputField className='mr-1 w-3.5 h-3.5' /> : <RiDraftLine className='mr-1 w-3.5 h-3.5' />}
  283. {editInJSON ? t('workflow.chatVariable.modal.oneByOne') : t('workflow.chatVariable.modal.editInJSON')}
  284. </Button>
  285. )}
  286. {type === ChatVarType.Object && (
  287. <Button
  288. variant='ghost'
  289. size='small'
  290. className='text-text-tertiary'
  291. onClick={() => handleEditorChange(!editInJSON)}
  292. >
  293. {editInJSON ? <RiInputField className='mr-1 w-3.5 h-3.5' /> : <RiDraftLine className='mr-1 w-3.5 h-3.5' />}
  294. {editInJSON ? t('workflow.chatVariable.modal.editInForm') : t('workflow.chatVariable.modal.editInJSON')}
  295. </Button>
  296. )}
  297. </div>
  298. <div className='flex'>
  299. {type === ChatVarType.String && (
  300. <input
  301. 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'
  302. placeholder={t('workflow.chatVariable.modal.valuePlaceholder') || ''}
  303. value={value}
  304. onChange={e => setValue(e.target.value)}
  305. />
  306. )}
  307. {type === ChatVarType.Number && (
  308. <input
  309. 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'
  310. placeholder={t('workflow.chatVariable.modal.valuePlaceholder') || ''}
  311. value={value}
  312. onChange={e => setValue(Number(e.target.value))}
  313. type='number'
  314. />
  315. )}
  316. {type === ChatVarType.Object && !editInJSON && (
  317. <ObjectValueList
  318. list={objectValue}
  319. onChange={setObjectValue}
  320. />
  321. )}
  322. {type === ChatVarType.ArrayString && !editInJSON && (
  323. <ArrayValueList
  324. isString
  325. list={value || [undefined]}
  326. onChange={setValue}
  327. />
  328. )}
  329. {type === ChatVarType.ArrayNumber && !editInJSON && (
  330. <ArrayValueList
  331. isString={false}
  332. list={value || [undefined]}
  333. onChange={setValue}
  334. />
  335. )}
  336. {editInJSON && (
  337. <div className='w-full py-2 pl-3 pr-1 rounded-[10px] bg-components-input-bg-normal' style={{ height: editorMinHeight }}>
  338. <CodeEditor
  339. isExpand
  340. noWrapper
  341. language={CodeLanguage.json}
  342. value={editorContent}
  343. placeholder={<div className='whitespace-pre'>{placeholder}</div>}
  344. onChange={handleEditorValueChange}
  345. />
  346. </div>
  347. )}
  348. </div>
  349. </div>
  350. {/* description */}
  351. <div className=''>
  352. <div className='mb-1 h-6 flex items-center text-text-secondary system-sm-semibold'>{t('workflow.chatVariable.modal.description')}</div>
  353. <div className='flex'>
  354. <textarea
  355. 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'
  356. value={des}
  357. placeholder={t('workflow.chatVariable.modal.descriptionPlaceholder') || ''}
  358. onChange={e => setDes(e.target.value)}
  359. />
  360. </div>
  361. </div>
  362. </div>
  363. <div className='p-4 pt-2 flex flex-row-reverse rounded-b-2xl'>
  364. <div className='flex gap-2'>
  365. <Button onClick={onClose}>{t('common.operation.cancel')}</Button>
  366. <Button variant='primary' onClick={handleSave}>{t('common.operation.save')}</Button>
  367. </div>
  368. </div>
  369. </div>
  370. )
  371. }
  372. export default ChatVariableModal