chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
+248
@@ -0,0 +1,248 @@
|
||||
import type { ReactElement, ReactNode } from 'react'
|
||||
import type { CodeNodeType } from '@/app/components/workflow/nodes/code/types'
|
||||
import type { ConversationVariable, Node } from '@/app/components/workflow/types'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { useStoreApi } from 'reactflow'
|
||||
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { HooksStoreContext } from '@/app/components/workflow/hooks-store/provider'
|
||||
import { createHooksStore } from '@/app/components/workflow/hooks-store/store'
|
||||
import {
|
||||
useConversationVarValues,
|
||||
useInvalidateConversationVarValues,
|
||||
} from '@/service/use-workflow'
|
||||
import ChatVariablePanel from '../index'
|
||||
import { ChatVarType } from '../type'
|
||||
|
||||
const mockUpdateConversationVariables = vi.fn().mockResolvedValue(undefined)
|
||||
|
||||
let mockConversationVariables: ConversationVariable[] = []
|
||||
let mockFlowNodes: Node<CodeNodeType>[] = []
|
||||
let flowStore: ReturnType<typeof useStoreApi>
|
||||
function InspectVariables({ children }: { children: ReactNode }) {
|
||||
flowStore = useStoreApi()
|
||||
const invalidateConversationVarValues = useInvalidateConversationVarValues({
|
||||
kind: 'app',
|
||||
appId: 'app-1',
|
||||
mode: 'advanced-chat',
|
||||
})
|
||||
const [hooks] = useState(() => createHooksStore({ invalidateConversationVarValues }))
|
||||
const { data } = useConversationVarValues({ kind: 'app', appId: 'app-1', mode: 'advanced-chat' })
|
||||
return (
|
||||
<HooksStoreContext value={hooks}>
|
||||
{children}
|
||||
<output aria-label="Inspected conversation variables">{JSON.stringify(data)}</output>
|
||||
</HooksStoreContext>
|
||||
)
|
||||
}
|
||||
const render = (ui: ReactElement) =>
|
||||
renderWorkflowFlowComponent(<InspectVariables>{ui}</InspectVariables>, {
|
||||
nodes: mockFlowNodes,
|
||||
initialStoreState: {
|
||||
conversationVariables: mockConversationVariables,
|
||||
showChatVariablePanel: true,
|
||||
},
|
||||
})
|
||||
|
||||
const createConversationVariable = (
|
||||
overrides: Partial<ConversationVariable> = {},
|
||||
): ConversationVariable => ({
|
||||
id: 'var-1',
|
||||
name: 'conversation_var',
|
||||
value_type: ChatVarType.String,
|
||||
value: '',
|
||||
description: 'Conversation variable',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const createNode = (id: string): Node<CodeNodeType> => ({
|
||||
id,
|
||||
type: 'custom',
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
title: id,
|
||||
desc: '',
|
||||
type: 'code',
|
||||
code_language: 'python3',
|
||||
code: '',
|
||||
outputs: {},
|
||||
variables: [],
|
||||
},
|
||||
})
|
||||
|
||||
vi.mock('@/service/workflow', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/workflow')>()),
|
||||
updateConversationVariables: (...args: unknown[]) => mockUpdateConversationVariables(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleResponses } = await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'apps.byAppId.workflows.draft.conversationVariables.get': () =>
|
||||
Promise.resolve({
|
||||
items: [
|
||||
{
|
||||
id: 'var-added',
|
||||
name: 'fresh_var',
|
||||
value: 'server value',
|
||||
value_type: 'string',
|
||||
selector: ['conversation', 'fresh_var'],
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
// VariableItem exposes only unnamed SVG edit/delete targets; keep this minimal action boundary.
|
||||
vi.mock('@/app/components/workflow/panel/chat-variable-panel/components/variable-item', () => ({
|
||||
default: ({
|
||||
item,
|
||||
onEdit,
|
||||
onDelete,
|
||||
}: {
|
||||
item: ConversationVariable
|
||||
onEdit: (item: ConversationVariable) => void
|
||||
onDelete: (item: ConversationVariable) => void
|
||||
}) => (
|
||||
<div>
|
||||
<span>{item.name}</span>
|
||||
<button type="button" onClick={() => onEdit(item)}>{`edit-${item.name}`}</button>
|
||||
<button type="button" onClick={() => onDelete(item)}>{`delete-${item.name}`}</button>
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
|
||||
describe('ChatVariablePanel', () => {
|
||||
beforeEach(() => {
|
||||
mockConversationVariables = [createConversationVariable()]
|
||||
mockFlowNodes = [createNode('node-1'), createNode('node-2')]
|
||||
mockUpdateConversationVariables.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('should toggle the tips area and close the panel', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = render(<ChatVariablePanel />)
|
||||
|
||||
expect(screen.getByText('workflow.chatVariable.panelDescription')).toBeInTheDocument()
|
||||
|
||||
const toggleTipButton = screen.getByRole('button', {
|
||||
name: 'workflow.chatVariable.tips',
|
||||
expanded: true,
|
||||
})
|
||||
await user.click(toggleTipButton)
|
||||
expect(screen.queryByText('workflow.chatVariable.panelDescription')).not.toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByRole('button', {
|
||||
name: 'workflow.chatVariable.tips',
|
||||
expanded: false,
|
||||
}),
|
||||
).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
|
||||
|
||||
expect(store.getState().showChatVariablePanel).toBe(false)
|
||||
})
|
||||
|
||||
it('should prepend new variables, persist them and refresh inspector values', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
const { store } = render(<ChatVariablePanel />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.chatVariable.button' }))
|
||||
await user.type(
|
||||
screen.getByPlaceholderText('workflow.chatVariable.modal.namePlaceholder'),
|
||||
'fresh_var',
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(store.getState().conversationVariables).toEqual([
|
||||
expect.objectContaining({ id: expect.any(String), name: 'fresh_var' }),
|
||||
createConversationVariable(),
|
||||
])
|
||||
expect(mockUpdateConversationVariables).toHaveBeenCalledWith({
|
||||
appId: 'app-1',
|
||||
conversationVariables: [
|
||||
expect.objectContaining({ id: expect.any(String), name: 'fresh_var' }),
|
||||
createConversationVariable(),
|
||||
],
|
||||
})
|
||||
expect(screen.getByLabelText('Inspected conversation variables')).toHaveTextContent(
|
||||
'server value',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('should rename existing variables and update affected node references', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockFlowNodes[0]!.data.variables = [
|
||||
{ variable: 'topic', value_selector: ['conversation', 'conversation_var'] },
|
||||
]
|
||||
const updatedNode = {
|
||||
...createNode('node-1'),
|
||||
data: {
|
||||
...createNode('node-1').data,
|
||||
variables: [
|
||||
{ variable: 'topic', value_selector: ['conversation', 'conversation_var_next'] },
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
const { store } = render(<ChatVariablePanel />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'edit-conversation_var' }))
|
||||
const name = screen.getByPlaceholderText('workflow.chatVariable.modal.namePlaceholder')
|
||||
await user.clear(name)
|
||||
await user.type(name, 'conversation_var_next')
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
|
||||
|
||||
expect(store.getState().conversationVariables).toEqual([
|
||||
expect.objectContaining({ id: 'var-1', name: 'conversation_var_next' }),
|
||||
])
|
||||
expect(flowStore.getState().getNodes()).toEqual([
|
||||
expect.objectContaining(updatedNode),
|
||||
expect.objectContaining(createNode('node-2')),
|
||||
])
|
||||
expect(store.getState().controlPromptEditorRerenderKey).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('should require confirmation before deleting variables referenced by workflow nodes', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockFlowNodes[0]!.data.variables = [
|
||||
{ variable: 'topic', value_selector: ['conversation', 'conversation_var'] },
|
||||
]
|
||||
const prunedNode = {
|
||||
...createNode('node-1'),
|
||||
data: {
|
||||
...createNode('node-1').data,
|
||||
variables: [{ variable: 'topic', value_selector: [] }],
|
||||
},
|
||||
}
|
||||
|
||||
const { store } = render(<ChatVariablePanel />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'delete-conversation_var' }))
|
||||
expect(screen.getByRole('alertdialog')).toBeInTheDocument()
|
||||
expect(mockUpdateConversationVariables).not.toHaveBeenCalled()
|
||||
expect(store.getState().conversationVariables).toEqual(mockConversationVariables)
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
|
||||
expect(store.getState().conversationVariables).toEqual(mockConversationVariables)
|
||||
expect(flowStore.getState().getNodes()[0]!.data.variables).toEqual(
|
||||
mockFlowNodes[0]!.data.variables,
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'delete-conversation_var' }))
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))
|
||||
|
||||
expect(flowStore.getState().getNodes()).toEqual([
|
||||
expect.objectContaining(prunedNode),
|
||||
expect.objectContaining(createNode('node-2')),
|
||||
])
|
||||
expect(store.getState().conversationVariables).toEqual([])
|
||||
})
|
||||
})
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import ArrayBoolList from '../array-bool-list'
|
||||
|
||||
function BooleanArrayEditor() {
|
||||
const [values, setValues] = useState([true])
|
||||
return (
|
||||
<>
|
||||
<ArrayBoolList list={values} onChange={setValues} />
|
||||
<output aria-label="Variable value">{JSON.stringify(values)}</output>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
it('updates, appends, and removes boolean values without losing existing edits', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<BooleanArrayEditor />)
|
||||
|
||||
await user.click(screen.getByText('False'))
|
||||
expect(screen.getByLabelText('Variable value')).toHaveTextContent('[false]')
|
||||
await user.click(screen.getByText('True'))
|
||||
expect(screen.getByLabelText('Variable value')).toHaveTextContent('[true]')
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: 'workflow.chatVariable.modal.addArrayValue' }),
|
||||
)
|
||||
expect(screen.getByLabelText('Variable value')).toHaveTextContent('[true,false]')
|
||||
await user.click(screen.getAllByRole('button', { name: 'common.operation.remove' })[0]!)
|
||||
expect(screen.getByLabelText('Variable value')).toHaveTextContent('[false]')
|
||||
})
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import ArrayValueList from '../array-value-list'
|
||||
|
||||
describe('ArrayValueList', () => {
|
||||
it('updates string items, appends a row, and removes an item', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
function StringArray() {
|
||||
const [list, setList] = useState<Array<string | number | undefined>>(['alpha', 'beta'])
|
||||
return (
|
||||
<ArrayValueList
|
||||
isString
|
||||
list={list}
|
||||
onChange={(value) => {
|
||||
setList(value)
|
||||
onChange(value)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
render(<StringArray />)
|
||||
|
||||
await user.type(
|
||||
screen.getByRole('textbox', { name: 'workflow.chatVariable.modal.arrayValue 1' }),
|
||||
'x',
|
||||
)
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: 'workflow.chatVariable.modal.addArrayValue' }),
|
||||
)
|
||||
await user.click(screen.getAllByRole('button', { name: 'common.operation.remove' })[0]!)
|
||||
|
||||
expect(onChange).toHaveBeenNthCalledWith(1, ['alphax', 'beta'])
|
||||
expect(onChange).toHaveBeenNthCalledWith(2, ['alphax', 'beta', undefined])
|
||||
expect(onChange).toHaveBeenNthCalledWith(3, ['beta', undefined])
|
||||
expect(
|
||||
screen.getAllByRole('textbox').map((input) => (input as HTMLInputElement).value),
|
||||
).toEqual(['beta', ''])
|
||||
})
|
||||
|
||||
it('edits decimal numbers and keeps cleared rows empty instead of converting them to zero', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
function NumericArray() {
|
||||
const [list, setList] = useState<Array<string | number | undefined>>([1])
|
||||
return (
|
||||
<ArrayValueList
|
||||
isString={false}
|
||||
list={list}
|
||||
onChange={(value) => {
|
||||
setList(value)
|
||||
onChange(value)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
render(<NumericArray />)
|
||||
|
||||
const input = screen.getByRole('textbox', { name: 'workflow.chatVariable.modal.arrayValue 1' })
|
||||
await user.clear(input)
|
||||
await user.type(input, '-7.123456')
|
||||
await user.tab()
|
||||
expect(onChange).toHaveBeenLastCalledWith([-7.123456])
|
||||
expect(input).toHaveValue('-7.123456')
|
||||
await user.clear(input)
|
||||
await user.tab()
|
||||
expect(input).toHaveValue('')
|
||||
expect(onChange).toHaveBeenLastCalledWith([undefined])
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: 'workflow.chatVariable.modal.addArrayValue' }),
|
||||
)
|
||||
|
||||
expect(onChange).toHaveBeenLastCalledWith([undefined, undefined])
|
||||
})
|
||||
})
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { ChatVarType } from '../../type'
|
||||
import ObjectValueItem from '../object-value-item'
|
||||
|
||||
const toastError = vi.fn()
|
||||
vi.mock('@/app/notifications', () => ({
|
||||
toast: { error: (...args: unknown[]) => toastError(...args) },
|
||||
}))
|
||||
|
||||
describe('ObjectValueItem', () => {
|
||||
it('preserves a renamed key while editing its value and appends only one draft row', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
function ObjectDraft() {
|
||||
const [list, setList] = useState([
|
||||
{ key: 'reason', type: ChatVarType.String, value: 'draft' },
|
||||
])
|
||||
return (
|
||||
<ObjectValueItem
|
||||
index={0}
|
||||
list={list}
|
||||
onChange={(value) => {
|
||||
setList(value)
|
||||
onChange(value)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
render(<ObjectDraft />)
|
||||
|
||||
await user.type(screen.getByDisplayValue('reason'), '_code')
|
||||
const value = screen.getByDisplayValue('draft')
|
||||
await user.clear(value)
|
||||
await user.type(value, 'published')
|
||||
await user.tab()
|
||||
await user.click(value)
|
||||
|
||||
expect(onChange).toHaveBeenLastCalledWith([
|
||||
{ key: 'reason_code', type: ChatVarType.String, value: 'published' },
|
||||
{ key: '', type: ChatVarType.String, value: undefined },
|
||||
])
|
||||
expect(screen.getByDisplayValue('reason_code')).toBeInTheDocument()
|
||||
expect(value).toHaveValue('published')
|
||||
})
|
||||
|
||||
it('rejects invalid object keys', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(
|
||||
<ObjectValueItem
|
||||
index={0}
|
||||
list={[{ key: 'reason', type: ChatVarType.String, value: 'draft' }]}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
)
|
||||
|
||||
await user.type(screen.getByDisplayValue('reason'), ' ')
|
||||
|
||||
expect(toastError).toHaveBeenCalledWith('workflow.chatVariable.modal.objectKeyPatternError')
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
expect(screen.getByDisplayValue('reason')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+278
@@ -0,0 +1,278 @@
|
||||
import type { TFunction } from 'i18next'
|
||||
import type { ChangeEvent } from 'react'
|
||||
import { act, renderHook } from '@testing-library/react'
|
||||
import { withSelectorKey } from '@/test/i18n-mock'
|
||||
import { ChatVarType } from '../../type'
|
||||
import { useVariableModalState } from '../use-variable-modal-state'
|
||||
|
||||
const t = withSelectorKey((key: string) => key) as TFunction<['appDebug', 'workflow']>
|
||||
|
||||
const createOptions = (overrides: Partial<Parameters<typeof useVariableModalState>[0]> = {}) => ({
|
||||
chatVar: undefined,
|
||||
conversationVariables: [],
|
||||
notify: vi.fn(),
|
||||
onClose: vi.fn(),
|
||||
onSave: vi.fn(),
|
||||
t,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('useVariableModalState', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should build initial state from an existing array object variable', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useVariableModalState(
|
||||
createOptions({
|
||||
chatVar: {
|
||||
id: 'var-1',
|
||||
name: 'payload',
|
||||
description: 'desc',
|
||||
value_type: ChatVarType.ArrayObject,
|
||||
value: [{ enabled: true }],
|
||||
},
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
expect(result.current.name).toBe('payload')
|
||||
expect(result.current.description).toBe('desc')
|
||||
expect(result.current.type).toBe(ChatVarType.ArrayObject)
|
||||
expect(result.current.editInJSON).toBe(true)
|
||||
expect(result.current.editorContent).toBe(JSON.stringify([{ enabled: true }]))
|
||||
})
|
||||
|
||||
it('should update state when changing types and editing scalar values', () => {
|
||||
const { result } = renderHook(() => useVariableModalState(createOptions()))
|
||||
|
||||
act(() => {
|
||||
result.current.handleTypeChange(ChatVarType.Object)
|
||||
})
|
||||
expect(result.current.type).toBe(ChatVarType.Object)
|
||||
expect(result.current.objectValue).toHaveLength(1)
|
||||
|
||||
act(() => {
|
||||
result.current.handleTypeChange(ChatVarType.Number)
|
||||
result.current.handleStringOrNumberChange([12])
|
||||
})
|
||||
expect(result.current.value).toBe(12)
|
||||
})
|
||||
|
||||
it('should toggle object values between form and json modes', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useVariableModalState(
|
||||
createOptions({
|
||||
chatVar: {
|
||||
id: 'var-2',
|
||||
name: 'config',
|
||||
description: '',
|
||||
value_type: ChatVarType.Object,
|
||||
value: { timeout: 30 },
|
||||
},
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
act(() => {
|
||||
result.current.handleEditorChange(true)
|
||||
})
|
||||
expect(result.current.editInJSON).toBe(true)
|
||||
expect(result.current.editorContent).toBe(JSON.stringify({ timeout: 30 }))
|
||||
|
||||
act(() => {
|
||||
result.current.handleEditorValueChange('{"timeout":45}')
|
||||
result.current.handleEditorChange(false)
|
||||
})
|
||||
expect(result.current.editInJSON).toBe(false)
|
||||
expect(result.current.objectValue).toEqual([
|
||||
{ key: 'timeout', type: ChatVarType.Number, value: 45 },
|
||||
])
|
||||
})
|
||||
|
||||
it('should keep valid object rows when switching to json mode from form mode', () => {
|
||||
const { result } = renderHook(() => useVariableModalState(createOptions()))
|
||||
|
||||
act(() => {
|
||||
result.current.handleTypeChange(ChatVarType.Object)
|
||||
result.current.setObjectValue([
|
||||
{ key: '', type: ChatVarType.String, value: undefined },
|
||||
{ key: 'timeout', type: ChatVarType.Number, value: 30 },
|
||||
])
|
||||
result.current.handleEditorChange(true)
|
||||
})
|
||||
|
||||
expect(result.current.editInJSON).toBe(true)
|
||||
expect(result.current.value).toEqual({ timeout: 30 })
|
||||
expect(result.current.editorContent).toBe(JSON.stringify({ timeout: 30 }))
|
||||
})
|
||||
it('should reset object form values when leaving empty json mode', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useVariableModalState(
|
||||
createOptions({
|
||||
chatVar: {
|
||||
id: 'var-3',
|
||||
name: 'config',
|
||||
description: '',
|
||||
value_type: ChatVarType.Object,
|
||||
value: {},
|
||||
},
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
act(() => {
|
||||
result.current.handleEditorChange(true)
|
||||
result.current.handleEditorValueChange('')
|
||||
result.current.handleEditorChange(false)
|
||||
})
|
||||
|
||||
expect(result.current.objectValue).toHaveLength(1)
|
||||
expect(result.current.value).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should handle array editor toggles and invalid json safely', () => {
|
||||
const { result } = renderHook(() => useVariableModalState(createOptions()))
|
||||
|
||||
act(() => {
|
||||
result.current.handleTypeChange(ChatVarType.ArrayString)
|
||||
result.current.setValue(['a', '', 'b'])
|
||||
result.current.handleEditorChange(true)
|
||||
})
|
||||
expect(result.current.editInJSON).toBe(true)
|
||||
expect(result.current.value).toEqual(['a', 'b'])
|
||||
|
||||
act(() => {
|
||||
result.current.handleEditorValueChange('[invalid')
|
||||
})
|
||||
expect(result.current.editorContent).toBe('[invalid')
|
||||
expect(result.current.value).toEqual(['a', 'b'])
|
||||
|
||||
act(() => {
|
||||
result.current.handleEditorChange(false)
|
||||
})
|
||||
expect(result.current.value).toEqual(['a', 'b'])
|
||||
|
||||
act(() => {
|
||||
result.current.handleTypeChange(ChatVarType.ArrayBoolean)
|
||||
result.current.setValue([true, false])
|
||||
result.current.handleEditorChange(true)
|
||||
})
|
||||
expect(result.current.editorContent).toBe(JSON.stringify(['True', 'False']))
|
||||
})
|
||||
|
||||
it('should preserve zero values when switching number arrays into json mode', () => {
|
||||
const { result } = renderHook(() => useVariableModalState(createOptions()))
|
||||
|
||||
act(() => {
|
||||
result.current.handleTypeChange(ChatVarType.ArrayNumber)
|
||||
result.current.setValue([0, 2, undefined])
|
||||
result.current.handleEditorChange(true)
|
||||
})
|
||||
|
||||
expect(result.current.editInJSON).toBe(true)
|
||||
expect(result.current.value).toEqual([0, 2])
|
||||
expect(result.current.editorContent).toBe(JSON.stringify([0, 2]))
|
||||
})
|
||||
it('should notify and stop saving when object keys are invalid', () => {
|
||||
const notify = vi.fn()
|
||||
const onSave = vi.fn()
|
||||
const onClose = vi.fn()
|
||||
const { result } = renderHook(() =>
|
||||
useVariableModalState(
|
||||
createOptions({
|
||||
notify,
|
||||
onClose,
|
||||
onSave,
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
act(() => {
|
||||
result.current.handleVarNameChange({
|
||||
target: { value: 'config' },
|
||||
} as ChangeEvent<HTMLInputElement>)
|
||||
result.current.handleTypeChange(ChatVarType.Object)
|
||||
result.current.setObjectValue([{ key: '', type: ChatVarType.String, value: 'secret' }])
|
||||
})
|
||||
|
||||
act(() => {
|
||||
result.current.handleSave()
|
||||
})
|
||||
|
||||
expect(notify).toHaveBeenCalledWith({
|
||||
type: 'error',
|
||||
message: 'chatVariable.modal.objectKeyRequired',
|
||||
})
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should notify and stop saving when description exceeds the limit', () => {
|
||||
const notify = vi.fn()
|
||||
const onSave = vi.fn()
|
||||
const onClose = vi.fn()
|
||||
const { result } = renderHook(() =>
|
||||
useVariableModalState(
|
||||
createOptions({
|
||||
notify,
|
||||
onClose,
|
||||
onSave,
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
act(() => {
|
||||
result.current.handleVarNameChange({
|
||||
target: { value: 'greeting' },
|
||||
} as ChangeEvent<HTMLInputElement>)
|
||||
result.current.handleStringOrNumberChange(['hello'])
|
||||
result.current.setDescription('a'.repeat(256))
|
||||
})
|
||||
|
||||
act(() => {
|
||||
result.current.handleSave()
|
||||
})
|
||||
|
||||
expect(notify).toHaveBeenCalledWith({
|
||||
type: 'error',
|
||||
message: 'chatVariable.modal.descriptionTooLong',
|
||||
})
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should save a new variable and close when state is valid', () => {
|
||||
const onSave = vi.fn()
|
||||
const onClose = vi.fn()
|
||||
const { result } = renderHook(() =>
|
||||
useVariableModalState(
|
||||
createOptions({
|
||||
onClose,
|
||||
onSave,
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
act(() => {
|
||||
result.current.handleVarNameChange({
|
||||
target: { value: 'greeting' },
|
||||
} as ChangeEvent<HTMLInputElement>)
|
||||
result.current.handleStringOrNumberChange(['hello'])
|
||||
})
|
||||
|
||||
act(() => {
|
||||
result.current.handleSave()
|
||||
})
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith({
|
||||
description: '',
|
||||
id: expect.any(String),
|
||||
name: 'greeting',
|
||||
value: 'hello',
|
||||
value_type: ChatVarType.String,
|
||||
})
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
import type { ConversationVariable } from '@/app/components/workflow/types'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import * as React from 'react'
|
||||
import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { ChatVarType } from '../../type'
|
||||
import VariableModalTrigger from '../variable-modal-trigger'
|
||||
|
||||
vi.mock('uuid', () => ({
|
||||
v4: () => 'generated-id',
|
||||
}))
|
||||
|
||||
const createVariable = (overrides: Partial<ConversationVariable> = {}): ConversationVariable => ({
|
||||
id: 'var-1',
|
||||
name: 'conversation_var',
|
||||
description: 'Conversation scoped variable',
|
||||
value_type: ChatVarType.String,
|
||||
value: '',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('VariableModalTrigger', () => {
|
||||
it('saves through the real modal and closes the trigger', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onClose = vi.fn()
|
||||
const onSave = vi.fn()
|
||||
const Harness = () => {
|
||||
const [open, setOpen] = React.useState(false)
|
||||
return (
|
||||
<VariableModalTrigger
|
||||
open={open}
|
||||
setOpen={setOpen}
|
||||
showTip={false}
|
||||
chatVar={createVariable()}
|
||||
onClose={onClose}
|
||||
onSave={onSave}
|
||||
/>
|
||||
)
|
||||
}
|
||||
renderWorkflowComponent(<Harness />)
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.chatVariable.button' }))
|
||||
|
||||
await user.clear(screen.getByDisplayValue('conversation_var'))
|
||||
await user.type(
|
||||
screen.getByPlaceholderText('workflow.chatVariable.modal.namePlaceholder'),
|
||||
'updated_var',
|
||||
)
|
||||
await user.type(
|
||||
screen.getByPlaceholderText('workflow.chatVariable.modal.valuePlaceholder'),
|
||||
'hello',
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 'var-1',
|
||||
name: 'updated_var',
|
||||
value: 'hello',
|
||||
value_type: ChatVarType.String,
|
||||
}),
|
||||
)
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.queryByPlaceholderText('workflow.chatVariable.modal.namePlaceholder'),
|
||||
).not.toBeInTheDocument(),
|
||||
)
|
||||
})
|
||||
|
||||
it('closes when the portal dismisses', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onClose = vi.fn()
|
||||
|
||||
const TriggerHarness = () => {
|
||||
const [open, setOpen] = React.useState(true)
|
||||
|
||||
return (
|
||||
<VariableModalTrigger
|
||||
open={open}
|
||||
setOpen={setOpen}
|
||||
showTip={false}
|
||||
chatVar={createVariable()}
|
||||
onClose={onClose}
|
||||
onSave={vi.fn()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
renderWorkflowComponent(<TriggerHarness />)
|
||||
|
||||
expect(
|
||||
screen.getByPlaceholderText('workflow.chatVariable.modal.namePlaceholder'),
|
||||
).toBeInTheDocument()
|
||||
|
||||
await user.keyboard('{Escape}')
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.queryByPlaceholderText('workflow.chatVariable.modal.namePlaceholder'),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import type { TFunction } from 'i18next'
|
||||
import { withSelectorKey } from '@/test/i18n-mock'
|
||||
import { ChatVarType } from '../../type'
|
||||
import {
|
||||
buildObjectValueItems,
|
||||
formatChatVariableValue,
|
||||
formatObjectValueFromList,
|
||||
getTypeChangeState,
|
||||
parseEditorContent,
|
||||
validateVariableName,
|
||||
} from '../variable-modal.helpers'
|
||||
|
||||
describe('variable-modal helpers', () => {
|
||||
it('should build object items from a conversation variable value', () => {
|
||||
expect(buildObjectValueItems()).toHaveLength(1)
|
||||
|
||||
expect(
|
||||
buildObjectValueItems({
|
||||
id: 'var-1',
|
||||
name: 'config',
|
||||
description: '',
|
||||
value_type: ChatVarType.Object,
|
||||
value: { apiKey: 'secret', timeout: 30 },
|
||||
}),
|
||||
).toEqual([
|
||||
{ key: 'apiKey', type: ChatVarType.String, value: 'secret' },
|
||||
{ key: 'timeout', type: ChatVarType.Number, value: 30 },
|
||||
])
|
||||
})
|
||||
|
||||
it('should format object and array values for saving', () => {
|
||||
expect(
|
||||
formatObjectValueFromList([
|
||||
{ key: 'apiKey', type: ChatVarType.String, value: 'secret' },
|
||||
{ key: '', type: ChatVarType.Number, value: 1 },
|
||||
]),
|
||||
).toEqual({ apiKey: 'secret' })
|
||||
|
||||
expect(
|
||||
formatObjectValueFromList([
|
||||
{ key: 'count', type: ChatVarType.Number, value: 0 },
|
||||
{ key: 'label', type: ChatVarType.String, value: '' },
|
||||
]),
|
||||
).toEqual({ count: 0, label: null })
|
||||
expect(
|
||||
formatChatVariableValue({
|
||||
editInJSON: false,
|
||||
objectValue: [{ key: 'enabled', type: ChatVarType.String, value: 'true' }],
|
||||
type: ChatVarType.Object,
|
||||
value: undefined,
|
||||
}),
|
||||
).toEqual({ enabled: 'true' })
|
||||
|
||||
expect(
|
||||
formatChatVariableValue({
|
||||
editInJSON: true,
|
||||
objectValue: [],
|
||||
type: ChatVarType.Object,
|
||||
value: { count: 1 },
|
||||
}),
|
||||
).toEqual({ count: 1 })
|
||||
|
||||
expect(
|
||||
formatChatVariableValue({
|
||||
editInJSON: false,
|
||||
objectValue: [],
|
||||
type: ChatVarType.ArrayString,
|
||||
value: ['a', '', 'b'],
|
||||
}),
|
||||
).toEqual(['a', 'b'])
|
||||
|
||||
expect(
|
||||
formatChatVariableValue({
|
||||
editInJSON: false,
|
||||
objectValue: [],
|
||||
type: ChatVarType.ArrayNumber,
|
||||
value: [0, 1, undefined, null, ''],
|
||||
}),
|
||||
).toEqual([0, 1])
|
||||
|
||||
expect(
|
||||
formatChatVariableValue({
|
||||
editInJSON: false,
|
||||
objectValue: [],
|
||||
type: ChatVarType.Number,
|
||||
value: undefined,
|
||||
}),
|
||||
).toBe(0)
|
||||
|
||||
expect(
|
||||
formatChatVariableValue({
|
||||
editInJSON: false,
|
||||
objectValue: [],
|
||||
type: ChatVarType.Boolean,
|
||||
value: undefined,
|
||||
}),
|
||||
).toBe(true)
|
||||
|
||||
expect(
|
||||
formatChatVariableValue({
|
||||
editInJSON: false,
|
||||
objectValue: [],
|
||||
type: ChatVarType.ArrayBoolean,
|
||||
value: undefined,
|
||||
}),
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('initializes values and editing mode when changing variable types', () => {
|
||||
expect(getTypeChangeState(ChatVarType.Boolean).value).toBe(false)
|
||||
expect(getTypeChangeState(ChatVarType.ArrayBoolean).value).toEqual([false])
|
||||
expect(getTypeChangeState(ChatVarType.Object).objectValue).toHaveLength(1)
|
||||
expect(getTypeChangeState(ChatVarType.ArrayObject).editInJSON).toBe(true)
|
||||
})
|
||||
|
||||
it('should parse boolean arrays from JSON editor content', () => {
|
||||
expect(
|
||||
parseEditorContent({
|
||||
content: '["True","false",true,false,"invalid"]',
|
||||
type: ChatVarType.ArrayBoolean,
|
||||
}),
|
||||
).toEqual([true, false, true, false])
|
||||
|
||||
expect(() =>
|
||||
parseEditorContent({
|
||||
content: '{"enabled":true}',
|
||||
type: ChatVarType.ArrayBoolean,
|
||||
}),
|
||||
).toThrow('JSON array')
|
||||
expect(
|
||||
parseEditorContent({
|
||||
content: '{"enabled":true}',
|
||||
type: ChatVarType.Object,
|
||||
}),
|
||||
).toEqual({ enabled: true })
|
||||
})
|
||||
|
||||
it('should validate variable names and notify when invalid', () => {
|
||||
const notify = vi.fn()
|
||||
const t = withSelectorKey((key: string) => key) as TFunction<['appDebug', 'workflow']>
|
||||
|
||||
expect(
|
||||
validateVariableName({
|
||||
name: 'valid_name',
|
||||
notify,
|
||||
t,
|
||||
}),
|
||||
).toBe(true)
|
||||
|
||||
expect(
|
||||
validateVariableName({
|
||||
name: '1invalid',
|
||||
notify,
|
||||
t,
|
||||
}),
|
||||
).toBe(false)
|
||||
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'error',
|
||||
message: 'varKeyError.notStartWithNumber',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import * as React from 'react'
|
||||
import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { toast } from '@/app/notifications'
|
||||
import { ChatVarType } from '../../type'
|
||||
import VariableModal from '../variable-modal'
|
||||
|
||||
vi.mock('uuid', () => ({
|
||||
v4: () => 'generated-id',
|
||||
}))
|
||||
|
||||
vi.mock('@/app/notifications', async (importOriginal) => ({
|
||||
...(await importOriginal()),
|
||||
toast: {
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
success: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const renderVariableModal = (props?: Partial<React.ComponentProps<typeof VariableModal>>) => {
|
||||
const onClose = vi.fn()
|
||||
const onSave = vi.fn()
|
||||
|
||||
const result = renderWorkflowComponent(
|
||||
React.createElement(VariableModal, {
|
||||
onClose,
|
||||
onSave,
|
||||
...props,
|
||||
}),
|
||||
)
|
||||
|
||||
return { ...result, onClose, onSave }
|
||||
}
|
||||
|
||||
describe('variable-modal', () => {
|
||||
const mockToastError = vi.mocked(toast.error)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should create a new string variable and close after saving', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onClose, onSave } = renderVariableModal()
|
||||
|
||||
await user.type(
|
||||
screen.getByPlaceholderText('workflow.chatVariable.modal.namePlaceholder'),
|
||||
'greeting',
|
||||
)
|
||||
await user.type(
|
||||
screen.getByPlaceholderText('workflow.chatVariable.modal.valuePlaceholder'),
|
||||
'hello',
|
||||
)
|
||||
await user.type(
|
||||
screen.getByPlaceholderText('workflow.chatVariable.modal.descriptionPlaceholder'),
|
||||
'demo variable',
|
||||
)
|
||||
await user.click(screen.getByText('common.operation.save'))
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith({
|
||||
id: 'generated-id',
|
||||
name: 'greeting',
|
||||
value_type: ChatVarType.String,
|
||||
value: 'hello',
|
||||
description: 'demo variable',
|
||||
})
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should reject duplicate variable names from the workflow store', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onSave, store } = renderVariableModal()
|
||||
|
||||
act(() =>
|
||||
store.setState({
|
||||
conversationVariables: [
|
||||
{
|
||||
id: 'var-1',
|
||||
name: 'existing_name',
|
||||
description: '',
|
||||
value_type: ChatVarType.String,
|
||||
value: '',
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
||||
await user.type(
|
||||
screen.getByPlaceholderText('workflow.chatVariable.modal.namePlaceholder'),
|
||||
'existing_name',
|
||||
)
|
||||
await user.click(screen.getByText('common.operation.save'))
|
||||
|
||||
expect(mockToastError.mock.calls.at(-1)?.[0]).toBe(
|
||||
'appDebug.varKeyError.keyAlreadyExists:{"key":"workflow.chatVariable.modal.name"}',
|
||||
)
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should load an existing object variable and save object values edited in form mode', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onSave } = renderVariableModal({
|
||||
chatVar: {
|
||||
id: 'var-2',
|
||||
name: 'config',
|
||||
description: 'settings',
|
||||
value_type: ChatVarType.Object,
|
||||
value: { apiKey: 'secret', timeout: 30 },
|
||||
},
|
||||
})
|
||||
|
||||
expect(screen.getByDisplayValue('config')).toBeInTheDocument()
|
||||
expect(screen.getByDisplayValue('secret')).toBeInTheDocument()
|
||||
expect(screen.getByDisplayValue('30')).toBeInTheDocument()
|
||||
|
||||
const timeoutInput = screen.getByDisplayValue('30') as HTMLInputElement
|
||||
await user.clear(screen.getByDisplayValue('secret'))
|
||||
await user.clear(timeoutInput)
|
||||
await user.type(timeoutInput, '5')
|
||||
await user.click(screen.getByText('common.operation.save'))
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith({
|
||||
id: 'var-2',
|
||||
name: 'config',
|
||||
value_type: ChatVarType.Object,
|
||||
value: {
|
||||
apiKey: null,
|
||||
timeout: 5,
|
||||
},
|
||||
description: 'settings',
|
||||
})
|
||||
})
|
||||
|
||||
it('should switch types and use default values for boolean arrays', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onSave } = renderVariableModal()
|
||||
|
||||
await user.type(
|
||||
screen.getByPlaceholderText('workflow.chatVariable.modal.namePlaceholder'),
|
||||
'flags',
|
||||
)
|
||||
await user.click(screen.getByText('string'))
|
||||
await user.click(screen.getByText('array[boolean]'))
|
||||
await user.click(screen.getByText('common.operation.save'))
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith({
|
||||
id: 'generated-id',
|
||||
name: 'flags',
|
||||
value_type: ChatVarType.ArrayBoolean,
|
||||
value: [false],
|
||||
description: '',
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves object values when switching between JSON and form modes', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onSave } = renderVariableModal({
|
||||
chatVar: {
|
||||
id: 'var-3',
|
||||
name: 'payload',
|
||||
description: '',
|
||||
value_type: ChatVarType.Object,
|
||||
value: { enabled: 1 },
|
||||
},
|
||||
})
|
||||
|
||||
await user.click(screen.getByText('workflow.chatVariable.modal.editInJSON'))
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('monaco-editor')).toBeInTheDocument()
|
||||
})
|
||||
await user.click(screen.getByText('workflow.chatVariable.modal.editInForm'))
|
||||
expect(screen.getByDisplayValue('enabled')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
|
||||
expect(onSave).toHaveBeenCalledWith({
|
||||
id: 'var-3',
|
||||
name: 'payload',
|
||||
description: '',
|
||||
value_type: ChatVarType.Object,
|
||||
value: { enabled: 1 },
|
||||
})
|
||||
})
|
||||
|
||||
it('normalizes spaces in the saved variable name on blur', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onSave } = renderVariableModal()
|
||||
const input = screen.getByPlaceholderText('workflow.chatVariable.modal.namePlaceholder')
|
||||
|
||||
await user.type(input, 'bad name')
|
||||
await user.tab()
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
|
||||
|
||||
expect(input).toHaveValue('bad_name')
|
||||
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ name: 'bad_name' }))
|
||||
expect(mockToastError).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should stop invalid variable names before they are stored in local state', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onSave } = renderVariableModal()
|
||||
const input = screen.getByPlaceholderText(
|
||||
'workflow.chatVariable.modal.namePlaceholder',
|
||||
) as HTMLInputElement
|
||||
|
||||
fireEvent.change(input, { target: { value: '1bad' } })
|
||||
await user.click(screen.getByText('common.operation.save'))
|
||||
|
||||
expect(input).toHaveValue('')
|
||||
expect(mockToastError).toHaveBeenCalled()
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should edit number variables through the value input', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onSave } = renderVariableModal()
|
||||
|
||||
await user.type(
|
||||
screen.getByPlaceholderText('workflow.chatVariable.modal.namePlaceholder'),
|
||||
'timeout',
|
||||
)
|
||||
await user.click(screen.getByText('string'))
|
||||
await user.click(screen.getByText('number'))
|
||||
await user.type(
|
||||
screen.getByPlaceholderText('workflow.chatVariable.modal.valuePlaceholder'),
|
||||
'3',
|
||||
)
|
||||
await user.click(screen.getByText('common.operation.save'))
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith({
|
||||
id: 'generated-id',
|
||||
name: 'timeout',
|
||||
value_type: ChatVarType.Number,
|
||||
value: 3,
|
||||
description: '',
|
||||
})
|
||||
})
|
||||
|
||||
it('should keep the number input empty while editing after the user clears it', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderVariableModal({
|
||||
chatVar: {
|
||||
id: 'var-4',
|
||||
name: 'timeout',
|
||||
description: '',
|
||||
value_type: ChatVarType.Number,
|
||||
value: 3,
|
||||
},
|
||||
})
|
||||
|
||||
const input = screen.getByRole('textbox', { name: 'workflow.chatVariable.modal.value' })
|
||||
await user.clear(input)
|
||||
|
||||
expect(input).toHaveValue('')
|
||||
})
|
||||
})
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import VariableTypeSelector from '../variable-type-select'
|
||||
|
||||
describe('VariableTypeSelector', () => {
|
||||
it('opens the selector and applies a new type', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onSelect = vi.fn()
|
||||
render(
|
||||
<VariableTypeSelector
|
||||
value="string"
|
||||
list={['string', 'number', 'boolean']}
|
||||
onSelect={onSelect}
|
||||
/>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('combobox'))
|
||||
await user.click(await screen.findByRole('option', { name: 'number' }))
|
||||
|
||||
expect(onSelect).toHaveBeenCalledWith('number')
|
||||
})
|
||||
})
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { RiAddLine } from '@remixicon/react'
|
||||
import { produce } from 'immer'
|
||||
import * as React from 'react'
|
||||
import { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import RemoveButton from '@/app/components/workflow/nodes/_base/components/remove-button'
|
||||
import BoolValue from './bool-value'
|
||||
|
||||
type Props = Readonly<{
|
||||
className?: string
|
||||
list: boolean[]
|
||||
onChange: (list: boolean[]) => void
|
||||
}>
|
||||
|
||||
const ArrayValueList: FC<Props> = ({ className, list, onChange }) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
|
||||
const handleChange = useCallback(
|
||||
(index: number) => {
|
||||
return (value: boolean) => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft[index] = value
|
||||
})
|
||||
onChange(newList)
|
||||
}
|
||||
},
|
||||
[list, onChange],
|
||||
)
|
||||
|
||||
const handleItemRemove = useCallback(
|
||||
(index: number) => {
|
||||
return () => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft.splice(index, 1)
|
||||
})
|
||||
onChange(newList)
|
||||
}
|
||||
},
|
||||
[list, onChange],
|
||||
)
|
||||
|
||||
const handleItemAdd = useCallback(() => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft.push(false)
|
||||
})
|
||||
onChange(newList)
|
||||
}, [list, onChange])
|
||||
|
||||
return (
|
||||
<div className={cn('w-full space-y-2', className)}>
|
||||
{list.map((item, index) => (
|
||||
<div className="flex items-center space-x-1" key={index}>
|
||||
<BoolValue value={item} onChange={handleChange(index)} />
|
||||
|
||||
<RemoveButton
|
||||
className="bg-gray-100! p-2! hover:bg-gray-200!"
|
||||
onClick={handleItemRemove(index)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<Button variant="tertiary" className="w-full" onClick={handleItemAdd}>
|
||||
<RiAddLine className="size-4" />
|
||||
<span>{t(($) => $['chatVariable.modal.addArrayValue'], { ns: 'workflow' })}</span>
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(ArrayValueList)
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { Input } from '@langgenius/dify-ui/input'
|
||||
import { NumberField, NumberFieldGroup, NumberFieldInput } from '@langgenius/dify-ui/number-field'
|
||||
import { RiAddLine } from '@remixicon/react'
|
||||
import { produce } from 'immer'
|
||||
import * as React from 'react'
|
||||
import { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import RemoveButton from '@/app/components/workflow/nodes/_base/components/remove-button'
|
||||
|
||||
type Props = Readonly<{
|
||||
isString: boolean
|
||||
list: Array<string | number | undefined>
|
||||
onChange: (list: Array<string | number | undefined>) => void
|
||||
}>
|
||||
|
||||
const ArrayValueList: FC<Props> = ({ isString = true, list, onChange }) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
|
||||
const handleValueChange = useCallback(
|
||||
(index: number) => {
|
||||
return (value: string | number | undefined) => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft[index] = value
|
||||
})
|
||||
onChange(newList)
|
||||
}
|
||||
},
|
||||
[list, onChange],
|
||||
)
|
||||
|
||||
const handleItemRemove = useCallback(
|
||||
(index: number) => {
|
||||
return () => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft.splice(index, 1)
|
||||
})
|
||||
onChange(newList)
|
||||
}
|
||||
},
|
||||
[list, onChange],
|
||||
)
|
||||
|
||||
const handleItemAdd = useCallback(() => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft.push(undefined)
|
||||
})
|
||||
onChange(newList)
|
||||
}, [list, onChange])
|
||||
|
||||
return (
|
||||
<div className="w-full space-y-2">
|
||||
{list.map((item, index) => (
|
||||
<div className="flex items-center gap-1" key={index}>
|
||||
{isString ? (
|
||||
<Input
|
||||
className="min-w-0 flex-1"
|
||||
aria-label={`${t(($) => $['chatVariable.modal.arrayValue'], { ns: 'workflow' })} ${index + 1}`}
|
||||
placeholder={t(($) => $['chatVariable.modal.arrayValue'], { ns: 'workflow' })}
|
||||
value={typeof item === 'string' ? item : ''}
|
||||
onValueChange={handleValueChange(index)}
|
||||
/>
|
||||
) : (
|
||||
<NumberField
|
||||
format={{ maximumSignificantDigits: 21, useGrouping: false }}
|
||||
className="min-w-0 flex-1"
|
||||
value={typeof item === 'number' ? item : null}
|
||||
onValueChange={(value) => handleValueChange(index)(value ?? undefined)}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldInput
|
||||
inputMode="decimal"
|
||||
aria-label={`${t(($) => $['chatVariable.modal.arrayValue'], { ns: 'workflow' })} ${index + 1}`}
|
||||
placeholder={t(($) => $['chatVariable.modal.arrayValue'], { ns: 'workflow' })}
|
||||
/>
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
)}
|
||||
<RemoveButton
|
||||
className="bg-gray-100! p-2! hover:bg-gray-200!"
|
||||
onClick={handleItemRemove(index)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<Button variant="tertiary" className="w-full" onClick={handleItemAdd}>
|
||||
<RiAddLine className="size-4" aria-hidden />
|
||||
<span>{t(($) => $['chatVariable.modal.addArrayValue'], { ns: 'workflow' })}</span>
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(ArrayValueList)
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import * as React from 'react'
|
||||
import { useCallback } from 'react'
|
||||
import OptionCard from '../../../nodes/_base/components/option-card'
|
||||
|
||||
type Props = Readonly<{
|
||||
value: boolean
|
||||
disabled?: boolean
|
||||
onChange: (value: boolean) => void
|
||||
}>
|
||||
|
||||
const BoolValue: FC<Props> = ({ value, onChange, disabled }) => {
|
||||
const booleanValue = value
|
||||
const handleChange = useCallback(
|
||||
(newValue: boolean) => {
|
||||
return () => {
|
||||
onChange(newValue)
|
||||
}
|
||||
},
|
||||
[onChange],
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex w-full space-x-1">
|
||||
<OptionCard
|
||||
className="grow"
|
||||
disabled={disabled}
|
||||
selected={booleanValue}
|
||||
title="True"
|
||||
onSelect={handleChange(true)}
|
||||
/>
|
||||
<OptionCard
|
||||
className="grow"
|
||||
disabled={disabled}
|
||||
selected={!booleanValue}
|
||||
title="False"
|
||||
onSelect={handleChange(false)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(BoolValue)
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { produce } from 'immer'
|
||||
import * as React from 'react'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import VariableTypeSelector from '@/app/components/workflow/panel/chat-variable-panel/components/variable-type-select'
|
||||
import { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'
|
||||
import { toast } from '@/app/notifications'
|
||||
|
||||
type Props = Readonly<{
|
||||
index: number
|
||||
list: any[]
|
||||
onChange: (list: any[]) => void
|
||||
}>
|
||||
|
||||
const typeList = [ChatVarType.String, ChatVarType.Number]
|
||||
|
||||
export const DEFAULT_OBJECT_VALUE = {
|
||||
key: '',
|
||||
type: ChatVarType.String,
|
||||
value: undefined,
|
||||
}
|
||||
|
||||
const ObjectValueItem: FC<Props> = ({ index, list, onChange }) => {
|
||||
const { t } = useTranslation(['common', 'workflow'])
|
||||
const [isFocus, setIsFocus] = useState(false)
|
||||
|
||||
const handleKeyChange = useCallback(
|
||||
(index: number) => {
|
||||
return (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (!/^\w+$/.test(e.target.value)) {
|
||||
toast.error(t(($) => $['chatVariable.modal.objectKeyPatternError'], { ns: 'workflow' }))
|
||||
return
|
||||
}
|
||||
|
||||
const newList = produce(list, (draft: any[]) => {
|
||||
draft[index].key = e.target.value
|
||||
})
|
||||
onChange(newList)
|
||||
}
|
||||
},
|
||||
[list, onChange, t],
|
||||
)
|
||||
|
||||
const handleTypeChange = useCallback(
|
||||
(index: number) => {
|
||||
return (type: ChatVarType) => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft[index].type = type
|
||||
if (type === ChatVarType.Number)
|
||||
draft[index].value = Number.isNaN(Number(draft[index].value))
|
||||
? undefined
|
||||
: Number(draft[index].value)
|
||||
else draft[index].value = draft[index].value ? String(draft[index].value) : undefined
|
||||
})
|
||||
onChange(newList)
|
||||
}
|
||||
},
|
||||
[list, onChange],
|
||||
)
|
||||
|
||||
const handleValueChange = useCallback(
|
||||
(index: number) => {
|
||||
return (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newList = produce(list, (draft: any[]) => {
|
||||
draft[index].value =
|
||||
draft[index].type === ChatVarType.String
|
||||
? e.target.value
|
||||
: Number.isNaN(Number(e.target.value))
|
||||
? undefined
|
||||
: Number(e.target.value)
|
||||
})
|
||||
onChange(newList)
|
||||
}
|
||||
},
|
||||
[list, onChange],
|
||||
)
|
||||
|
||||
const handleItemRemove = useCallback(
|
||||
(index: number) => {
|
||||
return () => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft.splice(index, 1)
|
||||
})
|
||||
onChange(newList)
|
||||
}
|
||||
},
|
||||
[list, onChange],
|
||||
)
|
||||
|
||||
const handleItemAdd = useCallback(() => {
|
||||
const newList = produce(list, (draft: any[]) => {
|
||||
draft.push(DEFAULT_OBJECT_VALUE)
|
||||
})
|
||||
onChange(newList)
|
||||
}, [list, onChange])
|
||||
|
||||
const handleFocusChange = useCallback(() => {
|
||||
setIsFocus(true)
|
||||
if (index === list.length - 1) handleItemAdd()
|
||||
}, [handleItemAdd, index, list.length])
|
||||
|
||||
return (
|
||||
<div className="group flex border-t border-gray-200">
|
||||
{/* Key */}
|
||||
<div className="w-30 border-r border-gray-200">
|
||||
<input
|
||||
className="block h-7 w-full appearance-none px-2 system-xs-regular text-text-secondary caret-primary-600 outline-hidden placeholder:system-xs-regular placeholder:text-components-input-text-placeholder hover:bg-state-base-hover focus:bg-components-input-bg-active"
|
||||
placeholder={t(($) => $['chatVariable.modal.objectKey'], { ns: 'workflow' })}
|
||||
value={list[index].key}
|
||||
onChange={handleKeyChange(index)}
|
||||
/>
|
||||
</div>
|
||||
{/* Type */}
|
||||
<div className="w-24 border-r border-gray-200">
|
||||
<VariableTypeSelector
|
||||
inCell
|
||||
value={list[index].type}
|
||||
list={typeList}
|
||||
onSelect={handleTypeChange(index)}
|
||||
popupClassName="w-[120px]"
|
||||
/>
|
||||
</div>
|
||||
{/* Value */}
|
||||
<div className="relative w-57.5">
|
||||
<input
|
||||
className="block h-7 w-full appearance-none px-2 pr-9 system-xs-regular text-text-secondary caret-primary-600 outline-hidden placeholder:system-xs-regular placeholder:text-components-input-text-placeholder hover:bg-state-base-hover focus:bg-components-input-bg-active"
|
||||
placeholder={t(($) => $['chatVariable.modal.objectValue'], { ns: 'workflow' })}
|
||||
value={list[index].value}
|
||||
onChange={handleValueChange(index)}
|
||||
onFocus={() => handleFocusChange()}
|
||||
onBlur={() => setIsFocus(false)}
|
||||
type={list[index].type === ChatVarType.Number ? 'number' : 'text'}
|
||||
/>
|
||||
{list.length > 1 && !isFocus && (
|
||||
<div className="absolute top-0.5 right-1 z-10">
|
||||
<IconButton
|
||||
aria-label={t(($) => $['operation.remove'], { ns: 'common' })}
|
||||
size="md"
|
||||
tone="destructive"
|
||||
onClick={handleItemRemove(index)}
|
||||
>
|
||||
<span aria-hidden="true" className="i-ri-delete-bin-line size-4" />
|
||||
</IconButton>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(ObjectValueItem)
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import ObjectValueItem from '@/app/components/workflow/panel/chat-variable-panel/components/object-value-item'
|
||||
|
||||
type Props = Readonly<{
|
||||
list: any[]
|
||||
onChange: (list: any[]) => void
|
||||
}>
|
||||
|
||||
const ObjectValueList: FC<Props> = ({ list, onChange }) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
|
||||
return (
|
||||
<div className="w-full overflow-hidden rounded-lg border border-gray-200">
|
||||
<div className="flex h-7 items-center system-xs-medium-uppercase text-text-tertiary">
|
||||
<div className="flex h-full w-30 items-center border-r border-gray-200 pl-2">
|
||||
{t(($) => $['chatVariable.modal.objectKey'], { ns: 'workflow' })}
|
||||
</div>
|
||||
<div className="flex h-full w-24 items-center border-r border-gray-200 pl-2">
|
||||
{t(($) => $['chatVariable.modal.objectType'], { ns: 'workflow' })}
|
||||
</div>
|
||||
<div className="flex h-full w-57.5 items-center pr-1 pl-2">
|
||||
{t(($) => $['chatVariable.modal.objectValue'], { ns: 'workflow' })}
|
||||
</div>
|
||||
</div>
|
||||
{list.map((item, index) => (
|
||||
<ObjectValueItem key={index} index={index} list={list} onChange={onChange} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(ObjectValueList)
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
import type {
|
||||
ChatVariableTranslator,
|
||||
ObjectValueItem,
|
||||
ToastPayload,
|
||||
} from './variable-modal.helpers'
|
||||
import type { ConversationVariable } from '@/app/components/workflow/types'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { v4 as uuid4 } from 'uuid'
|
||||
import { DEFAULT_OBJECT_VALUE } from '@/app/components/workflow/panel/chat-variable-panel/components/object-value-item'
|
||||
import { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'
|
||||
import {
|
||||
buildObjectValueItems,
|
||||
formatChatVariableValue,
|
||||
formatObjectValueFromList,
|
||||
getEditorMinHeight,
|
||||
getPlaceholderByType,
|
||||
getTypeChangeState,
|
||||
MAX_DESCRIPTION_LENGTH,
|
||||
parseEditorContent,
|
||||
validateVariableName,
|
||||
} from './variable-modal.helpers'
|
||||
|
||||
type UseVariableModalStateOptions = {
|
||||
chatVar?: ConversationVariable
|
||||
conversationVariables: ConversationVariable[]
|
||||
notify: (props: ToastPayload) => void
|
||||
onClose: () => void
|
||||
onSave: (chatVar: ConversationVariable) => void
|
||||
t: ChatVariableTranslator
|
||||
}
|
||||
|
||||
type VariableModalState = {
|
||||
description: string
|
||||
editInJSON: boolean
|
||||
editorContent?: string
|
||||
name: string
|
||||
objectValue: ObjectValueItem[]
|
||||
type: ChatVarType
|
||||
value: unknown
|
||||
}
|
||||
|
||||
const buildObjectValueListFromRecord = (record: Record<string, string | number>) => {
|
||||
return Object.keys(record).map((key) => ({
|
||||
key,
|
||||
type: typeof record[key] === 'string' ? ChatVarType.String : ChatVarType.Number,
|
||||
value: record[key],
|
||||
}))
|
||||
}
|
||||
|
||||
const buildInitialState = (chatVar?: ConversationVariable): VariableModalState => {
|
||||
if (!chatVar) {
|
||||
return {
|
||||
description: '',
|
||||
editInJSON: false,
|
||||
editorContent: undefined,
|
||||
name: '',
|
||||
objectValue: [DEFAULT_OBJECT_VALUE],
|
||||
type: ChatVarType.String,
|
||||
value: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
description: chatVar.description,
|
||||
editInJSON: chatVar.value_type === ChatVarType.ArrayObject,
|
||||
editorContent:
|
||||
chatVar.value_type === ChatVarType.ArrayObject ? JSON.stringify(chatVar.value) : undefined,
|
||||
name: chatVar.name,
|
||||
objectValue: buildObjectValueItems(chatVar),
|
||||
type: chatVar.value_type,
|
||||
value: chatVar.value,
|
||||
}
|
||||
}
|
||||
|
||||
export const useVariableModalState = ({
|
||||
chatVar,
|
||||
conversationVariables,
|
||||
notify,
|
||||
onClose,
|
||||
onSave,
|
||||
t,
|
||||
}: UseVariableModalStateOptions) => {
|
||||
const [state, setState] = useState<VariableModalState>(() => buildInitialState(chatVar))
|
||||
|
||||
const editorMinHeight = useMemo(() => getEditorMinHeight(state.type), [state.type])
|
||||
const placeholder = useMemo(() => getPlaceholderByType(state.type), [state.type])
|
||||
|
||||
const handleVarNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setState((prev) => ({ ...prev, name: e.target.value || '' }))
|
||||
}
|
||||
|
||||
const handleTypeChange = (nextType: ChatVarType) => {
|
||||
const nextState = getTypeChangeState(nextType)
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
editInJSON: nextState.editInJSON,
|
||||
editorContent: nextState.editorContent,
|
||||
objectValue: nextState.objectValue ?? prev.objectValue,
|
||||
type: nextType,
|
||||
value: nextState.value,
|
||||
}))
|
||||
}
|
||||
|
||||
const handleStringOrNumberChange = (nextValue: Array<string | number | undefined>) => {
|
||||
setState((prev) => ({ ...prev, value: nextValue[0] }))
|
||||
}
|
||||
|
||||
const handleEditorChange = (nextEditInJSON: boolean) => {
|
||||
setState((prev) => {
|
||||
const nextState: VariableModalState = {
|
||||
...prev,
|
||||
editInJSON: nextEditInJSON,
|
||||
}
|
||||
|
||||
if (prev.type === ChatVarType.Object) {
|
||||
if (nextEditInJSON) {
|
||||
const nextValue = prev.objectValue.some((item) => item.key)
|
||||
? formatObjectValueFromList(prev.objectValue)
|
||||
: undefined
|
||||
nextState.value = nextValue
|
||||
nextState.editorContent = JSON.stringify(nextValue)
|
||||
return nextState
|
||||
}
|
||||
|
||||
if (!prev.editorContent) {
|
||||
nextState.value = undefined
|
||||
nextState.objectValue = [DEFAULT_OBJECT_VALUE]
|
||||
return nextState
|
||||
}
|
||||
|
||||
try {
|
||||
const nextValue = JSON.parse(prev.editorContent) as Record<string, string | number>
|
||||
nextState.value = nextValue
|
||||
nextState.objectValue = buildObjectValueListFromRecord(nextValue)
|
||||
} catch {
|
||||
// ignore JSON.parse errors
|
||||
}
|
||||
return nextState
|
||||
}
|
||||
|
||||
if (prev.type === ChatVarType.ArrayString || prev.type === ChatVarType.ArrayNumber) {
|
||||
if (nextEditInJSON) {
|
||||
const compactValues = Array.isArray(prev.value)
|
||||
? prev.value.filter((item) => item !== null && item !== undefined && item !== '')
|
||||
: []
|
||||
const nextValue = compactValues.length ? compactValues : undefined
|
||||
nextState.value = nextValue
|
||||
if (!prev.editorContent) nextState.editorContent = JSON.stringify(nextValue)
|
||||
return nextState
|
||||
}
|
||||
|
||||
nextState.value = Array.isArray(prev.value) && prev.value.length ? prev.value : [undefined]
|
||||
return nextState
|
||||
}
|
||||
|
||||
if (prev.type === ChatVarType.ArrayBoolean && Array.isArray(prev.value) && nextEditInJSON)
|
||||
nextState.editorContent = JSON.stringify(
|
||||
prev.value.map((item) => (item ? 'True' : 'False')),
|
||||
)
|
||||
|
||||
return nextState
|
||||
})
|
||||
}
|
||||
|
||||
const handleEditorValueChange = (content: string) => {
|
||||
setState((prev) => {
|
||||
const nextState: VariableModalState = {
|
||||
...prev,
|
||||
editorContent: content,
|
||||
}
|
||||
|
||||
if (!content) {
|
||||
nextState.value = undefined
|
||||
return nextState
|
||||
}
|
||||
|
||||
try {
|
||||
nextState.value = parseEditorContent({ content, type: prev.type })
|
||||
} catch {
|
||||
// ignore JSON.parse errors
|
||||
}
|
||||
|
||||
return nextState
|
||||
})
|
||||
}
|
||||
|
||||
const handleSave = () => {
|
||||
if (!validateVariableName({ name: state.name, notify, t })) return
|
||||
|
||||
if (!chatVar && conversationVariables.some((item) => item.name === state.name)) {
|
||||
notify({
|
||||
type: 'error',
|
||||
message: t(($) => $['varKeyError.keyAlreadyExists'], {
|
||||
ns: 'appDebug',
|
||||
key: t(($) => $['chatVariable.modal.name'], { ns: 'workflow' }),
|
||||
}),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
state.type === ChatVarType.Object &&
|
||||
state.objectValue.some((item) => !item.key && item.value !== undefined && item.value !== '')
|
||||
) {
|
||||
notify({
|
||||
type: 'error',
|
||||
message: t(($) => $['chatVariable.modal.objectKeyRequired'], { ns: 'workflow' }),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (state.description.length > MAX_DESCRIPTION_LENGTH) {
|
||||
notify({
|
||||
type: 'error',
|
||||
message: t(($) => $['chatVariable.modal.descriptionTooLong'], {
|
||||
maxLength: MAX_DESCRIPTION_LENGTH,
|
||||
ns: 'workflow',
|
||||
}),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
onSave({
|
||||
description: state.description,
|
||||
id: chatVar ? chatVar.id : uuid4(),
|
||||
name: state.name,
|
||||
value: formatChatVariableValue({
|
||||
editInJSON: state.editInJSON,
|
||||
objectValue: state.objectValue,
|
||||
type: state.type,
|
||||
value: state.value,
|
||||
}),
|
||||
value_type: state.type,
|
||||
})
|
||||
onClose()
|
||||
}
|
||||
|
||||
return {
|
||||
description: state.description,
|
||||
editInJSON: state.editInJSON,
|
||||
editorContent: state.editorContent,
|
||||
editorMinHeight,
|
||||
handleEditorChange,
|
||||
handleEditorValueChange,
|
||||
handleSave,
|
||||
handleStringOrNumberChange,
|
||||
handleTypeChange,
|
||||
handleVarNameChange,
|
||||
name: state.name,
|
||||
objectValue: state.objectValue,
|
||||
placeholder,
|
||||
setDescription: (description: string) => setState((prev) => ({ ...prev, description })),
|
||||
setObjectValue: (objectValue: ObjectValueItem[]) =>
|
||||
setState((prev) => ({ ...prev, objectValue })),
|
||||
setValue: (value: unknown) => setState((prev) => ({ ...prev, value })),
|
||||
type: state.type,
|
||||
value: state.value,
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import type { ConversationVariable } from '@/app/components/workflow/types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { RiDeleteBinLine, RiEditLine } from '@remixicon/react'
|
||||
import { capitalize } from 'es-toolkit/string'
|
||||
import { memo, useState } from 'react'
|
||||
|
||||
type VariableItemProps = {
|
||||
item: ConversationVariable
|
||||
onEdit: (item: ConversationVariable) => void
|
||||
onDelete: (item: ConversationVariable) => void
|
||||
}
|
||||
|
||||
const VariableItem = ({ item, onEdit, onDelete }: VariableItemProps) => {
|
||||
const [destructive, setDestructive] = useState(false)
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'mb-1 rounded-lg border border-components-panel-border-subtle bg-components-panel-on-panel-item-bg px-2.5 py-2 shadow-xs hover:bg-components-panel-on-panel-item-bg-hover',
|
||||
destructive && 'border-state-destructive-border hover:bg-state-destructive-hover',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex grow items-center gap-1">
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-custom-vender-line-others-bubble-x size-4 text-util-colors-teal-teal-700"
|
||||
/>
|
||||
<div className="system-sm-medium text-text-primary">{item.name}</div>
|
||||
<div className="system-xs-medium text-text-tertiary">{capitalize(item.value_type)}</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1 text-text-tertiary">
|
||||
<div className="cursor-pointer rounded-lg p-1 hover:bg-state-base-hover hover:text-text-secondary">
|
||||
<RiEditLine className="size-4" onClick={() => onEdit(item)} />
|
||||
</div>
|
||||
<div
|
||||
className="cursor-pointer rounded-lg p-1 hover:bg-state-destructive-hover hover:text-text-destructive"
|
||||
onMouseOver={() => setDestructive(true)}
|
||||
onMouseOut={() => setDestructive(false)}
|
||||
>
|
||||
<RiDeleteBinLine className="size-4" onClick={() => onDelete(item)} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="truncate system-xs-regular text-text-tertiary">{item.description}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(VariableItem)
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
'use client'
|
||||
import type { ConversationVariable } from '@/app/components/workflow/types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
|
||||
import { RiAddLine } from '@remixicon/react'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import VariableModal from '@/app/components/workflow/panel/chat-variable-panel/components/variable-modal'
|
||||
|
||||
type Props = Readonly<{
|
||||
open: boolean
|
||||
setOpen: (value: React.SetStateAction<boolean>) => void
|
||||
showTip: boolean
|
||||
chatVar?: ConversationVariable
|
||||
onClose: () => void
|
||||
onSave: (env: ConversationVariable) => void
|
||||
}>
|
||||
|
||||
const VariableModalTrigger = ({ open, setOpen, showTip, chatVar, onClose, onSave }: Props) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const handleOpenChange = React.useCallback(
|
||||
(nextOpen: boolean) => {
|
||||
setOpen(nextOpen)
|
||||
if (!nextOpen) onClose()
|
||||
},
|
||||
[onClose, setOpen],
|
||||
)
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={handleOpenChange}>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button variant="primary">
|
||||
<RiAddLine className="size-4" />
|
||||
<span className="system-sm-medium">
|
||||
{t(($) => $['chatVariable.button'], { ns: 'workflow' })}
|
||||
</span>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<PopoverContent
|
||||
side="left"
|
||||
align="start"
|
||||
alignOffset={showTip ? -278 : -48}
|
||||
className="border-none bg-transparent shadow-none"
|
||||
>
|
||||
<VariableModal
|
||||
chatVar={chatVar}
|
||||
onSave={onSave}
|
||||
onClose={() => {
|
||||
onClose()
|
||||
setOpen(false)
|
||||
}}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
export default VariableModalTrigger
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
import type { SelectorParam, TFunction } from 'i18next'
|
||||
import type { ReactNode } from 'react'
|
||||
import type { ChatVarType } from '../type'
|
||||
import type { ConversationVariable } from '@/app/components/workflow/types'
|
||||
import { checkKeys } from '@/utils/var'
|
||||
import { ChatVarType as ChatVarTypeEnum } from '../type'
|
||||
import {
|
||||
arrayBoolPlaceholder,
|
||||
arrayNumberPlaceholder,
|
||||
arrayObjectPlaceholder,
|
||||
arrayStringPlaceholder,
|
||||
objectPlaceholder,
|
||||
} from '../utils'
|
||||
import { DEFAULT_OBJECT_VALUE } from './object-value-item'
|
||||
|
||||
export type ObjectValueItem = {
|
||||
key: string
|
||||
type: ChatVarType
|
||||
value: string | number | undefined
|
||||
}
|
||||
|
||||
export type ToastPayload = {
|
||||
type?: 'success' | 'error' | 'warning' | 'info'
|
||||
size?: 'md' | 'sm'
|
||||
duration?: number
|
||||
message: string
|
||||
children?: ReactNode
|
||||
onClose?: () => void
|
||||
className?: string
|
||||
customComponent?: ReactNode
|
||||
}
|
||||
|
||||
export const MAX_DESCRIPTION_LENGTH = 255
|
||||
|
||||
export type ChatVariableTranslator = TFunction<['appDebug', 'workflow']>
|
||||
|
||||
type VariableNameErrorKey = Exclude<ReturnType<typeof checkKeys>['errorMessageKey'], ''>
|
||||
|
||||
const variableNameErrorSelectors: Record<VariableNameErrorKey, SelectorParam<'appDebug'>> = {
|
||||
canNoBeEmpty: ($) => $['varKeyError.canNoBeEmpty'],
|
||||
keyAlreadyExists: ($) => $['varKeyError.keyAlreadyExists'],
|
||||
notStartWithNumber: ($) => $['varKeyError.notStartWithNumber'],
|
||||
notValid: ($) => $['varKeyError.notValid'],
|
||||
tooLong: ($) => $['varKeyError.tooLong'],
|
||||
}
|
||||
|
||||
export const typeList = [
|
||||
ChatVarTypeEnum.String,
|
||||
ChatVarTypeEnum.Number,
|
||||
ChatVarTypeEnum.Boolean,
|
||||
ChatVarTypeEnum.Object,
|
||||
ChatVarTypeEnum.ArrayString,
|
||||
ChatVarTypeEnum.ArrayNumber,
|
||||
ChatVarTypeEnum.ArrayBoolean,
|
||||
ChatVarTypeEnum.ArrayObject,
|
||||
]
|
||||
|
||||
export const getEditorMinHeight = (type: ChatVarType) =>
|
||||
type === ChatVarTypeEnum.ArrayObject ? '240px' : '120px'
|
||||
|
||||
export const getPlaceholderByType = (type: ChatVarType) => {
|
||||
if (type === ChatVarTypeEnum.ArrayString) return arrayStringPlaceholder
|
||||
if (type === ChatVarTypeEnum.ArrayNumber) return arrayNumberPlaceholder
|
||||
if (type === ChatVarTypeEnum.ArrayObject) return arrayObjectPlaceholder
|
||||
if (type === ChatVarTypeEnum.ArrayBoolean) return arrayBoolPlaceholder
|
||||
return objectPlaceholder
|
||||
}
|
||||
|
||||
export const buildObjectValueItems = (chatVar?: ConversationVariable): ObjectValueItem[] => {
|
||||
if (!chatVar || !chatVar.value || Object.keys(chatVar.value).length === 0)
|
||||
return [DEFAULT_OBJECT_VALUE]
|
||||
|
||||
return Object.keys(chatVar.value).map((key) => {
|
||||
const itemValue = chatVar.value[key]
|
||||
return {
|
||||
key,
|
||||
type: typeof itemValue === 'string' ? ChatVarTypeEnum.String : ChatVarTypeEnum.Number,
|
||||
value: itemValue,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const formatObjectValueFromList = (list: ObjectValueItem[]) => {
|
||||
return list.reduce<Record<string, string | number | null>>((acc, curr) => {
|
||||
if (curr.key) acc[curr.key] = curr.value === '' || curr.value === undefined ? null : curr.value
|
||||
return acc
|
||||
}, {})
|
||||
}
|
||||
|
||||
export const formatChatVariableValue = ({
|
||||
editInJSON,
|
||||
objectValue,
|
||||
type,
|
||||
value,
|
||||
}: {
|
||||
editInJSON: boolean
|
||||
objectValue: ObjectValueItem[]
|
||||
type: ChatVarType
|
||||
value: unknown
|
||||
}) => {
|
||||
const compactArrayValue = (items: unknown[]) =>
|
||||
items.filter((item) => item !== null && item !== undefined && item !== '')
|
||||
switch (type) {
|
||||
case ChatVarTypeEnum.String:
|
||||
return value || ''
|
||||
case ChatVarTypeEnum.Number:
|
||||
return value || 0
|
||||
case ChatVarTypeEnum.Boolean:
|
||||
return value === undefined ? true : value
|
||||
case ChatVarTypeEnum.Object:
|
||||
return editInJSON ? value : formatObjectValueFromList(objectValue)
|
||||
case ChatVarTypeEnum.ArrayString:
|
||||
case ChatVarTypeEnum.ArrayNumber:
|
||||
case ChatVarTypeEnum.ArrayObject:
|
||||
return Array.isArray(value) ? compactArrayValue(value) : []
|
||||
case ChatVarTypeEnum.ArrayBoolean:
|
||||
return value || []
|
||||
}
|
||||
}
|
||||
|
||||
export const validateVariableName = ({
|
||||
name,
|
||||
notify,
|
||||
t,
|
||||
}: {
|
||||
name: string
|
||||
notify: (props: ToastPayload) => void
|
||||
t: ChatVariableTranslator
|
||||
}) => {
|
||||
const { isValid, errorMessageKey } = checkKeys([name], false)
|
||||
if (!isValid) {
|
||||
notify({
|
||||
type: 'error',
|
||||
message: t(variableNameErrorSelectors[errorMessageKey], {
|
||||
ns: 'appDebug',
|
||||
key: t(($) => $['env.modal.name'], { ns: 'workflow' }),
|
||||
}),
|
||||
})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
export const getTypeChangeState = (nextType: ChatVarType) => {
|
||||
return {
|
||||
editInJSON: nextType === ChatVarTypeEnum.ArrayObject,
|
||||
editorContent: undefined as string | undefined,
|
||||
objectValue: nextType === ChatVarTypeEnum.Object ? [DEFAULT_OBJECT_VALUE] : undefined,
|
||||
value:
|
||||
nextType === ChatVarTypeEnum.Boolean
|
||||
? false
|
||||
: nextType === ChatVarTypeEnum.ArrayBoolean
|
||||
? [false]
|
||||
: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
export const parseEditorContent = ({ content, type }: { content: string; type: ChatVarType }) => {
|
||||
const parsed = JSON.parse(content)
|
||||
if (type !== ChatVarTypeEnum.ArrayBoolean) return parsed
|
||||
|
||||
if (!Array.isArray(parsed))
|
||||
throw new TypeError('ArrayBoolean editor content must be a JSON array')
|
||||
return parsed
|
||||
.map((item: string | boolean) => {
|
||||
if (item === 'True' || item === 'true' || item === true) return true
|
||||
if (item === 'False' || item === 'false' || item === false) return false
|
||||
return undefined
|
||||
})
|
||||
.filter((item?: boolean) => item !== undefined)
|
||||
}
|
||||
|
||||
export type EditorToggleLabelKey =
|
||||
| 'chatVariable.modal.editInForm'
|
||||
| 'chatVariable.modal.editInJSON'
|
||||
| 'chatVariable.modal.oneByOne'
|
||||
|
||||
export const getEditorToggleLabelKey = (
|
||||
type: ChatVarType,
|
||||
editInJSON: boolean,
|
||||
): EditorToggleLabelKey => {
|
||||
if (type === ChatVarTypeEnum.Object)
|
||||
return editInJSON ? 'chatVariable.modal.editInForm' : 'chatVariable.modal.editInJSON'
|
||||
|
||||
return editInJSON ? 'chatVariable.modal.oneByOne' : 'chatVariable.modal.editInJSON'
|
||||
}
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
import type { SelectorParam } from 'i18next'
|
||||
import type { ReactNode } from 'react'
|
||||
import type {
|
||||
ChatVariableTranslator,
|
||||
EditorToggleLabelKey,
|
||||
ObjectValueItem,
|
||||
} from './variable-modal.helpers'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Field, FieldLabel } from '@langgenius/dify-ui/field'
|
||||
import { Input } from '@langgenius/dify-ui/input'
|
||||
import { NumberField, NumberFieldGroup, NumberFieldInput } from '@langgenius/dify-ui/number-field'
|
||||
import { RiDraftLine, RiInputField } from '@remixicon/react'
|
||||
import { useId } from 'react'
|
||||
import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
|
||||
import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
|
||||
import { ChatVarType } from '../type'
|
||||
import ArrayBoolList from './array-bool-list'
|
||||
import ArrayValueList from './array-value-list'
|
||||
import BoolValue from './bool-value'
|
||||
import ObjectValueList from './object-value-list'
|
||||
import VariableTypeSelector from './variable-type-select'
|
||||
|
||||
const editorToggleLabelSelectors: Record<EditorToggleLabelKey, SelectorParam<'workflow'>> = {
|
||||
'chatVariable.modal.editInForm': ($) => $['chatVariable.modal.editInForm'],
|
||||
'chatVariable.modal.editInJSON': ($) => $['chatVariable.modal.editInJSON'],
|
||||
'chatVariable.modal.oneByOne': ($) => $['chatVariable.modal.oneByOne'],
|
||||
}
|
||||
|
||||
type SectionTitleProps = {
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
const SectionTitle = ({ children }: SectionTitleProps) => (
|
||||
<div className="mb-1 flex h-6 items-center system-sm-semibold text-text-secondary">
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
|
||||
type NameSectionProps = {
|
||||
name: string
|
||||
onBlur: (value: string) => void
|
||||
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
|
||||
placeholder: string
|
||||
title: string
|
||||
}
|
||||
|
||||
export const NameSection = ({ name, onBlur, onChange, placeholder, title }: NameSectionProps) => (
|
||||
<Field className="mb-4">
|
||||
<FieldLabel className="system-sm-semibold">{title}</FieldLabel>
|
||||
<Input
|
||||
placeholder={placeholder}
|
||||
value={name}
|
||||
onChange={onChange}
|
||||
onBlur={(e) => onBlur(e.target.value)}
|
||||
type="text"
|
||||
/>
|
||||
</Field>
|
||||
)
|
||||
|
||||
type TypeSectionProps = {
|
||||
list: ChatVarType[]
|
||||
onSelect: (value: ChatVarType) => void
|
||||
title: string
|
||||
type: ChatVarType
|
||||
}
|
||||
|
||||
export const TypeSection = ({ list, onSelect, title, type }: TypeSectionProps) => (
|
||||
<div className="mb-4">
|
||||
<SectionTitle>{title}</SectionTitle>
|
||||
<div className="flex">
|
||||
<VariableTypeSelector
|
||||
value={type}
|
||||
list={list}
|
||||
onSelect={onSelect}
|
||||
popupClassName="w-[327px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
type ValueSectionProps = {
|
||||
editorContent?: string
|
||||
editorMinHeight: string
|
||||
editInJSON: boolean
|
||||
objectValue: ObjectValueItem[]
|
||||
onArrayBoolChange: (value: boolean[]) => void
|
||||
onArrayChange: (value: Array<string | number | undefined>) => void
|
||||
onEditorChange: (nextEditInJson: boolean) => void
|
||||
onEditorValueChange: (content: string) => void
|
||||
onObjectChange: (value: ObjectValueItem[]) => void
|
||||
onValueChange: (value: boolean) => void
|
||||
placeholder: ReactNode
|
||||
t: ChatVariableTranslator
|
||||
toggleLabelKey?: EditorToggleLabelKey
|
||||
type: ChatVarType
|
||||
value: unknown
|
||||
}
|
||||
|
||||
export const ValueSection = ({
|
||||
editorContent,
|
||||
editorMinHeight,
|
||||
editInJSON,
|
||||
objectValue,
|
||||
onArrayBoolChange,
|
||||
onArrayChange,
|
||||
onEditorChange,
|
||||
onEditorValueChange,
|
||||
onObjectChange,
|
||||
onValueChange,
|
||||
placeholder,
|
||||
t,
|
||||
toggleLabelKey,
|
||||
type,
|
||||
value,
|
||||
}: ValueSectionProps) => {
|
||||
const numberInputId = useId()
|
||||
return (
|
||||
<div className="mb-4">
|
||||
<div className="mb-1 flex h-6 items-center justify-between system-sm-semibold text-text-secondary">
|
||||
{type === ChatVarType.Number ? (
|
||||
<label htmlFor={numberInputId}>
|
||||
{t(($) => $['chatVariable.modal.value'], { ns: 'workflow' })}
|
||||
</label>
|
||||
) : (
|
||||
<div>{t(($) => $['chatVariable.modal.value'], { ns: 'workflow' })}</div>
|
||||
)}
|
||||
{toggleLabelKey && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="small"
|
||||
className="text-text-tertiary"
|
||||
onClick={() => onEditorChange(!editInJSON)}
|
||||
>
|
||||
{editInJSON ? (
|
||||
<RiInputField className="size-3.5" />
|
||||
) : (
|
||||
<RiDraftLine className="size-3.5" />
|
||||
)}
|
||||
{t(editorToggleLabelSelectors[toggleLabelKey], { ns: 'workflow' })}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex">
|
||||
{type === ChatVarType.String && (
|
||||
<textarea
|
||||
className="block h-20 w-full resize-none appearance-none rounded-lg border border-transparent bg-components-input-bg-normal p-2 system-sm-regular text-components-input-text-filled caret-primary-600 outline-hidden placeholder:system-sm-regular 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"
|
||||
value={(value as string) || ''}
|
||||
placeholder={t(($) => $['chatVariable.modal.valuePlaceholder'], { ns: 'workflow' })}
|
||||
onChange={(e) => onArrayChange([e.target.value])}
|
||||
/>
|
||||
)}
|
||||
{type === ChatVarType.Number && (
|
||||
<NumberField
|
||||
format={{ maximumSignificantDigits: 21, useGrouping: false }}
|
||||
id={numberInputId}
|
||||
className="w-full"
|
||||
value={typeof value === 'number' ? value : null}
|
||||
onValueChange={(value) => onArrayChange([value ?? undefined])}
|
||||
>
|
||||
<NumberFieldGroup>
|
||||
<NumberFieldInput
|
||||
inputMode="decimal"
|
||||
placeholder={t(($) => $['chatVariable.modal.valuePlaceholder'], { ns: 'workflow' })}
|
||||
/>
|
||||
</NumberFieldGroup>
|
||||
</NumberField>
|
||||
)}
|
||||
{type === ChatVarType.Boolean && (
|
||||
<BoolValue value={value as boolean} onChange={onValueChange} />
|
||||
)}
|
||||
{type === ChatVarType.Object && !editInJSON && (
|
||||
<ObjectValueList list={objectValue} onChange={onObjectChange} />
|
||||
)}
|
||||
{type === ChatVarType.ArrayString && !editInJSON && (
|
||||
<ArrayValueList
|
||||
isString
|
||||
list={(value as Array<string | undefined>) || [undefined]}
|
||||
onChange={onArrayChange}
|
||||
/>
|
||||
)}
|
||||
{type === ChatVarType.ArrayNumber && !editInJSON && (
|
||||
<ArrayValueList
|
||||
isString={false}
|
||||
list={(value as Array<number | undefined>) || [undefined]}
|
||||
onChange={onArrayChange}
|
||||
/>
|
||||
)}
|
||||
{type === ChatVarType.ArrayBoolean && !editInJSON && (
|
||||
<ArrayBoolList list={(value as boolean[]) || [true]} onChange={onArrayBoolChange} />
|
||||
)}
|
||||
{editInJSON && (
|
||||
<div
|
||||
className="w-full rounded-[10px] bg-components-input-bg-normal py-2 pr-1 pl-3"
|
||||
style={{ height: editorMinHeight }}
|
||||
>
|
||||
<CodeEditor
|
||||
isExpand
|
||||
noWrapper
|
||||
language={CodeLanguage.json}
|
||||
value={editorContent}
|
||||
placeholder={<div className="whitespace-pre">{placeholder}</div>}
|
||||
onChange={onEditorValueChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type DescriptionSectionProps = {
|
||||
description: string
|
||||
maxLength: number
|
||||
onChange: (value: string) => void
|
||||
placeholder: string
|
||||
title: string
|
||||
}
|
||||
|
||||
export const DescriptionSection = ({
|
||||
description,
|
||||
maxLength,
|
||||
onChange,
|
||||
placeholder,
|
||||
title,
|
||||
}: DescriptionSectionProps) => (
|
||||
<div>
|
||||
<SectionTitle>{title}</SectionTitle>
|
||||
<div className="flex">
|
||||
<textarea
|
||||
className="block h-20 w-full resize-none appearance-none rounded-lg border border-transparent bg-components-input-bg-normal p-2 system-sm-regular text-components-input-text-filled caret-primary-600 outline-hidden placeholder:system-sm-regular 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"
|
||||
value={description}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
'mt-1 text-right system-xs-regular',
|
||||
description.length > maxLength ? 'text-text-destructive' : 'text-text-quaternary',
|
||||
)}
|
||||
>
|
||||
{description.length}/{maxLength}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
import type { ToastPayload } from './variable-modal.helpers'
|
||||
import type { ConversationVariable } from '@/app/components/workflow/types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { RiCloseLine } from '@remixicon/react'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'
|
||||
import { useWorkflowStore } from '@/app/components/workflow/store'
|
||||
import { toast } from '@/app/notifications'
|
||||
import { replaceSpaceWithUnderscoreInVarNameInput } from '@/utils/var'
|
||||
import { useVariableModalState } from './use-variable-modal-state'
|
||||
import {
|
||||
getEditorToggleLabelKey,
|
||||
MAX_DESCRIPTION_LENGTH,
|
||||
typeList,
|
||||
validateVariableName,
|
||||
} from './variable-modal.helpers'
|
||||
import {
|
||||
DescriptionSection,
|
||||
NameSection,
|
||||
TypeSection,
|
||||
ValueSection,
|
||||
} from './variable-modal.sections'
|
||||
|
||||
type ModalPropsType = {
|
||||
chatVar?: ConversationVariable
|
||||
onClose: () => void
|
||||
onSave: (chatVar: ConversationVariable) => void
|
||||
}
|
||||
|
||||
const ChatVariableModal = ({ chatVar, onClose, onSave }: ModalPropsType) => {
|
||||
const { t } = useTranslation(['appDebug', 'common', 'workflow'])
|
||||
const workflowStore = useWorkflowStore()
|
||||
const notify = React.useCallback(({ children, message, type = 'info' }: ToastPayload) => {
|
||||
toast[type](message, children ? { description: children } : undefined)
|
||||
}, [])
|
||||
const {
|
||||
description,
|
||||
editInJSON,
|
||||
editorContent,
|
||||
editorMinHeight,
|
||||
handleEditorChange,
|
||||
handleEditorValueChange,
|
||||
handleSave,
|
||||
handleStringOrNumberChange,
|
||||
handleTypeChange,
|
||||
handleVarNameChange,
|
||||
name,
|
||||
objectValue,
|
||||
placeholder,
|
||||
setDescription,
|
||||
setObjectValue,
|
||||
setValue,
|
||||
type,
|
||||
value,
|
||||
} = useVariableModalState({
|
||||
chatVar,
|
||||
conversationVariables: workflowStore.getState().conversationVariables,
|
||||
notify,
|
||||
onClose,
|
||||
onSave,
|
||||
t,
|
||||
})
|
||||
|
||||
const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
replaceSpaceWithUnderscoreInVarNameInput(e.target)
|
||||
if (e.target.value && !validateVariableName({ name: e.target.value, notify, t })) return
|
||||
handleVarNameChange(e)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex h-full w-90 flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-2xl',
|
||||
type === ChatVarType.Object && 'w-120',
|
||||
)}
|
||||
>
|
||||
<div className="mb-3 flex shrink-0 items-center justify-between p-4 pb-0 system-xl-semibold text-text-primary">
|
||||
{!chatVar
|
||||
? t(($) => $['chatVariable.modal.title'], { ns: 'workflow' })
|
||||
: t(($) => $['chatVariable.modal.editTitle'], { ns: 'workflow' })}
|
||||
<div className="flex items-center">
|
||||
<div className="flex size-6 cursor-pointer items-center justify-center" onClick={onClose}>
|
||||
<RiCloseLine className="size-4 text-text-tertiary" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="max-h-120 overflow-y-auto px-4 py-2">
|
||||
<NameSection
|
||||
name={name}
|
||||
onBlur={(nextName) => validateVariableName({ name: nextName, notify, t })}
|
||||
onChange={handleNameChange}
|
||||
placeholder={t(($) => $['chatVariable.modal.namePlaceholder'], { ns: 'workflow' })}
|
||||
title={t(($) => $['chatVariable.modal.name'], { ns: 'workflow' })}
|
||||
/>
|
||||
<TypeSection
|
||||
type={type}
|
||||
list={typeList}
|
||||
onSelect={handleTypeChange}
|
||||
title={t(($) => $['chatVariable.modal.type'], { ns: 'workflow' })}
|
||||
/>
|
||||
<ValueSection
|
||||
type={type}
|
||||
value={value}
|
||||
objectValue={objectValue}
|
||||
editInJSON={editInJSON}
|
||||
editorContent={editorContent}
|
||||
editorMinHeight={editorMinHeight}
|
||||
onArrayBoolChange={setValue}
|
||||
onArrayChange={
|
||||
type === ChatVarType.String || type === ChatVarType.Number
|
||||
? handleStringOrNumberChange
|
||||
: setValue
|
||||
}
|
||||
onEditorChange={handleEditorChange}
|
||||
onEditorValueChange={handleEditorValueChange}
|
||||
onObjectChange={setObjectValue}
|
||||
onValueChange={setValue}
|
||||
placeholder={placeholder}
|
||||
t={t}
|
||||
toggleLabelKey={
|
||||
type === ChatVarType.Object ||
|
||||
type === ChatVarType.ArrayString ||
|
||||
type === ChatVarType.ArrayNumber ||
|
||||
type === ChatVarType.ArrayBoolean
|
||||
? getEditorToggleLabelKey(type, editInJSON)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<DescriptionSection
|
||||
description={description}
|
||||
maxLength={MAX_DESCRIPTION_LENGTH}
|
||||
onChange={setDescription}
|
||||
placeholder={t(($) => $['chatVariable.modal.descriptionPlaceholder'], { ns: 'workflow' })}
|
||||
title={t(($) => $['chatVariable.modal.description'], { ns: 'workflow' })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-row-reverse rounded-b-2xl p-4 pt-2">
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={onClose}>{t(($) => $['operation.cancel'], { ns: 'common' })}</Button>
|
||||
<Button variant="primary" onClick={handleSave}>
|
||||
{t(($) => $['operation.save'], { ns: 'common' })}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ChatVariableModal
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
'use client'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectItemIndicator,
|
||||
SelectItemText,
|
||||
SelectTrigger,
|
||||
} from '@langgenius/dify-ui/select'
|
||||
import * as React from 'react'
|
||||
import { useState } from 'react'
|
||||
|
||||
type Props<T extends string> = {
|
||||
inCell?: boolean
|
||||
value?: T
|
||||
list: readonly T[]
|
||||
onSelect: (value: T) => void
|
||||
popupClassName?: string
|
||||
}
|
||||
|
||||
const VariableTypeSelector = <T extends string>({
|
||||
inCell = false,
|
||||
value,
|
||||
list,
|
||||
onSelect,
|
||||
popupClassName,
|
||||
}: Props<T>) => {
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const handleValueChange = (nextValue: string | null) => {
|
||||
if (!nextValue) return
|
||||
|
||||
const nextItem = list.find((item) => item === nextValue)
|
||||
if (!nextItem) return
|
||||
|
||||
onSelect(nextItem)
|
||||
}
|
||||
|
||||
return (
|
||||
<Select
|
||||
value={value ?? null}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
onValueChange={handleValueChange}
|
||||
>
|
||||
<SelectTrigger className="h-auto w-full max-w-none cursor-pointer rounded-none bg-transparent p-0 hover:bg-transparent focus-visible:bg-transparent data-popup-open:bg-transparent [&>*:last-child]:hidden">
|
||||
<div
|
||||
className={cn(
|
||||
'flex w-full cursor-pointer items-center px-2',
|
||||
!inCell &&
|
||||
'rounded-lg bg-components-input-bg-normal py-1 hover:bg-state-base-hover-alt',
|
||||
inCell && 'py-0.5 hover:bg-state-base-hover',
|
||||
open && !inCell && 'bg-state-base-hover-alt hover:bg-state-base-hover-alt',
|
||||
open && inCell && 'bg-state-base-hover hover:bg-state-base-hover',
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'grow truncate p-1 system-sm-regular text-components-input-text-filled',
|
||||
inCell && 'system-xs-regular text-text-secondary',
|
||||
)}
|
||||
>
|
||||
{value}
|
||||
</div>
|
||||
<span
|
||||
className="ml-0.5 i-ri-arrow-down-s-line size-4 text-text-quaternary"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</div>
|
||||
</SelectTrigger>
|
||||
<SelectContent className={cn('bg-components-panel-bg-blur', popupClassName)}>
|
||||
{list.map((item) => (
|
||||
<SelectItem
|
||||
key={item}
|
||||
value={item}
|
||||
className="h-auto gap-2 py-1.5 system-md-regular font-normal"
|
||||
>
|
||||
<SelectItemText className="system-md-regular text-text-secondary">
|
||||
{item}
|
||||
</SelectItemText>
|
||||
<SelectItemIndicator />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
}
|
||||
|
||||
export default VariableTypeSelector
|
||||
@@ -0,0 +1,311 @@
|
||||
import type { ConversationVariable } from '@/app/components/workflow/types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from '@langgenius/dify-ui/collapsible'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { useAtomValue } from 'jotai'
|
||||
import { memo, useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import BlockIcon from '@/app/components/workflow/block-icon'
|
||||
import { webSocketClient } from '@/app/components/workflow/collaboration/core/websocket-manager'
|
||||
import { workflowAppIdentityAtom } from '@/app/components/workflow/editor-resource/state'
|
||||
import RemoveEffectVarConfirm from '@/app/components/workflow/nodes/_base/components/remove-effect-var-confirm'
|
||||
import {
|
||||
findUsedVarNodes,
|
||||
updateNodeVars,
|
||||
} from '@/app/components/workflow/nodes/_base/components/variable/utils'
|
||||
import VariableItem from '@/app/components/workflow/panel/chat-variable-panel/components/variable-item'
|
||||
import VariableModalTrigger from '@/app/components/workflow/panel/chat-variable-panel/components/variable-modal-trigger'
|
||||
import { useStore } from '@/app/components/workflow/store'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import { updateConversationVariables } from '@/service/workflow'
|
||||
import { useCollaborativeWorkflow } from '../../hooks/use-collaborative-workflow'
|
||||
import useInspectVarsCrud from '../../hooks/use-inspect-vars-crud'
|
||||
|
||||
const ChatVariablePanel = () => {
|
||||
const { t } = useTranslation(['common', 'workflow'])
|
||||
const setShowChatVariablePanel = useStore((s) => s.setShowChatVariablePanel)
|
||||
const varList = useStore((s) => s.conversationVariables) as ConversationVariable[]
|
||||
const updateChatVarList = useStore((s) => s.setConversationVariables)
|
||||
const setControlPromptEditorRerenderKey = useStore((s) => s.setControlPromptEditorRerenderKey)
|
||||
const { appId } = useAtomValue(workflowAppIdentityAtom)
|
||||
const { invalidateConversationVarValues } = useInspectVarsCrud()
|
||||
|
||||
const [showTip, setShowTip] = useState(true)
|
||||
const [showVariableModal, setShowVariableModal] = useState(false)
|
||||
const [currentVar, setCurrentVar] = useState<ConversationVariable>()
|
||||
|
||||
const [showRemoveVarConfirm, setShowRemoveConfirm] = useState(false)
|
||||
const [cacheForDelete, setCacheForDelete] = useState<ConversationVariable>()
|
||||
const collaborativeWorkflow = useCollaborativeWorkflow()
|
||||
|
||||
const getEffectedNodes = useCallback(
|
||||
(chatVar: ConversationVariable) => {
|
||||
const { nodes: allNodes } = collaborativeWorkflow.getState()
|
||||
return findUsedVarNodes(['conversation', chatVar.name], allNodes)
|
||||
},
|
||||
[collaborativeWorkflow],
|
||||
)
|
||||
|
||||
const removeUsedVarInNodes = useCallback(
|
||||
(chatVar: ConversationVariable) => {
|
||||
const { nodes, setNodes } = collaborativeWorkflow.getState()
|
||||
const effectedNodes = getEffectedNodes(chatVar)
|
||||
const newNodes = nodes.map((node) => {
|
||||
if (effectedNodes.find((n) => n.id === node.id))
|
||||
return updateNodeVars(node, ['conversation', chatVar.name], [])
|
||||
|
||||
return node
|
||||
})
|
||||
setNodes(newNodes)
|
||||
},
|
||||
[getEffectedNodes, collaborativeWorkflow],
|
||||
)
|
||||
|
||||
const handleEdit = (chatVar: ConversationVariable) => {
|
||||
setCurrentVar(chatVar)
|
||||
setShowVariableModal(true)
|
||||
}
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (chatVar: ConversationVariable) => {
|
||||
removeUsedVarInNodes(chatVar)
|
||||
const newVarList = varList.filter((v) => v.id !== chatVar.id)
|
||||
updateChatVarList(newVarList)
|
||||
setCacheForDelete(undefined)
|
||||
setShowRemoveConfirm(false)
|
||||
|
||||
// Use new dedicated conversation variables API instead of workflow draft sync
|
||||
try {
|
||||
await updateConversationVariables({
|
||||
appId,
|
||||
conversationVariables: newVarList,
|
||||
})
|
||||
|
||||
// Emit update event to other connected clients
|
||||
const socket = webSocketClient.getSocket(appId)
|
||||
if (socket) {
|
||||
socket.emit('collaboration_event', {
|
||||
type: 'vars_and_features_update',
|
||||
})
|
||||
}
|
||||
|
||||
invalidateConversationVarValues()
|
||||
} catch (error) {
|
||||
console.error('Failed to update conversation variables:', error)
|
||||
// Revert local state on error
|
||||
updateChatVarList(varList)
|
||||
}
|
||||
},
|
||||
[removeUsedVarInNodes, updateChatVarList, varList, appId, invalidateConversationVarValues],
|
||||
)
|
||||
|
||||
const deleteCheck = useCallback(
|
||||
(chatVar: ConversationVariable) => {
|
||||
const effectedNodes = getEffectedNodes(chatVar)
|
||||
if (effectedNodes.length > 0) {
|
||||
setCacheForDelete(chatVar)
|
||||
setShowRemoveConfirm(true)
|
||||
} else {
|
||||
handleDelete(chatVar)
|
||||
}
|
||||
},
|
||||
[getEffectedNodes, handleDelete],
|
||||
)
|
||||
|
||||
const handleSave = useCallback(
|
||||
async (chatVar: ConversationVariable) => {
|
||||
let newList: ConversationVariable[]
|
||||
|
||||
if (!currentVar) {
|
||||
// Adding new conversation variable
|
||||
newList = [chatVar, ...varList]
|
||||
updateChatVarList(newList)
|
||||
|
||||
// Use new dedicated conversation variables API
|
||||
try {
|
||||
await updateConversationVariables({
|
||||
appId,
|
||||
conversationVariables: newList,
|
||||
})
|
||||
|
||||
const socket = webSocketClient.getSocket(appId)
|
||||
if (socket) {
|
||||
socket.emit('collaboration_event', {
|
||||
type: 'vars_and_features_update',
|
||||
})
|
||||
}
|
||||
|
||||
invalidateConversationVarValues()
|
||||
} catch (error) {
|
||||
console.error('Failed to update conversation variables:', error)
|
||||
// Revert local state on error
|
||||
updateChatVarList(varList)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Updating existing conversation variable
|
||||
newList = varList.map((v) => (v.id === currentVar.id ? chatVar : v))
|
||||
updateChatVarList(newList)
|
||||
|
||||
// side effects of rename conversation variable
|
||||
if (currentVar.name !== chatVar.name) {
|
||||
const { nodes, setNodes } = collaborativeWorkflow.getState()
|
||||
const effectedNodes = getEffectedNodes(currentVar)
|
||||
const newNodes = nodes.map((node) => {
|
||||
if (effectedNodes.find((n) => n.id === node.id))
|
||||
return updateNodeVars(
|
||||
node,
|
||||
['conversation', currentVar.name],
|
||||
['conversation', chatVar.name],
|
||||
)
|
||||
|
||||
return node
|
||||
})
|
||||
setNodes(newNodes)
|
||||
setControlPromptEditorRerenderKey(Date.now())
|
||||
}
|
||||
|
||||
// Use new dedicated conversation variables API
|
||||
try {
|
||||
await updateConversationVariables({
|
||||
appId,
|
||||
conversationVariables: newList,
|
||||
})
|
||||
|
||||
const socket = webSocketClient.getSocket(appId)
|
||||
if (socket) {
|
||||
socket.emit('collaboration_event', {
|
||||
type: 'vars_and_features_update',
|
||||
})
|
||||
}
|
||||
|
||||
invalidateConversationVarValues()
|
||||
} catch (error) {
|
||||
console.error('Failed to update conversation variables:', error)
|
||||
// Revert local state on error
|
||||
updateChatVarList(varList)
|
||||
}
|
||||
},
|
||||
[
|
||||
currentVar,
|
||||
getEffectedNodes,
|
||||
collaborativeWorkflow,
|
||||
updateChatVarList,
|
||||
varList,
|
||||
appId,
|
||||
invalidateConversationVarValues,
|
||||
setControlPromptEditorRerenderKey,
|
||||
],
|
||||
)
|
||||
|
||||
return (
|
||||
<Collapsible
|
||||
open={showTip}
|
||||
onOpenChange={setShowTip}
|
||||
render={
|
||||
<div
|
||||
className={cn(
|
||||
'relative flex h-full w-105 flex-col rounded-l-2xl border border-components-panel-border bg-components-panel-bg-alt',
|
||||
)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<div className="flex shrink-0 items-center justify-between p-4 pb-0 system-xl-semibold text-text-primary">
|
||||
{t(($) => $['chatVariable.panelTitle'], { ns: 'workflow' })}
|
||||
<div className="flex items-center gap-1">
|
||||
<CollapsibleTrigger
|
||||
className="rounded-lg text-text-secondary data-panel-open:bg-state-accent-active data-panel-open:text-text-accent data-panel-open:hover:bg-state-accent-active-alt"
|
||||
render={
|
||||
<IconButton aria-label={t(($) => $['chatVariable.tips'], { ns: 'workflow' })}>
|
||||
<span aria-hidden="true" className="i-ri-book-open-line size-4" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
<IconButton
|
||||
aria-label={t(($) => $['operation.close'], { ns: 'common' })}
|
||||
onClick={() => setShowChatVariablePanel(false)}
|
||||
>
|
||||
<span aria-hidden="true" className="i-ri-close-line size-4 text-text-tertiary" />
|
||||
</IconButton>
|
||||
</div>
|
||||
</div>
|
||||
<CollapsiblePanel render={<div className="shrink-0 px-3 pt-2.5 pb-2" />}>
|
||||
<div className="relative rounded-2xl bg-background-section-burn p-3">
|
||||
<div className="inline-block rounded-[5px] border border-divider-deep px-1.25 py-0.75 system-2xs-medium-uppercase text-text-tertiary">
|
||||
TIPS
|
||||
</div>
|
||||
<div className="mt-1 mb-4 system-sm-regular text-text-secondary">
|
||||
{t(($) => $['chatVariable.panelDescription'], { ns: 'workflow' })}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex flex-col rounded-[10px] border border-workflow-block-border bg-workflow-block-bg p-3 pb-4 shadow-md">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="mb-1 i-custom-vender-line-others-bubble-x size-4 shrink-0 text-util-colors-teal-teal-700"
|
||||
/>
|
||||
<div className="system-xs-semibold text-text-secondary">conversation_var</div>
|
||||
<div className="system-2xs-regular text-text-tertiary">String</div>
|
||||
</div>
|
||||
<div className="grow">
|
||||
<div className="mb-2 flex items-center gap-2 py-1">
|
||||
<div className="flex h-3 w-16 shrink-0 items-center gap-1 px-1">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="i-custom-vender-line-others-long-arrow-left h-2 grow text-text-quaternary"
|
||||
/>
|
||||
<div className="shrink-0 system-2xs-medium text-text-tertiary">WRITE</div>
|
||||
</div>
|
||||
<BlockIcon className="shrink-0" type={BlockEnum.Assigner} />
|
||||
<div className="grow truncate system-xs-semibold text-text-secondary">
|
||||
{t(($) => $['blocks.assigner'], { ns: 'workflow' })}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 py-1">
|
||||
<div className="flex h-3 w-16 shrink-0 items-center gap-1 px-1">
|
||||
<div className="shrink-0 system-2xs-medium text-text-tertiary">READ</div>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="i-custom-vender-line-others-long-arrow-right h-2 grow text-text-quaternary"
|
||||
/>
|
||||
</div>
|
||||
<BlockIcon className="shrink-0" type={BlockEnum.LLM} />
|
||||
<div className="grow truncate system-xs-semibold text-text-secondary">
|
||||
{t(($) => $['blocks.llm'], { ns: 'workflow' })}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="absolute -top-1 right-9.5 z-10 h-3 w-3 rotate-45 bg-background-section-burn" />
|
||||
</div>
|
||||
</CollapsiblePanel>
|
||||
<div className="shrink-0 px-4 pt-2 pb-3">
|
||||
<VariableModalTrigger
|
||||
open={showVariableModal}
|
||||
setOpen={setShowVariableModal}
|
||||
showTip={showTip}
|
||||
chatVar={currentVar}
|
||||
onSave={handleSave}
|
||||
onClose={() => setCurrentVar(undefined)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grow overflow-y-auto rounded-b-2xl px-4">
|
||||
{varList.map((chatVar) => (
|
||||
<VariableItem
|
||||
key={chatVar.id}
|
||||
item={chatVar}
|
||||
onEdit={handleEdit}
|
||||
onDelete={deleteCheck}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<RemoveEffectVarConfirm
|
||||
isShow={showRemoveVarConfirm}
|
||||
onCancel={() => setShowRemoveConfirm(false)}
|
||||
onConfirm={() => cacheForDelete && handleDelete(cacheForDelete)}
|
||||
/>
|
||||
</Collapsible>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(ChatVariablePanel)
|
||||
@@ -0,0 +1,12 @@
|
||||
export const ChatVarType = {
|
||||
Number: 'number',
|
||||
String: 'string',
|
||||
Boolean: 'boolean',
|
||||
Object: 'object',
|
||||
ArrayString: 'array[string]',
|
||||
ArrayNumber: 'array[number]',
|
||||
ArrayBoolean: 'array[boolean]',
|
||||
ArrayObject: 'array[object]',
|
||||
} as const
|
||||
|
||||
export type ChatVarType = (typeof ChatVarType)[keyof typeof ChatVarType]
|
||||
@@ -0,0 +1,35 @@
|
||||
export const objectPlaceholder = `# example
|
||||
# {
|
||||
# "name": "ray",
|
||||
# "age": 20
|
||||
# }`
|
||||
|
||||
export const arrayStringPlaceholder = `# example
|
||||
# [
|
||||
# "value1",
|
||||
# "value2"
|
||||
# ]`
|
||||
|
||||
export const arrayNumberPlaceholder = `# example
|
||||
# [
|
||||
# 100,
|
||||
# 200
|
||||
# ]`
|
||||
|
||||
export const arrayObjectPlaceholder = `# example
|
||||
# [
|
||||
# {
|
||||
# "name": "ray",
|
||||
# "age": 20
|
||||
# },
|
||||
# {
|
||||
# "name": "lily",
|
||||
# "age": 18
|
||||
# }
|
||||
# ]`
|
||||
|
||||
export const arrayBoolPlaceholder = `# example
|
||||
# [
|
||||
# "True",
|
||||
# "False"
|
||||
# ]`
|
||||
Reference in new issue
Block a user