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
+198
@@ -0,0 +1,198 @@
|
||||
import type { Node } from '../../../types'
|
||||
import { act } from '@testing-library/react'
|
||||
import { useNodes } from 'reactflow'
|
||||
import { createEdge, createNode } from '../../../__tests__/fixtures'
|
||||
import { renderWorkflowCanvasHook } from '../../../__tests__/workflow-test-env'
|
||||
import { BlockEnum, VarType } from '../../../types'
|
||||
import { useGetAvailableVars, useVariableAssigner } from '../hooks'
|
||||
|
||||
// Branch traversal and variable collection have their own suites; here they only feed the filters.
|
||||
const mockGetBeforeNodesInSameBranchIncludeParent = vi.hoisted(() => vi.fn())
|
||||
const mockGetNodeAvailableVars = vi.hoisted(() => vi.fn())
|
||||
vi.mock('../../../hooks/use-workflow', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../hooks/use-workflow')>()),
|
||||
useWorkflow: () => ({
|
||||
getBeforeNodesInSameBranchIncludeParent: mockGetBeforeNodesInSameBranchIncludeParent,
|
||||
}),
|
||||
}))
|
||||
vi.mock('../../../hooks/use-workflow-variables', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../hooks/use-workflow-variables')>()),
|
||||
useWorkflowVariables: () => ({ getNodeAvailableVars: mockGetNodeAvailableVars }),
|
||||
}))
|
||||
|
||||
const createAssigner = (data: Record<string, unknown> = {}) =>
|
||||
createNode({
|
||||
id: 'assigner-1',
|
||||
data: {
|
||||
type: BlockEnum.VariableAssigner,
|
||||
variables: [['start', 'foo']],
|
||||
output_type: VarType.string,
|
||||
advanced_settings: {
|
||||
group_enabled: true,
|
||||
groups: [
|
||||
{ groupId: 'group-1', group_name: 'Group1', variables: [], output_type: VarType.string },
|
||||
],
|
||||
},
|
||||
...data,
|
||||
},
|
||||
})
|
||||
|
||||
const renderAssigner = (nodes: Node[] = [createAssigner()], initialStoreState = {}) =>
|
||||
renderWorkflowCanvasHook(() => ({ assigner: useVariableAssigner(), nodes: useNodes() }), {
|
||||
nodes,
|
||||
initialStoreState,
|
||||
})
|
||||
|
||||
const assignerData = (nodes: { id: string; data: unknown }[]) =>
|
||||
nodes.find((node) => node.id === 'assigner-1')!.data as Record<string, unknown>
|
||||
|
||||
describe('useVariableAssigner', () => {
|
||||
it('appends new target variables, ignores duplicates, and fills grouped variables', () => {
|
||||
const { result } = renderAssigner()
|
||||
|
||||
act(() => {
|
||||
result.current.assigner.handleAssignVariableValueChange('assigner-1', ['start', 'bar'], {
|
||||
variable: 'value',
|
||||
type: VarType.number,
|
||||
})
|
||||
result.current.assigner.handleAssignVariableValueChange('assigner-1', ['start', 'foo'], {
|
||||
variable: 'value',
|
||||
type: VarType.number,
|
||||
})
|
||||
result.current.assigner.handleAssignVariableValueChange(
|
||||
'assigner-1',
|
||||
['start', 'grouped'],
|
||||
{ variable: 'grouped', type: VarType.arrayString },
|
||||
'group-1',
|
||||
)
|
||||
})
|
||||
|
||||
expect(assignerData(result.current.nodes)).toMatchObject({
|
||||
variables: [
|
||||
['start', 'foo'],
|
||||
['start', 'bar'],
|
||||
],
|
||||
output_type: VarType.number,
|
||||
advanced_settings: {
|
||||
groups: [
|
||||
{
|
||||
groupId: 'group-1',
|
||||
variables: [['start', 'grouped']],
|
||||
output_type: VarType.arrayString,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('closes the add-variable popups and adds the picked variable to the group', () => {
|
||||
const popupOpen = { _showAddVariablePopup: true, _holdAddVariablePopup: true }
|
||||
const { result, store } = renderAssigner(
|
||||
[
|
||||
createNode({ id: 'source-node', data: popupOpen }),
|
||||
createAssigner({ variables: [], ...popupOpen }),
|
||||
],
|
||||
{ showAssignVariablePopup: { nodeId: 'assigner-1' } },
|
||||
)
|
||||
|
||||
act(() =>
|
||||
result.current.assigner.handleAddVariableInAddVariablePopupWithPosition(
|
||||
'source-node',
|
||||
'assigner-1',
|
||||
'group-1',
|
||||
['start', 'output'],
|
||||
{ variable: 'output', type: VarType.object },
|
||||
),
|
||||
)
|
||||
|
||||
for (const node of result.current.nodes)
|
||||
expect(node.data).toMatchObject({
|
||||
_showAddVariablePopup: false,
|
||||
_holdAddVariablePopup: false,
|
||||
})
|
||||
expect(store.getState().showAssignVariablePopup).toBeUndefined()
|
||||
expect(assignerData(result.current.nodes)).toMatchObject({
|
||||
advanced_settings: {
|
||||
groups: [
|
||||
{ groupId: 'group-1', variables: [['start', 'output']], output_type: VarType.object },
|
||||
],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ connecting: true, afterLeave: undefined },
|
||||
{ connecting: false, afterLeave: 'group-1' },
|
||||
])(
|
||||
'tracks the hovered group and clears it on leave only while connecting (connecting=$connecting)',
|
||||
({ connecting, afterLeave }) => {
|
||||
const { result, store } = renderAssigner([createAssigner()], {
|
||||
connectingNodePayload: connecting ? { nodeId: 'source-node' } : undefined,
|
||||
})
|
||||
|
||||
act(() => result.current.assigner.handleGroupItemMouseEnter('group-1'))
|
||||
expect(store.getState().hoveringAssignVariableGroupId).toBe('group-1')
|
||||
|
||||
act(() => result.current.assigner.handleGroupItemMouseLeave())
|
||||
expect(store.getState().hoveringAssignVariableGroupId).toBe(afterLeave)
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
describe('useGetAvailableVars', () => {
|
||||
const canvas = {
|
||||
nodes: [
|
||||
createNode({ id: 'parent-node', data: { type: BlockEnum.Iteration } }),
|
||||
createNode({ id: 'before-1' }),
|
||||
createNode({ id: 'current-node', parentId: 'parent-node' }),
|
||||
],
|
||||
edges: [createEdge({ source: 'before-1', target: 'current-node' })],
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockGetBeforeNodesInSameBranchIncludeParent.mockReturnValue([canvas.nodes[1], canvas.nodes[1]])
|
||||
})
|
||||
|
||||
it('hides system start variables and empty groups when env vars are hidden', () => {
|
||||
mockGetNodeAvailableVars.mockReturnValue([
|
||||
{ isStartNode: true, vars: [{ variable: 'sys.user_id' }, { variable: 'foo' }] },
|
||||
{ isStartNode: false, vars: [] },
|
||||
])
|
||||
const { result } = renderWorkflowCanvasHook(() => useGetAvailableVars(), canvas)
|
||||
|
||||
expect(result.current('current-node', 'target', () => true, true)).toEqual([
|
||||
{ isStartNode: true, vars: [{ variable: 'foo' }] },
|
||||
])
|
||||
expect(mockGetNodeAvailableVars).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
parentNode: expect.objectContaining({ id: 'parent-node' }),
|
||||
beforeNodes: [expect.objectContaining({ id: 'before-1' })],
|
||||
hideEnv: true,
|
||||
isChatflow: false,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('returns the collected variables unchanged when env vars are shown', () => {
|
||||
const vars = [{ isStartNode: false, vars: [{ variable: 'bar' }] }]
|
||||
mockGetNodeAvailableVars.mockReturnValue(vars)
|
||||
const { result } = renderWorkflowCanvasHook(() => useGetAvailableVars(), canvas)
|
||||
|
||||
expect(result.current('current-node', 'target', () => true, false)).toEqual(vars)
|
||||
expect(result.current('missing-node', 'target', () => true)).toEqual([])
|
||||
})
|
||||
|
||||
it('filters system variables when the current flow is a snippet', () => {
|
||||
mockGetNodeAvailableVars.mockReturnValue([
|
||||
{ isStartNode: false, vars: [{ variable: 'sys.user_id' }, { variable: 'answer' }] },
|
||||
])
|
||||
const { result } = renderWorkflowCanvasHook(() => useGetAvailableVars(), {
|
||||
...canvas,
|
||||
resource: { kind: 'snippet', snippetId: 'snippet-1' },
|
||||
})
|
||||
|
||||
expect(result.current('current-node', 'target', () => true, false)).toEqual([
|
||||
{ isStartNode: false, vars: [{ variable: 'answer' }] },
|
||||
])
|
||||
})
|
||||
})
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
import type { VariableAssignerNodeType } from '../types'
|
||||
import { screen } from '@testing-library/react'
|
||||
import { createNode } from '@/app/components/workflow/__tests__/fixtures'
|
||||
import { BlockEnum, VarType } from '@/app/components/workflow/types'
|
||||
import Node from '../node'
|
||||
import { renderAssigner as renderWorkflowFlowComponent } from './test-helpers'
|
||||
|
||||
const createData = (
|
||||
overrides: Partial<VariableAssignerNodeType> = {},
|
||||
): VariableAssignerNodeType => ({
|
||||
title: 'Variable Assigner',
|
||||
desc: '',
|
||||
type: BlockEnum.VariableAssigner,
|
||||
output_type: VarType.string,
|
||||
variables: [['source-node', 'rootVar']],
|
||||
advanced_settings: {
|
||||
group_enabled: true,
|
||||
groups: [
|
||||
{
|
||||
groupId: 'group-1',
|
||||
group_name: 'Group1',
|
||||
output_type: VarType.string,
|
||||
variables: [['source-node', 'groupVar']],
|
||||
},
|
||||
{
|
||||
groupId: 'group-2',
|
||||
group_name: 'Group2',
|
||||
output_type: VarType.number,
|
||||
variables: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const baseNodeProps = {
|
||||
id: 'assigner-node',
|
||||
type: 'custom',
|
||||
selected: false,
|
||||
zIndex: 1,
|
||||
isConnectable: true,
|
||||
xPos: 0,
|
||||
yPos: 0,
|
||||
dragging: false,
|
||||
dragHandle: '.drag-handle',
|
||||
}
|
||||
|
||||
const renderNode = (data: VariableAssignerNodeType) =>
|
||||
renderWorkflowFlowComponent(<Node {...baseNodeProps} data={data} />, {
|
||||
nodes: [
|
||||
createNode({ id: 'assigner-node', data }),
|
||||
createNode({
|
||||
id: 'source-node',
|
||||
data: {
|
||||
title: 'Source',
|
||||
type: BlockEnum.Code,
|
||||
outputs: {
|
||||
rootVar: { type: VarType.string },
|
||||
groupVar: { type: VarType.string },
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
edges: [],
|
||||
})
|
||||
|
||||
it('renders each group with its own variables and shows an unset group', async () => {
|
||||
renderNode(createData())
|
||||
expect(await screen.findByText('Group1')).toBeInTheDocument()
|
||||
expect(screen.getByText('Group2')).toBeInTheDocument()
|
||||
expect(screen.getByText('groupVar')).toBeInTheDocument()
|
||||
expect(screen.queryByText('rootVar')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('workflowLogic.nodes.variableAssigner.varNotSet')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('uses root variables when grouping is disabled', async () => {
|
||||
renderNode(createData({ advanced_settings: { group_enabled: false, groups: [] } }))
|
||||
expect(await screen.findByText('workflow.nodes.variableAssigner.title')).toBeInTheDocument()
|
||||
expect(screen.getByText('rootVar')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Group1')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('groupVar')).not.toBeInTheDocument()
|
||||
})
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
import type { VariableAssignerNodeType } from '../types'
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { BlockEnum, VarType } from '@/app/components/workflow/types'
|
||||
import { createEdge, createNode } from '../../../__tests__/fixtures'
|
||||
import { renderNodePanel } from '../../__tests__/render-node-panel'
|
||||
import Panel from '../panel'
|
||||
|
||||
const createData = (
|
||||
overrides: Partial<VariableAssignerNodeType> = {},
|
||||
): VariableAssignerNodeType => ({
|
||||
title: 'Variable Assigner',
|
||||
desc: '',
|
||||
type: BlockEnum.VariableAssigner,
|
||||
output_type: VarType.string,
|
||||
variables: [['source-node', 'rootVar']],
|
||||
advanced_settings: {
|
||||
group_enabled: true,
|
||||
groups: [
|
||||
{
|
||||
groupId: 'group-1',
|
||||
group_name: 'Group1',
|
||||
output_type: VarType.string,
|
||||
variables: [['source-node', 'groupVar']],
|
||||
},
|
||||
{
|
||||
groupId: 'group-2',
|
||||
group_name: 'Group2',
|
||||
output_type: VarType.number,
|
||||
variables: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const source = createNode({
|
||||
id: 'source-node',
|
||||
data: {
|
||||
type: BlockEnum.Code,
|
||||
title: 'Source',
|
||||
outputs: { rootVar: { type: VarType.string }, groupVar: { type: VarType.string } },
|
||||
},
|
||||
})
|
||||
const renderPanel = (data = createData(), readOnly = false) =>
|
||||
renderNodePanel(Panel, data, {
|
||||
nodes: [source, createNode({ id: 'node', data })],
|
||||
edges: [createEdge({ source: source.id, target: 'node' })],
|
||||
initialStoreState: { canvasReadOnly: readOnly },
|
||||
})
|
||||
|
||||
describe('variable-assigner/panel', () => {
|
||||
it('adds aggregation groups and preserves the first group when aggregation is disabled', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { data } = renderPanel()
|
||||
expect(screen.getByText('Group1')).toBeInTheDocument()
|
||||
expect(screen.getByText('Group2')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.nodes.common.outputVars' }))
|
||||
expect(screen.getByText('Group1.output')).toBeInTheDocument()
|
||||
expect(screen.getByText('Group2.output')).toBeInTheDocument()
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: 'workflowLogic.nodes.variableAssigner.addGroup' }),
|
||||
)
|
||||
expect(data().advanced_settings?.groups).toEqual([
|
||||
...createData().advanced_settings!.groups,
|
||||
expect.objectContaining({ group_name: 'Group3', output_type: VarType.any, variables: [] }),
|
||||
])
|
||||
expect(screen.getByText('Group3')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('switch'))
|
||||
expect(data()).toMatchObject({
|
||||
advanced_settings: { group_enabled: false },
|
||||
variables: [['source-node', 'groupVar']],
|
||||
output_type: VarType.string,
|
||||
})
|
||||
expect(screen.queryByText('Group1.output')).not.toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'workflowLogic.nodes.variableAssigner.addGroup' }),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders a single root group and hides output vars when aggregation is disabled', () => {
|
||||
renderPanel(createData({ advanced_settings: { group_enabled: false, groups: [] } }))
|
||||
expect(screen.getByText('rootVar')).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByText('workflowLogic.nodes.variableAssigner.aggregationGroup'),
|
||||
).toBeInTheDocument()
|
||||
expect(screen.queryByText('Group1.output')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('prevents adding or renaming groups in read-only mode', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { data } = renderPanel(createData(), true)
|
||||
expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'workflowLogic.nodes.variableAssigner.addGroup' }),
|
||||
).not.toBeInTheDocument()
|
||||
await user.click(screen.getByText('Group1'))
|
||||
expect(screen.queryByDisplayValue('Group1')).not.toBeInTheDocument()
|
||||
expect(data()).toMatchObject(createData())
|
||||
})
|
||||
|
||||
it.each(['cancel', 'confirm'])(
|
||||
'handles %s when disabling groups would remove a referenced output',
|
||||
async (action) => {
|
||||
const user = userEvent.setup()
|
||||
const initial = createData()
|
||||
const consumer = createNode({
|
||||
id: 'consumer',
|
||||
data: {
|
||||
type: BlockEnum.TemplateTransform,
|
||||
variables: [{ variable: 'value', value_selector: ['node', 'Group2', 'output'] }],
|
||||
template: '{{ value }}',
|
||||
},
|
||||
})
|
||||
const { data, getNode } = renderNodePanel(Panel, initial, {
|
||||
nodes: [source, createNode({ id: 'node', data: initial }), consumer],
|
||||
edges: [
|
||||
createEdge({ source: source.id, target: 'node' }),
|
||||
createEdge({ source: 'node', target: 'consumer' }),
|
||||
],
|
||||
})
|
||||
await user.click(screen.getByRole('switch'))
|
||||
expect(data().advanced_settings?.group_enabled).toBe(true)
|
||||
await user.click(screen.getByRole('button', { name: `common.operation.${action}` }))
|
||||
expect(data().advanced_settings?.group_enabled).toBe(action === 'cancel')
|
||||
expect(getNode('consumer')?.data.variables).toEqual([
|
||||
{
|
||||
variable: 'value',
|
||||
value_selector: action === 'confirm' ? [] : ['node', 'Group2', 'output'],
|
||||
},
|
||||
])
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'common.operation.confirm' }),
|
||||
).not.toBeInTheDocument()
|
||||
},
|
||||
)
|
||||
})
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { createConsoleQueryWrapper } from '@/test/console/query-data'
|
||||
import { seedToolProviders } from '@/test/console/tool-providers'
|
||||
|
||||
export function renderAssigner(...[ui, options]: Parameters<typeof renderWorkflowFlowComponent>) {
|
||||
const { queryClient } = createConsoleQueryWrapper()
|
||||
seedToolProviders(queryClient, {
|
||||
builtInTools: [],
|
||||
customTools: [],
|
||||
workflowTools: [],
|
||||
mcpTools: [],
|
||||
})
|
||||
queryClient.setQueryData(consoleQuery.spec.schemaDefinitions.get.queryKey(), [])
|
||||
return renderWorkflowFlowComponent(ui, { queryClient, ...options })
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
import type { VariableAssignerNodeType } from '../types'
|
||||
import { act, waitFor } from '@testing-library/react'
|
||||
import { BlockEnum, VarType } from '@/app/components/workflow/types'
|
||||
import { createEdge, createNode } from '../../../__tests__/fixtures'
|
||||
import { renderNodeConfig } from '../../__tests__/render-node-config'
|
||||
import useConfig from '../use-config'
|
||||
|
||||
// Inspector persistence is outside graph editing; its CRUD contract has separate coverage.
|
||||
const { deleteNodeInspectorVars, renameInspectVarName } = vi.hoisted(() => ({
|
||||
deleteNodeInspectorVars: vi.fn(),
|
||||
renameInspectVarName: vi.fn(),
|
||||
}))
|
||||
vi.mock('../../../hooks/use-inspect-vars-crud', () => ({
|
||||
default: () => ({ deleteNodeInspectorVars, renameInspectVarName }),
|
||||
}))
|
||||
const createPayload = (
|
||||
overrides: Partial<VariableAssignerNodeType> = {},
|
||||
): VariableAssignerNodeType => ({
|
||||
title: 'Variable Assigner',
|
||||
desc: '',
|
||||
type: BlockEnum.VariableAssigner,
|
||||
output_type: VarType.string,
|
||||
variables: [['source-node', 'initialVar']],
|
||||
advanced_settings: {
|
||||
group_enabled: true,
|
||||
groups: [
|
||||
{
|
||||
groupId: 'group-1',
|
||||
group_name: 'Group1',
|
||||
output_type: VarType.string,
|
||||
variables: [['source-node', 'initialVar']],
|
||||
},
|
||||
{
|
||||
groupId: 'group-2',
|
||||
group_name: 'Group2',
|
||||
output_type: VarType.number,
|
||||
variables: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const createPayloadWithoutAdvancedSettings = (): VariableAssignerNodeType => {
|
||||
const payload = createPayload() as Omit<VariableAssignerNodeType, 'advanced_settings'> & {
|
||||
advanced_settings?: VariableAssignerNodeType['advanced_settings']
|
||||
}
|
||||
delete payload.advanced_settings
|
||||
|
||||
return payload as VariableAssignerNodeType
|
||||
}
|
||||
|
||||
const renderWithConsumer = (groupName = 'Group2') => {
|
||||
const payload = createPayload()
|
||||
return renderNodeConfig(useConfig, payload, {
|
||||
nodes: [
|
||||
createNode({ id: 'node', data: payload }),
|
||||
createNode({
|
||||
id: 'consumer',
|
||||
data: {
|
||||
type: BlockEnum.TemplateTransform,
|
||||
template: '{{ output }}',
|
||||
variables: [{ variable: 'output', value_selector: ['node', groupName, 'output'] }],
|
||||
},
|
||||
}),
|
||||
],
|
||||
edges: [createEdge({ source: 'node', target: 'consumer' })],
|
||||
})
|
||||
}
|
||||
describe('variable-assigner/use-config', () => {
|
||||
it('preserves root bindings while editing groups and adding/removing other groups', () => {
|
||||
const { result } = renderNodeConfig(useConfig, createPayload())
|
||||
act(() =>
|
||||
result.current.config.handleListOrTypeChange({
|
||||
output_type: VarType.number,
|
||||
variables: [['source-node', 'changed']],
|
||||
}),
|
||||
)
|
||||
act(() =>
|
||||
result.current.config.handleListOrTypeChangeInGroup('group-1')({
|
||||
output_type: VarType.boolean,
|
||||
variables: [['source-node', 'groupVar']],
|
||||
}),
|
||||
)
|
||||
act(() => result.current.config.handleAddGroup())
|
||||
const added = result.current.config.inputs.advanced_settings!.groups[2]!
|
||||
act(() => result.current.config.handleGroupRemoved('group-2')())
|
||||
expect(result.current.flow.getNode('node')?.data).toMatchObject({
|
||||
output_type: VarType.number,
|
||||
variables: [['source-node', 'changed']],
|
||||
advanced_settings: {
|
||||
groups: [
|
||||
expect.objectContaining({
|
||||
groupId: 'group-1',
|
||||
output_type: VarType.boolean,
|
||||
variables: [['source-node', 'groupVar']],
|
||||
}),
|
||||
added,
|
||||
],
|
||||
},
|
||||
})
|
||||
expect(deleteNodeInspectorVars).toHaveBeenCalledWith('node')
|
||||
})
|
||||
it('renames the group and its downstream reference, then persists the inspector name', async () => {
|
||||
const { result } = renderWithConsumer('Group1')
|
||||
act(() => result.current.config.handleVarGroupNameChange('group-1')('Renamed'))
|
||||
expect(result.current.flow.getNode('node')?.data.advanced_settings.groups[0].group_name).toBe(
|
||||
'Renamed',
|
||||
)
|
||||
expect(result.current.flow.getNode('consumer')?.data.variables[0].value_selector).toEqual([
|
||||
'node',
|
||||
'Renamed',
|
||||
'output',
|
||||
])
|
||||
await waitFor(() =>
|
||||
expect(renameInspectVarName).toHaveBeenCalledWith('node', 'Group1', 'Renamed'),
|
||||
)
|
||||
})
|
||||
it.each(['remove', 'disable'] as const)(
|
||||
'requires confirmation to %s a referenced group',
|
||||
(action) => {
|
||||
const { result } = renderWithConsumer()
|
||||
act(() =>
|
||||
action === 'remove'
|
||||
? result.current.config.handleGroupRemoved('group-2')()
|
||||
: result.current.config.handleGroupEnabledChange(false),
|
||||
)
|
||||
expect(result.current.config.isShowRemoveVarConfirm).toBe(true)
|
||||
expect(result.current.flow.getNode('node')?.data.advanced_settings.groups).toHaveLength(2)
|
||||
expect(result.current.flow.getNode('consumer')?.data.variables[0].value_selector).toEqual([
|
||||
'node',
|
||||
'Group2',
|
||||
'output',
|
||||
])
|
||||
act(() => result.current.config.onRemoveVarConfirm())
|
||||
expect(result.current.config.isShowRemoveVarConfirm).toBe(false)
|
||||
expect(result.current.flow.getNode('consumer')?.data.variables[0].value_selector).toEqual([])
|
||||
if (action === 'remove')
|
||||
expect(result.current.flow.getNode('node')?.data.advanced_settings.groups).toEqual([
|
||||
expect.objectContaining({ groupId: 'group-1' }),
|
||||
])
|
||||
else
|
||||
expect(result.current.flow.getNode('node')?.data.advanced_settings.group_enabled).toBe(
|
||||
false,
|
||||
)
|
||||
},
|
||||
)
|
||||
it.each(['empty', 'legacy'] as const)(
|
||||
'enables groups for %s settings and restores root bindings when disabled',
|
||||
(variant) => {
|
||||
const payload =
|
||||
variant === 'legacy'
|
||||
? createPayloadWithoutAdvancedSettings()
|
||||
: createPayload({ advanced_settings: { group_enabled: false, groups: [] } })
|
||||
const { result } = renderNodeConfig(useConfig, payload)
|
||||
act(() => result.current.config.handleGroupEnabledChange(true))
|
||||
expect(result.current.flow.getNode('node')?.data.advanced_settings).toMatchObject({
|
||||
group_enabled: true,
|
||||
groups: [expect.objectContaining({ group_name: 'Group1', variables: payload.variables })],
|
||||
})
|
||||
act(() => result.current.config.handleGroupEnabledChange(false))
|
||||
expect(result.current.flow.getNode('node')?.data).toMatchObject({
|
||||
advanced_settings: { group_enabled: false },
|
||||
variables: payload.variables,
|
||||
output_type: payload.output_type,
|
||||
})
|
||||
},
|
||||
)
|
||||
})
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
import type { VariableAssignerNodeType } from '../types'
|
||||
import type { InputVar } from '@/app/components/workflow/types'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'
|
||||
import useSingleRunFormParams from '../use-single-run-form-params'
|
||||
|
||||
const createData = (
|
||||
overrides: Partial<VariableAssignerNodeType> = {},
|
||||
): VariableAssignerNodeType => ({
|
||||
title: 'Variable Assigner',
|
||||
desc: '',
|
||||
type: BlockEnum.VariableAssigner,
|
||||
output_type: VarType.string,
|
||||
variables: [['source-node', 'rootVar']],
|
||||
advanced_settings: {
|
||||
group_enabled: true,
|
||||
groups: [
|
||||
{
|
||||
groupId: 'group-1',
|
||||
group_name: 'Group1',
|
||||
output_type: VarType.string,
|
||||
variables: [
|
||||
['source-node', 'sharedVar'],
|
||||
['source-node', 'uniqueVar'],
|
||||
],
|
||||
},
|
||||
{
|
||||
groupId: 'group-2',
|
||||
group_name: 'Group2',
|
||||
output_type: VarType.number,
|
||||
variables: [['source-node', 'sharedVar']],
|
||||
},
|
||||
],
|
||||
},
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('variable-assigner/use-single-run-form-params', () => {
|
||||
it('deduplicates grouped variable inputs and marks them optional for single run', () => {
|
||||
const varSelectorsToVarInputs = vi.fn<() => InputVar[]>(() => [
|
||||
{
|
||||
label: 'Shared',
|
||||
variable: 'sharedVar',
|
||||
type: InputVarType.textInput,
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
label: 'Unique',
|
||||
variable: 'uniqueVar',
|
||||
type: InputVarType.number,
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
label: 'Shared duplicate',
|
||||
variable: 'sharedVar',
|
||||
type: InputVarType.textInput,
|
||||
required: true,
|
||||
},
|
||||
])
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSingleRunFormParams({
|
||||
id: 'assigner-node',
|
||||
payload: createData(),
|
||||
runInputData: { sharedVar: 'hello' },
|
||||
runInputDataRef: { current: {} },
|
||||
getInputVars: () => [],
|
||||
setRunInputData: vi.fn(),
|
||||
toVarInputs: () => [],
|
||||
varSelectorsToVarInputs,
|
||||
}),
|
||||
)
|
||||
|
||||
expect(varSelectorsToVarInputs).toHaveBeenCalledWith([
|
||||
['source-node', 'sharedVar'],
|
||||
['source-node', 'uniqueVar'],
|
||||
['source-node', 'sharedVar'],
|
||||
])
|
||||
expect(result.current.forms[0]!.inputs).toEqual([
|
||||
{
|
||||
label: 'Shared',
|
||||
variable: 'sharedVar',
|
||||
type: InputVarType.textInput,
|
||||
required: false,
|
||||
},
|
||||
{
|
||||
label: 'Unique',
|
||||
variable: 'uniqueVar',
|
||||
type: InputVarType.number,
|
||||
required: false,
|
||||
},
|
||||
])
|
||||
|
||||
expect(result.current.getDependentVars()).toEqual([
|
||||
[
|
||||
['source-node', 'sharedVar'],
|
||||
['source-node', 'uniqueVar'],
|
||||
],
|
||||
[['source-node', 'sharedVar']],
|
||||
])
|
||||
})
|
||||
|
||||
it('returns root variables directly when grouping is disabled', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useSingleRunFormParams({
|
||||
id: 'assigner-node',
|
||||
payload: createData({
|
||||
advanced_settings: {
|
||||
group_enabled: false,
|
||||
groups: [],
|
||||
},
|
||||
variables: [['source-node', 'rootVar']],
|
||||
}),
|
||||
runInputData: {},
|
||||
runInputDataRef: { current: {} },
|
||||
getInputVars: () => [],
|
||||
setRunInputData: vi.fn(),
|
||||
toVarInputs: () => [],
|
||||
varSelectorsToVarInputs: () => [],
|
||||
}),
|
||||
)
|
||||
|
||||
expect(result.current.getDependentVars()).toEqual([[['source-node', 'rootVar']]])
|
||||
})
|
||||
})
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
import type { VariableAssignerNodeType } from '../../types'
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import {
|
||||
createNode,
|
||||
createStartNode,
|
||||
resetFixtureCounters,
|
||||
} from '@/app/components/workflow/__tests__/fixtures'
|
||||
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { BlockEnum, VarType } from '@/app/components/workflow/types'
|
||||
import NodeGroupItem from '../node-group-item'
|
||||
|
||||
const mockGetAvailableVars = vi.hoisted(() => vi.fn())
|
||||
vi.mock('../../hooks', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../hooks')>()),
|
||||
useGetAvailableVars: () => mockGetAvailableVars,
|
||||
}))
|
||||
|
||||
const createData = (): VariableAssignerNodeType => ({
|
||||
title: 'Variable Assigner',
|
||||
desc: '',
|
||||
type: BlockEnum.VariableAssigner,
|
||||
output_type: VarType.any,
|
||||
variables: [],
|
||||
advanced_settings: {
|
||||
group_enabled: true,
|
||||
groups: [
|
||||
{
|
||||
group_name: 'Group A',
|
||||
groupId: 'group-1',
|
||||
output_type: VarType.string,
|
||||
variables: [],
|
||||
},
|
||||
{
|
||||
group_name: 'Group B',
|
||||
groupId: 'group-2',
|
||||
output_type: VarType.number,
|
||||
variables: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const assignerNode = createNode({
|
||||
id: 'assigner-node',
|
||||
data: createData(),
|
||||
})
|
||||
|
||||
const sourceNode = createNode({
|
||||
id: 'source-node',
|
||||
data: {
|
||||
type: BlockEnum.Answer,
|
||||
title: 'Source Node',
|
||||
},
|
||||
})
|
||||
|
||||
const startNode = createStartNode({
|
||||
id: 'start-node',
|
||||
})
|
||||
|
||||
describe('variable-assigner/node-group-item', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetFixtureCounters()
|
||||
mockGetAvailableVars.mockReturnValue([])
|
||||
})
|
||||
|
||||
it('tracks the hovered group while connecting and clears it when the pointer leaves', async () => {
|
||||
const user = userEvent.setup()
|
||||
const data = createData()
|
||||
const { store } = renderWorkflowFlowComponent(
|
||||
<NodeGroupItem
|
||||
item={{
|
||||
groupEnabled: true,
|
||||
targetHandleId: 'group-1',
|
||||
title: 'Group A',
|
||||
type: 'string',
|
||||
variables: [],
|
||||
variableAssignerNodeId: 'assigner-node',
|
||||
variableAssignerNodeData: data,
|
||||
}}
|
||||
/>,
|
||||
{
|
||||
nodes: [assignerNode, sourceNode, startNode],
|
||||
edges: [],
|
||||
initialStoreState: {
|
||||
enteringNodePayload: {
|
||||
nodeId: 'assigner-node',
|
||||
nodeData: data,
|
||||
},
|
||||
connectingNodePayload: {
|
||||
nodeId: 'source-node',
|
||||
nodeType: BlockEnum.Answer,
|
||||
handleType: 'source',
|
||||
handleId: 'source',
|
||||
},
|
||||
hoveringAssignVariableGroupId: undefined,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
expect(screen.getByText('workflowLogic.nodes.variableAssigner.varNotSet')).toBeInTheDocument()
|
||||
const groupTitle = screen.getByText('Group A')
|
||||
await user.hover(groupTitle)
|
||||
expect(store.getState().hoveringAssignVariableGroupId).toBe('group-1')
|
||||
await user.unhover(groupTitle)
|
||||
expect(store.getState().hoveringAssignVariableGroupId).toBeUndefined()
|
||||
})
|
||||
|
||||
it('renders system and node variables with their source names', () => {
|
||||
const data = createData()
|
||||
renderWorkflowFlowComponent(
|
||||
<NodeGroupItem
|
||||
item={{
|
||||
groupEnabled: true,
|
||||
targetHandleId: 'group-2',
|
||||
title: 'Group B',
|
||||
type: 'number',
|
||||
variables: [
|
||||
['sys', 'query'],
|
||||
['source-node', 'answer'],
|
||||
],
|
||||
variableAssignerNodeId: 'assigner-node',
|
||||
variableAssignerNodeData: data,
|
||||
}}
|
||||
/>,
|
||||
{
|
||||
nodes: [assignerNode, sourceNode, startNode],
|
||||
edges: [],
|
||||
initialStoreState: {
|
||||
enteringNodePayload: {
|
||||
nodeId: 'assigner-node',
|
||||
nodeData: data,
|
||||
} as never,
|
||||
hoveringAssignVariableGroupId: undefined,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
expect(screen.getByText('Start')).toBeInTheDocument()
|
||||
expect(screen.getByText('query')).toBeInTheDocument()
|
||||
expect(screen.getByText('Source Node')).toBeInTheDocument()
|
||||
expect(screen.getByText('answer')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
import type { VarGroupItem as Payload } from '../../types'
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { createEdge, createNode } from '@/app/components/workflow/__tests__/fixtures'
|
||||
import { BlockEnum, VarType } from '@/app/components/workflow/types'
|
||||
import { renderAssigner as renderWorkflowFlowComponent } from '../../__tests__/test-helpers'
|
||||
import VarGroupItem from '../var-group-item'
|
||||
|
||||
const source = createNode({
|
||||
id: 'source',
|
||||
data: {
|
||||
type: BlockEnum.Code,
|
||||
title: 'Source',
|
||||
outputs: {
|
||||
answer: { type: VarType.string },
|
||||
alternate: { type: VarType.string },
|
||||
flag: { type: VarType.boolean },
|
||||
},
|
||||
},
|
||||
})
|
||||
const availableVars = [
|
||||
{
|
||||
nodeId: 'source',
|
||||
title: 'Source',
|
||||
vars: [
|
||||
{ variable: 'answer', type: VarType.string },
|
||||
{ variable: 'alternate', type: VarType.string },
|
||||
{ variable: 'flag', type: VarType.boolean },
|
||||
],
|
||||
},
|
||||
]
|
||||
const renderGroup = () => {
|
||||
const onChange = vi.fn()
|
||||
function Harness() {
|
||||
const [payload, setPayload] = useState<Payload>({ output_type: VarType.any, variables: [] })
|
||||
return (
|
||||
<VarGroupItem
|
||||
readOnly={false}
|
||||
nodeId="group"
|
||||
payload={payload}
|
||||
groupEnabled={false}
|
||||
availableVars={availableVars}
|
||||
onChange={(next) => {
|
||||
setPayload(next)
|
||||
onChange(next)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
const result = renderWorkflowFlowComponent(<Harness />, {
|
||||
nodes: [source, createNode({ id: 'group', data: { type: BlockEnum.VariableAssigner } })],
|
||||
edges: [createEdge({ source: 'source', target: 'group' })],
|
||||
})
|
||||
return { ...result, onChange }
|
||||
}
|
||||
|
||||
it('fixes the group type after adding a variable, rejects duplicates, and resets it after removing the last value', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onChange } = renderGroup()
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.add' }))
|
||||
expect(await screen.findByText('flag')).toBeVisible()
|
||||
await user.click(screen.getByText('answer'))
|
||||
expect(onChange).toHaveBeenLastCalledWith({
|
||||
output_type: VarType.string,
|
||||
variables: [['source', 'answer']],
|
||||
})
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.add' }))
|
||||
const search = screen.getByRole('searchbox')
|
||||
await user.type(search, 'answer')
|
||||
await user.click(screen.getAllByText('answer').at(-1)!)
|
||||
expect(onChange).toHaveBeenCalledTimes(1)
|
||||
await user.keyboard('{Escape}')
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.remove' }))
|
||||
expect(onChange).toHaveBeenLastCalledWith({ output_type: VarType.any, variables: [] })
|
||||
expect(screen.getByText('workflowLogic.nodes.variableAssigner.noVarTip')).toBeVisible()
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.add' }))
|
||||
expect(await screen.findByText('flag')).toBeVisible()
|
||||
})
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { createNode } from '@/app/components/workflow/__tests__/fixtures'
|
||||
import { BlockEnum, VarType } from '@/app/components/workflow/types'
|
||||
import { renderAssigner as renderWorkflowFlowComponent } from '../../__tests__/test-helpers'
|
||||
import VarGroupItem from '../var-group-item'
|
||||
|
||||
it('normalizes spaces when renaming a variable group', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onGroupNameChange = vi.fn()
|
||||
function Harness() {
|
||||
const [name, setName] = useState('Group_A')
|
||||
return (
|
||||
<VarGroupItem
|
||||
readOnly={false}
|
||||
nodeId="node-1"
|
||||
payload={{ group_name: name, output_type: VarType.any, variables: [] }}
|
||||
onChange={vi.fn()}
|
||||
groupEnabled
|
||||
availableVars={[]}
|
||||
onGroupNameChange={(next) => {
|
||||
setName(next)
|
||||
onGroupNameChange(next)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
renderWorkflowFlowComponent(<Harness />, {
|
||||
nodes: [
|
||||
createNode({
|
||||
id: 'node-1',
|
||||
data: { type: BlockEnum.VariableAssigner, title: 'Variable Assigner' },
|
||||
}),
|
||||
],
|
||||
edges: [],
|
||||
hooksStoreProps: {},
|
||||
})
|
||||
|
||||
await user.click(screen.getByText('Group_A'))
|
||||
await user.type(screen.getByDisplayValue('Group_A'), ' renamed')
|
||||
await user.tab()
|
||||
expect(onGroupNameChange).toHaveBeenLastCalledWith('Group_A_renamed')
|
||||
expect(screen.getByText('Group_A_renamed')).toBeInTheDocument()
|
||||
})
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
import type { VariableAssignerNodeType } from '../../../types'
|
||||
import type { NodeOutPutVar } from '@/app/components/workflow/types'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useNodes } from 'reactflow'
|
||||
import { createNode } from '@/app/components/workflow/__tests__/fixtures'
|
||||
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { BlockEnum, VarType } from '@/app/components/workflow/types'
|
||||
import AddVariable from '../index'
|
||||
|
||||
vi.mock('@/app/components/workflow/collaboration/core/collaboration-manager', () => ({
|
||||
collaborationManager: {
|
||||
canApplyLocalGraphMutation: () => true,
|
||||
setNodes: vi.fn(),
|
||||
setEdges: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const availableVars: NodeOutPutVar[] = [
|
||||
{
|
||||
nodeId: 'node-source',
|
||||
title: 'Source Node',
|
||||
vars: [
|
||||
{ variable: 'answer', type: VarType.string },
|
||||
{ variable: 'second', type: VarType.string },
|
||||
],
|
||||
},
|
||||
]
|
||||
function Assignments() {
|
||||
const nodes = useNodes()
|
||||
return (
|
||||
<output aria-label="Assignments">
|
||||
{JSON.stringify(nodes.find((node) => node.id === 'node-target')?.data)}
|
||||
</output>
|
||||
)
|
||||
}
|
||||
const readAssignments = () => JSON.parse(screen.getByLabelText('Assignments').textContent!)
|
||||
function setup(grouped = false) {
|
||||
const data: VariableAssignerNodeType = {
|
||||
title: 'Variable Assigner',
|
||||
desc: '',
|
||||
type: BlockEnum.VariableAssigner,
|
||||
output_type: VarType.any,
|
||||
variables: [],
|
||||
advanced_settings: {
|
||||
group_enabled: grouped,
|
||||
groups: grouped
|
||||
? [{ groupId: 'group-1', group_name: 'Group 1', output_type: VarType.any, variables: [] }]
|
||||
: [],
|
||||
},
|
||||
}
|
||||
renderWorkflowFlowComponent(
|
||||
<>
|
||||
<input aria-label="Outside" />
|
||||
<AddVariable
|
||||
availableVars={availableVars}
|
||||
variableAssignerNodeId="node-target"
|
||||
variableAssignerNodeData={data}
|
||||
handleId={grouped ? 'group-1' : undefined}
|
||||
/>
|
||||
<Assignments />
|
||||
</>,
|
||||
{ nodes: [createNode({ id: 'node-target', data })] },
|
||||
)
|
||||
}
|
||||
|
||||
it('assigns the selected variable to the selected group and closes the popup', async () => {
|
||||
const user = userEvent.setup()
|
||||
setup(true)
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: 'workflowLogic.nodes.variableAssigner.setAssignVariable' }),
|
||||
)
|
||||
await user.click(screen.getByText('answer'))
|
||||
await waitFor(() =>
|
||||
expect(readAssignments()).toMatchObject({
|
||||
variables: [],
|
||||
advanced_settings: {
|
||||
groups: [
|
||||
{
|
||||
groupId: 'group-1',
|
||||
output_type: VarType.string,
|
||||
variables: [['node-source', 'answer']],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
)
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('assigns the keyboard choice to the node without handling outside keys', async () => {
|
||||
const user = userEvent.setup()
|
||||
setup()
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: 'workflowLogic.nodes.variableAssigner.setAssignVariable' }),
|
||||
)
|
||||
await user.keyboard('{ArrowDown}{Enter}')
|
||||
await waitFor(() =>
|
||||
expect(readAssignments()).toMatchObject({
|
||||
output_type: VarType.string,
|
||||
variables: [['node-source', 'second']],
|
||||
}),
|
||||
)
|
||||
await user.click(screen.getByRole('textbox', { name: 'Outside' }))
|
||||
await user.keyboard('{ArrowDown}{Enter}')
|
||||
expect(readAssignments().variables).toEqual([['node-source', 'second']])
|
||||
})
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
import type { VariableAssignerNodeType } from '../../types'
|
||||
import type { NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
|
||||
import { memo, useCallback, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import AddVariablePopup from '@/app/components/workflow/nodes/_base/components/add-variable-popup'
|
||||
import { useVariableAssigner } from '../../hooks'
|
||||
|
||||
type AddVariableProps = {
|
||||
variableAssignerNodeId: string
|
||||
variableAssignerNodeData: VariableAssignerNodeType
|
||||
availableVars: NodeOutPutVar[]
|
||||
handleId?: string
|
||||
}
|
||||
const AddVariable = ({
|
||||
availableVars,
|
||||
variableAssignerNodeId,
|
||||
variableAssignerNodeData,
|
||||
handleId,
|
||||
}: AddVariableProps) => {
|
||||
const { t } = useTranslation(['workflowLogic'])
|
||||
const [open, setOpen] = useState(false)
|
||||
const popupRef = useRef<HTMLDivElement>(null)
|
||||
const { handleAssignVariableValueChange } = useVariableAssigner()
|
||||
|
||||
const handleSelectVariable = useCallback(
|
||||
(v: ValueSelector, varDetail: Var) => {
|
||||
handleAssignVariableValueChange(variableAssignerNodeId, v, varDetail, handleId)
|
||||
setOpen(false)
|
||||
},
|
||||
[handleAssignVariableValueChange, variableAssignerNodeId, handleId, setOpen],
|
||||
)
|
||||
|
||||
return (
|
||||
<div className={cn(open && 'flex!', variableAssignerNodeData.selected && 'flex!')}>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger
|
||||
render={(props, state) => (
|
||||
<button
|
||||
{...props}
|
||||
type="button"
|
||||
aria-label={t(($) => $['nodes.variableAssigner.setAssignVariable'], {
|
||||
ns: 'workflowLogic',
|
||||
})}
|
||||
className={cn('block border-none bg-transparent p-0', props.className)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'group/addvariable flex items-center justify-center',
|
||||
'size-4 cursor-pointer',
|
||||
'hover:rounded-full hover:bg-primary-600',
|
||||
state.open && 'rounded-full! bg-primary-600!',
|
||||
)}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn(
|
||||
'i-custom-vender-line-general-plus-02 h-2.5 w-2.5',
|
||||
cn(
|
||||
'size-2.5 text-text-tertiary',
|
||||
'group-hover/addvariable:text-text-primary',
|
||||
state.open && 'text-text-primary!',
|
||||
),
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
/>
|
||||
<PopoverContent
|
||||
ref={popupRef}
|
||||
side="right"
|
||||
sideOffset={4}
|
||||
className="border-none bg-transparent shadow-none"
|
||||
>
|
||||
<AddVariablePopup
|
||||
onSelect={handleSelectVariable}
|
||||
availableVars={availableVars}
|
||||
keyboardTarget={popupRef}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(AddVariable)
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
import type { Node, ValueSelector, VarType } from '../../../types'
|
||||
import type { VariableAssignerNodeType } from '../types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { memo, useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useNodes } from 'reactflow'
|
||||
import { isSystemVar } from '@/app/components/workflow/nodes/_base/components/variable/utils'
|
||||
import { VariableLabelInNode } from '@/app/components/workflow/nodes/_base/components/variable/variable-label'
|
||||
import { isExceptionVariable } from '@/app/components/workflow/utils'
|
||||
import { useStore } from '../../../store'
|
||||
import { BlockEnum } from '../../../types'
|
||||
import { useGetAvailableVars, useVariableAssigner } from '../hooks'
|
||||
import { filterVar } from '../utils'
|
||||
import AddVariable from './add-variable'
|
||||
|
||||
const i18nPrefix = 'nodes.variableAssigner'
|
||||
type GroupItem = {
|
||||
groupEnabled: boolean
|
||||
targetHandleId: string
|
||||
title: string
|
||||
type: string
|
||||
variables: ValueSelector[]
|
||||
variableAssignerNodeId: string
|
||||
variableAssignerNodeData: VariableAssignerNodeType
|
||||
}
|
||||
type NodeGroupItemProps = {
|
||||
item: GroupItem
|
||||
}
|
||||
const NodeGroupItem = ({ item }: NodeGroupItemProps) => {
|
||||
const { t } = useTranslation(['workflowLogic'])
|
||||
const enteringNodePayload = useStore((s) => s.enteringNodePayload)
|
||||
const hoveringAssignVariableGroupId = useStore((s) => s.hoveringAssignVariableGroupId)
|
||||
const nodes: Node[] = useNodes()
|
||||
const { handleGroupItemMouseEnter, handleGroupItemMouseLeave } = useVariableAssigner()
|
||||
const getAvailableVars = useGetAvailableVars()
|
||||
const groupEnabled = item.groupEnabled
|
||||
const outputType = useMemo(() => {
|
||||
if (!groupEnabled) return item.variableAssignerNodeData.output_type
|
||||
|
||||
const group = item.variableAssignerNodeData.advanced_settings?.groups.find(
|
||||
(group) => group.groupId === item.targetHandleId,
|
||||
)
|
||||
return group?.output_type || ''
|
||||
}, [item.variableAssignerNodeData, item.targetHandleId, groupEnabled])
|
||||
const availableVars = getAvailableVars(
|
||||
item.variableAssignerNodeId,
|
||||
item.targetHandleId,
|
||||
filterVar(outputType as VarType),
|
||||
true,
|
||||
)
|
||||
const showSelectionBorder = useMemo(() => {
|
||||
if (groupEnabled && enteringNodePayload?.nodeId === item.variableAssignerNodeId) {
|
||||
if (hoveringAssignVariableGroupId)
|
||||
return hoveringAssignVariableGroupId !== item.targetHandleId
|
||||
else
|
||||
return (
|
||||
enteringNodePayload?.nodeData.advanced_settings?.groups[0]!.groupId !==
|
||||
item.targetHandleId
|
||||
)
|
||||
}
|
||||
|
||||
return false
|
||||
}, [
|
||||
enteringNodePayload,
|
||||
groupEnabled,
|
||||
hoveringAssignVariableGroupId,
|
||||
item.targetHandleId,
|
||||
item.variableAssignerNodeId,
|
||||
])
|
||||
const showSelectedBorder = useMemo(() => {
|
||||
if (groupEnabled && enteringNodePayload?.nodeId === item.variableAssignerNodeId) {
|
||||
if (hoveringAssignVariableGroupId)
|
||||
return hoveringAssignVariableGroupId === item.targetHandleId
|
||||
else
|
||||
return (
|
||||
enteringNodePayload?.nodeData.advanced_settings?.groups[0]!.groupId ===
|
||||
item.targetHandleId
|
||||
)
|
||||
}
|
||||
|
||||
return false
|
||||
}, [
|
||||
enteringNodePayload,
|
||||
groupEnabled,
|
||||
hoveringAssignVariableGroupId,
|
||||
item.targetHandleId,
|
||||
item.variableAssignerNodeId,
|
||||
])
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'relative rounded-lg border-[1.5px] border-transparent px-1.5 pt-1 pb-1.5',
|
||||
showSelectionBorder && 'border-dashed! border-divider-subtle! bg-state-base-hover',
|
||||
showSelectedBorder && 'border-text-accent! bg-util-colors-blue-blue-50!',
|
||||
)}
|
||||
onMouseEnter={() => groupEnabled && handleGroupItemMouseEnter(item.targetHandleId)}
|
||||
onMouseLeave={handleGroupItemMouseLeave}
|
||||
>
|
||||
<div className="flex h-4 items-center justify-between text-2xs font-medium text-text-tertiary">
|
||||
<span
|
||||
className={cn('grow truncate uppercase', showSelectedBorder && 'text-text-accent')}
|
||||
title={item.title}
|
||||
>
|
||||
{item.title}
|
||||
</span>
|
||||
<div className="flex items-center">
|
||||
<span className="ml-2 shrink-0">{item.type}</span>
|
||||
<div className="mr-1 ml-2 h-2.5 w-px bg-divider-regular"></div>
|
||||
<AddVariable
|
||||
availableVars={availableVars}
|
||||
variableAssignerNodeId={item.variableAssignerNodeId}
|
||||
variableAssignerNodeData={item.variableAssignerNodeData}
|
||||
handleId={item.targetHandleId}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{!item.variables.length && (
|
||||
<div
|
||||
className={cn(
|
||||
'relative flex h-5.5 items-center justify-between space-x-1 rounded-md bg-workflow-block-parma-bg px-1 text-2xs font-normal text-text-tertiary uppercase',
|
||||
(showSelectedBorder || showSelectionBorder) && 'bg-black/2!',
|
||||
)}
|
||||
>
|
||||
{t(($) => $[`${i18nPrefix}.varNotSet`], { ns: 'workflowLogic' })}
|
||||
</div>
|
||||
)}
|
||||
{!!item.variables.length && (
|
||||
<div className="space-y-0.5">
|
||||
{item.variables.map((variable = [], index) => {
|
||||
const isSystem = isSystemVar(variable)
|
||||
|
||||
const node = isSystem
|
||||
? nodes.find((node) => node.data.type === BlockEnum.Start)
|
||||
: nodes.find((node) => node.id === variable[0])
|
||||
const varName = isSystem
|
||||
? `sys.${variable[variable.length - 1]}`
|
||||
: variable.slice(1).join('.')
|
||||
const isException = isExceptionVariable(varName, node?.data.type)
|
||||
|
||||
return (
|
||||
<VariableLabelInNode
|
||||
key={index}
|
||||
variables={variable}
|
||||
nodeType={node?.data.type}
|
||||
nodeTitle={node?.data.title}
|
||||
isExceptionVariable={isException}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(NodeGroupItem)
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
'use client'
|
||||
import type { ChangeEvent, FC } from 'react'
|
||||
import type { VarGroupItem as VarGroupItemType } from '../types'
|
||||
import type { NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'
|
||||
import { RiDeleteBinLine } from '@remixicon/react'
|
||||
import { produce } from 'immer'
|
||||
import * as React from 'react'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Field from '@/app/components/workflow/nodes/_base/components/field'
|
||||
import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
|
||||
import { VarType } from '@/app/components/workflow/types'
|
||||
import { toast } from '@/app/notifications'
|
||||
import { checkKeys, replaceSpaceWithUnderscoreInVarNameInput } from '@/utils/var'
|
||||
import VarReferencePicker from '../../_base/components/variable/var-reference-picker'
|
||||
import VarList from '../components/var-list'
|
||||
|
||||
const i18nPrefix = 'nodes.variableAssigner'
|
||||
|
||||
type Payload = VarGroupItemType & {
|
||||
group_name?: string
|
||||
}
|
||||
|
||||
type Props = Readonly<{
|
||||
readOnly: boolean
|
||||
nodeId: string
|
||||
payload: Payload
|
||||
onChange: (newPayload: Payload) => void
|
||||
groupEnabled: boolean
|
||||
onGroupNameChange?: (value: string) => void
|
||||
canRemove?: boolean
|
||||
onRemove?: () => void
|
||||
availableVars: NodeOutPutVar[]
|
||||
}>
|
||||
|
||||
const VarGroupItem: FC<Props> = ({
|
||||
readOnly,
|
||||
nodeId,
|
||||
payload,
|
||||
onChange,
|
||||
groupEnabled,
|
||||
onGroupNameChange,
|
||||
canRemove,
|
||||
onRemove,
|
||||
availableVars,
|
||||
}) => {
|
||||
const { t } = useTranslation(['appDebug', 'workflow'])
|
||||
|
||||
const handleAddVariable = useCallback(
|
||||
(value: ValueSelector | string, _varKindType: VarKindType, varInfo?: Var) => {
|
||||
const chosenVariables = payload.variables
|
||||
if (chosenVariables.some((item) => item.join('.') === (value as ValueSelector).join('.')))
|
||||
return
|
||||
|
||||
const newPayload = produce(payload, (draft: Payload) => {
|
||||
draft.variables.push(value as ValueSelector)
|
||||
if (varInfo && varInfo.type !== VarType.any) draft.output_type = varInfo.type
|
||||
})
|
||||
onChange(newPayload)
|
||||
},
|
||||
[onChange, payload],
|
||||
)
|
||||
|
||||
const handleListChange = useCallback(
|
||||
(newList: ValueSelector[], changedItem?: ValueSelector) => {
|
||||
if (changedItem) {
|
||||
const chosenVariables = payload.variables
|
||||
if (chosenVariables.some((item) => item.join('.') === changedItem.join('.'))) return
|
||||
}
|
||||
|
||||
const newPayload = produce(payload, (draft) => {
|
||||
draft.variables = newList
|
||||
if (newList.length === 0) draft.output_type = VarType.any
|
||||
})
|
||||
onChange(newPayload)
|
||||
},
|
||||
[onChange, payload],
|
||||
)
|
||||
|
||||
const filterVar = useCallback(
|
||||
(varPayload: Var) => {
|
||||
if (payload.output_type === VarType.any) return true
|
||||
return varPayload.type === payload.output_type
|
||||
},
|
||||
[payload.output_type],
|
||||
)
|
||||
|
||||
const [isEditGroupName, setIsEditGroupName] = useState(false)
|
||||
|
||||
const handleGroupNameChange = useCallback(
|
||||
(e: ChangeEvent<any>) => {
|
||||
replaceSpaceWithUnderscoreInVarNameInput(e.target)
|
||||
const value = e.target.value
|
||||
const { isValid, errorKey, errorMessageKey } = checkKeys([value], false)
|
||||
if (!isValid) {
|
||||
toast.error(
|
||||
t(($) => $[`varKeyError.${errorMessageKey}`], { ns: 'appDebug', key: errorKey }),
|
||||
)
|
||||
return
|
||||
}
|
||||
onGroupNameChange?.(value)
|
||||
},
|
||||
[onGroupNameChange, t],
|
||||
)
|
||||
|
||||
return (
|
||||
<Field
|
||||
className="group"
|
||||
title={
|
||||
groupEnabled ? (
|
||||
<div className="flex items-center">
|
||||
<div className="flex items-center normal-case!">
|
||||
<span aria-hidden className="mr-0.5 i-custom-vender-line-files-folder size-3.5" />
|
||||
{!isEditGroupName ? (
|
||||
<div
|
||||
className="flex h-6 cursor-text items-center rounded-lg px-1 system-sm-semibold text-text-secondary hover:bg-gray-100"
|
||||
onClick={() => {
|
||||
if (!readOnly) setIsEditGroupName(true)
|
||||
}}
|
||||
>
|
||||
{payload.group_name}
|
||||
</div>
|
||||
) : (
|
||||
<input
|
||||
type="text"
|
||||
disabled={readOnly}
|
||||
className="h-6 rounded-lg border border-gray-300 bg-white px-1 focus:outline-hidden"
|
||||
// style={{
|
||||
// width: `${((payload.group_name?.length || 0) + 1) / 2}em`,
|
||||
// }}
|
||||
size={payload.group_name?.length} // to fit the input width
|
||||
autoFocus
|
||||
value={payload.group_name}
|
||||
onChange={handleGroupNameChange}
|
||||
onBlur={() => setIsEditGroupName(false)}
|
||||
maxLength={30}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{canRemove && (
|
||||
<div
|
||||
className="ml-0.5 hidden cursor-pointer rounded-md p-1 text-text-tertiary group-hover:block hover:bg-state-destructive-hover hover:text-text-destructive"
|
||||
onClick={onRemove}
|
||||
>
|
||||
<RiDeleteBinLine className="size-4" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
t(($) => $[`${i18nPrefix}.title`], { ns: 'workflow' })!
|
||||
)
|
||||
}
|
||||
operations={
|
||||
<div className="flex h-6 items-center space-x-2">
|
||||
{payload.variables.length > 0 && (
|
||||
<div className="flex h-4.5 items-center rounded-[5px] border border-divider-deep px-1 system-2xs-medium-uppercase text-text-tertiary">
|
||||
{payload.output_type}
|
||||
</div>
|
||||
)}
|
||||
{!readOnly ? (
|
||||
<VarReferencePicker
|
||||
isAddBtnTrigger
|
||||
readonly={false}
|
||||
nodeId={nodeId}
|
||||
isShowNodeName
|
||||
value={[]}
|
||||
onChange={handleAddVariable}
|
||||
defaultVarKindType={VarKindType.variable}
|
||||
filterVar={filterVar}
|
||||
availableVars={availableVars}
|
||||
/>
|
||||
) : undefined}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<VarList
|
||||
readonly={readOnly}
|
||||
nodeId={nodeId}
|
||||
list={payload.variables}
|
||||
onChange={handleListChange}
|
||||
filterVar={filterVar}
|
||||
/>
|
||||
</Field>
|
||||
)
|
||||
}
|
||||
export default React.memo(VarGroupItem)
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
import type { ComponentProps } from 'react'
|
||||
import { screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createEdge, createNode } from '@/app/components/workflow/__tests__/fixtures'
|
||||
import { BlockEnum, VarType } from '@/app/components/workflow/types'
|
||||
import { renderAssigner as renderWorkflowFlowComponent } from '../../../__tests__/test-helpers'
|
||||
import VarList from '../index'
|
||||
|
||||
const sourceNode = createNode({
|
||||
id: 'node-a',
|
||||
data: {
|
||||
type: BlockEnum.Code,
|
||||
title: 'Source Node',
|
||||
outputs: {
|
||||
answer: { type: VarType.string },
|
||||
other: { type: VarType.string },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const currentNode = createNode({
|
||||
id: 'node-current',
|
||||
data: {
|
||||
type: BlockEnum.VariableAssigner,
|
||||
title: 'Variable Assigner',
|
||||
},
|
||||
})
|
||||
|
||||
const renderVarList = (props: Partial<ComponentProps<typeof VarList>> = {}) => {
|
||||
const handleChange = vi.fn()
|
||||
const handleOpen = vi.fn()
|
||||
|
||||
const result = renderWorkflowFlowComponent(
|
||||
<VarList
|
||||
readonly={false}
|
||||
nodeId="node-current"
|
||||
list={[]}
|
||||
onChange={handleChange}
|
||||
onOpen={handleOpen}
|
||||
{...props}
|
||||
/>,
|
||||
{
|
||||
nodes: [sourceNode, currentNode],
|
||||
edges: [createEdge({ source: 'node-a', target: 'node-current' })],
|
||||
initialStoreState: { isWorkflowDataLoaded: true },
|
||||
hooksStoreProps: {},
|
||||
},
|
||||
)
|
||||
|
||||
return {
|
||||
...result,
|
||||
handleChange,
|
||||
handleOpen,
|
||||
}
|
||||
}
|
||||
|
||||
describe('variable-assigner/var-list', () => {
|
||||
it('selects a replacement through the real picker and removes the assigned variable', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { handleChange, handleOpen } = renderVarList({ list: [['node-a', 'other']] })
|
||||
await user.click(await screen.findByTestId('var-reference-picker-trigger'))
|
||||
expect(handleOpen).toHaveBeenCalledWith(0)
|
||||
const popup = await screen.findByRole('dialog')
|
||||
await user.click(await within(popup).findByText('answer'))
|
||||
expect(handleChange).toHaveBeenLastCalledWith([['node-a', 'answer']], ['node-a', 'answer'])
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.remove' }))
|
||||
expect(handleChange).toHaveBeenLastCalledWith([])
|
||||
})
|
||||
})
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { ValueSelector, Var } from '@/app/components/workflow/types'
|
||||
import { noop } from 'es-toolkit/function'
|
||||
import { produce } from 'immer'
|
||||
import * as React from 'react'
|
||||
import { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'
|
||||
import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
|
||||
import ListNoDataPlaceholder from '../../../_base/components/list-no-data-placeholder'
|
||||
import RemoveButton from '../../../_base/components/remove-button'
|
||||
|
||||
type Props = Readonly<{
|
||||
readonly: boolean
|
||||
nodeId: string
|
||||
list: ValueSelector[]
|
||||
onChange: (list: ValueSelector[], value?: ValueSelector) => void
|
||||
onOpen?: (index: number) => void
|
||||
filterVar?: (payload: Var, valueSelector: ValueSelector) => boolean
|
||||
}>
|
||||
|
||||
const VarList: FC<Props> = ({ readonly, nodeId, list, onChange, onOpen = noop, filterVar }) => {
|
||||
const { t } = useTranslation(['workflowLogic'])
|
||||
const handleVarReferenceChange = useCallback(
|
||||
(index: number) => {
|
||||
return (value: ValueSelector | string) => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft[index] = value as ValueSelector
|
||||
})
|
||||
onChange(newList, value as ValueSelector)
|
||||
}
|
||||
},
|
||||
[list, onChange],
|
||||
)
|
||||
|
||||
const handleVarRemove = useCallback(
|
||||
(index: number) => {
|
||||
return () => {
|
||||
const newList = produce(list, (draft) => {
|
||||
draft.splice(index, 1)
|
||||
})
|
||||
onChange(newList)
|
||||
}
|
||||
},
|
||||
[list, onChange],
|
||||
)
|
||||
|
||||
const handleOpen = useCallback(
|
||||
(index: number) => {
|
||||
return () => onOpen(index)
|
||||
},
|
||||
[onOpen],
|
||||
)
|
||||
|
||||
if (list.length === 0) {
|
||||
return (
|
||||
<ListNoDataPlaceholder>
|
||||
{t(($) => $['nodes.variableAssigner.noVarTip'], { ns: 'workflowLogic' })}
|
||||
</ListNoDataPlaceholder>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{list.map((item, index) => (
|
||||
<div className="flex items-center space-x-1" key={index}>
|
||||
<VarReferencePicker
|
||||
readonly={readonly}
|
||||
nodeId={nodeId}
|
||||
isShowNodeName
|
||||
className="grow"
|
||||
value={item}
|
||||
onChange={handleVarReferenceChange(index)}
|
||||
onOpen={handleOpen(index)}
|
||||
filterVar={filterVar}
|
||||
defaultVarKindType={VarKindType.variable}
|
||||
/>
|
||||
{!readonly && <RemoveButton onClick={handleVarRemove(index)} />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(VarList)
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { SelectorParam, TFunction } from 'i18next'
|
||||
import type { NodeDefault } from '../../types'
|
||||
import type { VariableAssignerNodeType } from './types'
|
||||
import { BlockClassification } from '@/app/components/workflow/block-selector/types'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import { genNodeMetaData } from '@/app/components/workflow/utils'
|
||||
import { VarType } from '../../types'
|
||||
|
||||
const metaData = genNodeMetaData({
|
||||
classification: BlockClassification.Transform,
|
||||
sort: 3,
|
||||
type: BlockEnum.VariableAggregator,
|
||||
})
|
||||
|
||||
type VariableFieldKey = 'errorMsg.fields.variableValue'
|
||||
|
||||
const variableFieldSelectors: Record<VariableFieldKey, SelectorParam<'workflow'>> = {
|
||||
'errorMsg.fields.variableValue': ($) => $['errorMsg.fields.variableValue'],
|
||||
}
|
||||
|
||||
const nodeDefault: NodeDefault<VariableAssignerNodeType> = {
|
||||
metaData,
|
||||
defaultValue: {
|
||||
output_type: VarType.any,
|
||||
variables: [],
|
||||
},
|
||||
checkValid(payload: VariableAssignerNodeType, t: TFunction<['workflow']>) {
|
||||
let errorMessages = ''
|
||||
const { variables, advanced_settings } = payload
|
||||
const { group_enabled = false, groups = [] } = advanced_settings || {}
|
||||
// enable group
|
||||
const validateVariables = (variables: any[], field: VariableFieldKey) => {
|
||||
variables.forEach((variable) => {
|
||||
if (!variable || variable.length === 0)
|
||||
errorMessages = t(($) => $['errorMsg.fieldRequired'], {
|
||||
ns: 'workflow',
|
||||
field: t(variableFieldSelectors[field], { ns: 'workflow' }),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
if (group_enabled) {
|
||||
if (!groups || groups.length === 0) {
|
||||
errorMessages = t(($) => $['errorMsg.fieldRequired'], {
|
||||
ns: 'workflow',
|
||||
field: t(($) => $['nodes.variableAssigner.title'], { ns: 'workflow' }),
|
||||
})
|
||||
} else if (!errorMessages) {
|
||||
groups.forEach((group) => {
|
||||
validateVariables(group.variables || [], 'errorMsg.fields.variableValue')
|
||||
})
|
||||
}
|
||||
} else {
|
||||
if (!variables || variables.length === 0)
|
||||
errorMessages = t(($) => $['errorMsg.fieldRequired'], {
|
||||
ns: 'workflow',
|
||||
field: t(($) => $['nodes.variableAssigner.title'], { ns: 'workflow' }),
|
||||
})
|
||||
else if (!errorMessages) validateVariables(variables, 'errorMsg.fields.variableValue')
|
||||
}
|
||||
|
||||
return {
|
||||
isValid: !errorMessages,
|
||||
errorMessage: errorMessages,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
export default nodeDefault
|
||||
@@ -0,0 +1,179 @@
|
||||
import type { Node, ValueSelector, Var } from '../../types'
|
||||
import type { VarGroupItem, VariableAssignerNodeType } from './types'
|
||||
import { uniqBy } from 'es-toolkit/compat'
|
||||
import { produce } from 'immer'
|
||||
import { useAtomValue } from 'jotai'
|
||||
import { useCallback } from 'react'
|
||||
import { useNodes, useStoreApi } from 'reactflow'
|
||||
import {
|
||||
editorResourceKindAtom,
|
||||
isChatflowAtom,
|
||||
} from '@/app/components/workflow/editor-resource/state'
|
||||
import { useNodeDataUpdate } from '../../hooks/use-node-data-update'
|
||||
import { useWorkflow } from '../../hooks/use-workflow'
|
||||
import { useWorkflowVariables } from '../../hooks/use-workflow-variables'
|
||||
import { useWorkflowStore } from '../../store'
|
||||
import { filterSnippetSystemVars } from '../_base/hooks/snippet-input-field-vars'
|
||||
|
||||
export const useVariableAssigner = () => {
|
||||
const store = useStoreApi()
|
||||
const workflowStore = useWorkflowStore()
|
||||
const { handleNodeDataUpdate } = useNodeDataUpdate()
|
||||
|
||||
const handleAssignVariableValueChange = useCallback(
|
||||
(nodeId: string, value: ValueSelector, varDetail: Var, groupId?: string) => {
|
||||
const { getNodes } = store.getState()
|
||||
const nodes = getNodes()
|
||||
const node: Node<VariableAssignerNodeType> = nodes.find((node) => node.id === nodeId)!
|
||||
|
||||
let payload
|
||||
if (groupId && groupId !== 'target') {
|
||||
payload = {
|
||||
advanced_settings: {
|
||||
...node.data.advanced_settings,
|
||||
groups: node.data.advanced_settings?.groups.map(
|
||||
(group: VarGroupItem & { groupId: string }) => {
|
||||
if (
|
||||
group.groupId === groupId &&
|
||||
!group.variables.some((item) => item.join('.') === value.join('.'))
|
||||
) {
|
||||
return {
|
||||
...group,
|
||||
variables: [...group.variables, value],
|
||||
output_type: varDetail.type,
|
||||
}
|
||||
}
|
||||
return group
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
} else {
|
||||
if (node.data.variables.some((item) => item.join('.') === value.join('.'))) return
|
||||
payload = {
|
||||
variables: [...node.data.variables, value],
|
||||
output_type: varDetail.type,
|
||||
}
|
||||
}
|
||||
handleNodeDataUpdate({
|
||||
id: nodeId,
|
||||
data: payload,
|
||||
})
|
||||
},
|
||||
[store, handleNodeDataUpdate],
|
||||
)
|
||||
|
||||
const handleAddVariableInAddVariablePopupWithPosition = useCallback(
|
||||
(
|
||||
nodeId: string,
|
||||
variableAssignerNodeId: string,
|
||||
variableAssignerNodeHandleId: string,
|
||||
value: ValueSelector,
|
||||
varDetail: Var,
|
||||
) => {
|
||||
const { getNodes, setNodes } = store.getState()
|
||||
const { setShowAssignVariablePopup } = workflowStore.getState()
|
||||
|
||||
const newNodes = produce(getNodes(), (draft) => {
|
||||
draft.forEach((node) => {
|
||||
if (node.id === nodeId || node.id === variableAssignerNodeId) {
|
||||
node.data = {
|
||||
...node.data,
|
||||
_showAddVariablePopup: false,
|
||||
_holdAddVariablePopup: false,
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
setNodes(newNodes)
|
||||
setShowAssignVariablePopup(undefined)
|
||||
handleAssignVariableValueChange(
|
||||
variableAssignerNodeId,
|
||||
value,
|
||||
varDetail,
|
||||
variableAssignerNodeHandleId,
|
||||
)
|
||||
},
|
||||
[store, workflowStore, handleAssignVariableValueChange],
|
||||
)
|
||||
|
||||
const handleGroupItemMouseEnter = useCallback(
|
||||
(groupId: string) => {
|
||||
const { setHoveringAssignVariableGroupId } = workflowStore.getState()
|
||||
|
||||
setHoveringAssignVariableGroupId(groupId)
|
||||
},
|
||||
[workflowStore],
|
||||
)
|
||||
|
||||
const handleGroupItemMouseLeave = useCallback(() => {
|
||||
const { connectingNodePayload, setHoveringAssignVariableGroupId } = workflowStore.getState()
|
||||
|
||||
if (connectingNodePayload) setHoveringAssignVariableGroupId(undefined)
|
||||
}, [workflowStore])
|
||||
|
||||
return {
|
||||
handleAddVariableInAddVariablePopupWithPosition,
|
||||
handleGroupItemMouseEnter,
|
||||
handleGroupItemMouseLeave,
|
||||
handleAssignVariableValueChange,
|
||||
}
|
||||
}
|
||||
|
||||
export const useGetAvailableVars = () => {
|
||||
const nodes: Node[] = useNodes()
|
||||
const { getBeforeNodesInSameBranchIncludeParent } = useWorkflow()
|
||||
const { getNodeAvailableVars } = useWorkflowVariables()
|
||||
const isChatflow = useAtomValue(isChatflowAtom)
|
||||
const isSnippetFlow = useAtomValue(editorResourceKindAtom) === 'snippet'
|
||||
const getAvailableVars = useCallback(
|
||||
(nodeId: string, handleId: string, filterVar: (v: Var) => boolean, hideEnv = false) => {
|
||||
const availableNodes: Node[] = []
|
||||
const currentNode = nodes.find((node) => node.id === nodeId)!
|
||||
|
||||
if (!currentNode) return []
|
||||
const beforeNodes = getBeforeNodesInSameBranchIncludeParent(nodeId)
|
||||
availableNodes.push(...beforeNodes)
|
||||
const parentNode = nodes.find((node) => node.id === currentNode.parentId)
|
||||
|
||||
if (hideEnv) {
|
||||
const availableVars = getNodeAvailableVars({
|
||||
parentNode,
|
||||
beforeNodes: uniqBy(availableNodes, 'id').filter((node) => node.id !== nodeId),
|
||||
isChatflow,
|
||||
hideEnv,
|
||||
hideChatVar: false,
|
||||
filterVar,
|
||||
})
|
||||
.map((node) => ({
|
||||
...node,
|
||||
vars: node.isStartNode
|
||||
? node.vars.filter((v) => !v.variable.startsWith('sys.'))
|
||||
: node.vars,
|
||||
}))
|
||||
.filter((item) => item.vars.length > 0)
|
||||
|
||||
return filterSnippetSystemVars(availableVars, isSnippetFlow)
|
||||
}
|
||||
|
||||
return filterSnippetSystemVars(
|
||||
getNodeAvailableVars({
|
||||
parentNode,
|
||||
beforeNodes: uniqBy(availableNodes, 'id').filter((node) => node.id !== nodeId),
|
||||
isChatflow,
|
||||
filterVar,
|
||||
}),
|
||||
isSnippetFlow,
|
||||
)
|
||||
},
|
||||
[
|
||||
nodes,
|
||||
getBeforeNodesInSameBranchIncludeParent,
|
||||
getNodeAvailableVars,
|
||||
isChatflow,
|
||||
isSnippetFlow,
|
||||
],
|
||||
)
|
||||
|
||||
return getAvailableVars
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { FC } from 'react'
|
||||
import type { NodeProps } from 'reactflow'
|
||||
import type { VariableAssignerNodeType } from './types'
|
||||
import { memo, useMemo, useRef } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import NodeGroupItem from './components/node-group-item'
|
||||
|
||||
const i18nPrefix = 'nodes.variableAssigner'
|
||||
|
||||
const Node: FC<NodeProps<VariableAssignerNodeType>> = (props) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const { id, data } = props
|
||||
const { advanced_settings } = data
|
||||
|
||||
const groups = useMemo(() => {
|
||||
if (!advanced_settings?.group_enabled) {
|
||||
return [
|
||||
{
|
||||
groupEnabled: false,
|
||||
targetHandleId: 'target',
|
||||
title: t(($) => $[`${i18nPrefix}.title`], { ns: 'workflow' }),
|
||||
type: data.output_type,
|
||||
variables: data.variables,
|
||||
variableAssignerNodeId: id,
|
||||
variableAssignerNodeData: data,
|
||||
},
|
||||
]
|
||||
}
|
||||
return advanced_settings.groups.map((group) => {
|
||||
return {
|
||||
groupEnabled: true,
|
||||
targetHandleId: group.groupId,
|
||||
title: group.group_name,
|
||||
type: group.output_type,
|
||||
variables: group.variables,
|
||||
variableAssignerNodeId: id,
|
||||
variableAssignerNodeData: data,
|
||||
}
|
||||
})
|
||||
}, [t, advanced_settings, data, id])
|
||||
|
||||
return (
|
||||
<div className="relative mb-1 space-y-0.5 px-1" ref={ref}>
|
||||
{groups.map((item) => {
|
||||
return <NodeGroupItem key={item.title} item={item} />
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(Node)
|
||||
@@ -0,0 +1,133 @@
|
||||
import type { FC } from 'react'
|
||||
import type { VariableAssignerNodeType } from './types'
|
||||
import type { NodePanelProps } from '@/app/components/workflow/types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Switch } from '@langgenius/dify-ui/switch'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import AddButton from '@/app/components/workflow/nodes/_base/components/add-button'
|
||||
import OutputVars, { VarItem } from '@/app/components/workflow/nodes/_base/components/output-vars'
|
||||
import Split from '@/app/components/workflow/nodes/_base/components/split'
|
||||
import Field from '../_base/components/field'
|
||||
import RemoveEffectVarConfirm from '../_base/components/remove-effect-var-confirm'
|
||||
import VarGroupItem from './components/var-group-item'
|
||||
import useConfig from './use-config'
|
||||
|
||||
const i18nPrefix = 'nodes.variableAssigner'
|
||||
const Panel: FC<NodePanelProps<VariableAssignerNodeType>> = ({ id, data }) => {
|
||||
const { t } = useTranslation(['workflowLogic'])
|
||||
|
||||
const {
|
||||
readOnly,
|
||||
inputs,
|
||||
handleListOrTypeChange,
|
||||
isEnableGroup,
|
||||
handleGroupEnabledChange,
|
||||
handleAddGroup,
|
||||
handleListOrTypeChangeInGroup,
|
||||
handleGroupRemoved,
|
||||
handleVarGroupNameChange,
|
||||
isShowRemoveVarConfirm,
|
||||
hideRemoveVarConfirm,
|
||||
onRemoveVarConfirm,
|
||||
getAvailableVars,
|
||||
filterVar,
|
||||
} = useConfig(id, data)
|
||||
|
||||
return (
|
||||
<div className="mt-2">
|
||||
<div className="space-y-4 px-4 pb-4">
|
||||
{!isEnableGroup ? (
|
||||
<VarGroupItem
|
||||
readOnly={readOnly}
|
||||
nodeId={id}
|
||||
payload={{
|
||||
output_type: inputs.output_type,
|
||||
variables: inputs.variables,
|
||||
}}
|
||||
onChange={handleListOrTypeChange}
|
||||
groupEnabled={false}
|
||||
availableVars={getAvailableVars(id, 'target', filterVar(inputs.output_type), true)}
|
||||
/>
|
||||
) : (
|
||||
<div>
|
||||
<div className="space-y-2">
|
||||
{inputs.advanced_settings?.groups.map((item, index) => (
|
||||
<div key={item.groupId}>
|
||||
<VarGroupItem
|
||||
readOnly={readOnly}
|
||||
nodeId={id}
|
||||
payload={item}
|
||||
onChange={handleListOrTypeChangeInGroup(item.groupId)}
|
||||
groupEnabled
|
||||
canRemove={!readOnly && inputs.advanced_settings?.groups.length > 1}
|
||||
onRemove={handleGroupRemoved(item.groupId)}
|
||||
onGroupNameChange={handleVarGroupNameChange(item.groupId)}
|
||||
availableVars={getAvailableVars(
|
||||
id,
|
||||
item.groupId,
|
||||
filterVar(item.output_type),
|
||||
true,
|
||||
)}
|
||||
/>
|
||||
{index !== inputs.advanced_settings?.groups.length - 1 && (
|
||||
<Split className="my-4" />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{!readOnly && (
|
||||
<AddButton
|
||||
className="mt-2"
|
||||
text={t(($) => $[`${i18nPrefix}.addGroup`], { ns: 'workflowLogic' })}
|
||||
onClick={handleAddGroup}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Split />
|
||||
<div className={cn('px-4 pt-4', isEnableGroup ? 'pb-4' : 'pb-2')}>
|
||||
<Field
|
||||
title={t(($) => $[`${i18nPrefix}.aggregationGroup`], { ns: 'workflowLogic' })}
|
||||
tooltip={t(($) => $[`${i18nPrefix}.aggregationGroupTip`], { ns: 'workflowLogic' })!}
|
||||
operations={
|
||||
<Switch
|
||||
checked={isEnableGroup}
|
||||
onCheckedChange={handleGroupEnabledChange}
|
||||
size="md"
|
||||
disabled={readOnly}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{isEnableGroup && (
|
||||
<>
|
||||
<Split />
|
||||
<OutputVars>
|
||||
<>
|
||||
{inputs.advanced_settings?.groups.map((item, index) => (
|
||||
<VarItem
|
||||
key={index}
|
||||
name={`${item.group_name}.output`}
|
||||
type={item.output_type}
|
||||
description={t(($) => $[`${i18nPrefix}.outputVars.varDescribe`], {
|
||||
ns: 'workflowLogic',
|
||||
groupName: item.group_name,
|
||||
})}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
</OutputVars>
|
||||
</>
|
||||
)}
|
||||
<RemoveEffectVarConfirm
|
||||
isShow={isShowRemoveVarConfirm}
|
||||
onCancel={hideRemoveVarConfirm}
|
||||
onConfirm={onRemoveVarConfirm}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Panel)
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { CommonNodeType, ValueSelector, VarType } from '@/app/components/workflow/types'
|
||||
|
||||
export type VarGroupItem = {
|
||||
output_type: VarType
|
||||
variables: ValueSelector[]
|
||||
}
|
||||
export type VariableAssignerNodeType = CommonNodeType &
|
||||
VarGroupItem & {
|
||||
advanced_settings: {
|
||||
group_enabled: boolean
|
||||
groups: ({
|
||||
group_name: string
|
||||
groupId: string
|
||||
} & VarGroupItem)[]
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
import type { Var } from '../../types'
|
||||
import type { VarGroupItem, VariableAssignerNodeType } from './types'
|
||||
import { produce } from 'immer'
|
||||
import { v4 as uuid4 } from 'uuid'
|
||||
import { VarType } from '../../types'
|
||||
|
||||
export const filterVarByType = (varType: VarType) => {
|
||||
return (variable: Var) => {
|
||||
if (varType === VarType.any || variable.type === VarType.any) return true
|
||||
|
||||
return variable.type === varType
|
||||
}
|
||||
}
|
||||
|
||||
export const updateRootVarGroupItem = (
|
||||
inputs: VariableAssignerNodeType,
|
||||
payload: VarGroupItem,
|
||||
) => ({
|
||||
...inputs,
|
||||
...payload,
|
||||
})
|
||||
|
||||
export const updateNestedVarGroupItem = (
|
||||
inputs: VariableAssignerNodeType,
|
||||
groupId: string,
|
||||
payload: VarGroupItem,
|
||||
) =>
|
||||
produce(inputs, (draft) => {
|
||||
if (!draft.advanced_settings) return
|
||||
|
||||
const index = draft.advanced_settings.groups.findIndex((item) => item.groupId === groupId)
|
||||
if (index < 0) return
|
||||
|
||||
draft.advanced_settings.groups[index] = {
|
||||
...draft.advanced_settings.groups[index]!,
|
||||
...payload,
|
||||
}
|
||||
})
|
||||
|
||||
export const removeGroupByIndex = (inputs: VariableAssignerNodeType, index: number) =>
|
||||
produce(inputs, (draft) => {
|
||||
if (!draft.advanced_settings) return
|
||||
if (index < 0 || index >= draft.advanced_settings.groups.length) return
|
||||
|
||||
draft.advanced_settings.groups.splice(index, 1)
|
||||
})
|
||||
|
||||
export const toggleGroupEnabled = ({
|
||||
inputs,
|
||||
enabled,
|
||||
}: {
|
||||
inputs: VariableAssignerNodeType
|
||||
enabled: boolean
|
||||
}) =>
|
||||
produce(inputs, (draft) => {
|
||||
if (!draft.advanced_settings) draft.advanced_settings = { group_enabled: false, groups: [] }
|
||||
|
||||
if (enabled) {
|
||||
if (draft.advanced_settings.groups.length === 0) {
|
||||
draft.advanced_settings.groups = [
|
||||
{
|
||||
output_type: draft.output_type,
|
||||
variables: draft.variables,
|
||||
group_name: 'Group1',
|
||||
groupId: uuid4(),
|
||||
},
|
||||
]
|
||||
}
|
||||
} else if (draft.advanced_settings.groups.length > 0) {
|
||||
draft.output_type = draft.advanced_settings.groups[0]!.output_type
|
||||
draft.variables = draft.advanced_settings.groups[0]!.variables
|
||||
}
|
||||
|
||||
draft.advanced_settings.group_enabled = enabled
|
||||
})
|
||||
|
||||
export const addGroup = (inputs: VariableAssignerNodeType) => {
|
||||
let maxInGroupName = 1
|
||||
const groups = inputs.advanced_settings?.groups ?? []
|
||||
groups.forEach((item) => {
|
||||
const match = /(\d+)$/.exec(item.group_name)
|
||||
if (match) {
|
||||
const num = Number.parseInt(match[1]!, 10)
|
||||
if (num > maxInGroupName) maxInGroupName = num
|
||||
}
|
||||
})
|
||||
|
||||
return produce(inputs, (draft) => {
|
||||
if (!draft.advanced_settings) draft.advanced_settings = { group_enabled: false, groups: [] }
|
||||
|
||||
draft.advanced_settings.groups.push({
|
||||
output_type: VarType.any,
|
||||
variables: [],
|
||||
group_name: `Group${maxInGroupName + 1}`,
|
||||
groupId: uuid4(),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export const renameGroup = (inputs: VariableAssignerNodeType, groupId: string, name: string) =>
|
||||
produce(inputs, (draft) => {
|
||||
if (!draft.advanced_settings) return
|
||||
|
||||
const index = draft.advanced_settings.groups.findIndex((item) => item.groupId === groupId)
|
||||
if (index < 0) return
|
||||
|
||||
draft.advanced_settings.groups[index]!.group_name = name
|
||||
})
|
||||
@@ -0,0 +1,167 @@
|
||||
import type { ValueSelector } from '../../types'
|
||||
import type { VarGroupItem, VariableAssignerNodeType } from './types'
|
||||
import { useDebounceFn } from 'ahooks'
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
|
||||
import useInspectVarsCrud from '../../hooks/use-inspect-vars-crud'
|
||||
import { useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'
|
||||
import { useGetAvailableVars } from './hooks'
|
||||
import {
|
||||
addGroup,
|
||||
filterVarByType,
|
||||
removeGroupByIndex,
|
||||
renameGroup,
|
||||
toggleGroupEnabled,
|
||||
updateNestedVarGroupItem,
|
||||
updateRootVarGroupItem,
|
||||
} from './use-config.helpers'
|
||||
|
||||
const useConfig = (id: string, payload: VariableAssignerNodeType) => {
|
||||
const { deleteNodeInspectorVars, renameInspectVarName } = useInspectVarsCrud()
|
||||
const { nodesReadOnly: readOnly } = useNodesReadOnly()
|
||||
const { handleOutVarRenameChange, isVarUsedInNodes, removeUsedVarInNodes } = useWorkflow()
|
||||
|
||||
const { inputs, setInputs } = useNodeCrud<VariableAssignerNodeType>(id, payload)
|
||||
const isEnableGroup = !!inputs.advanced_settings?.group_enabled
|
||||
|
||||
// Not Enable Group
|
||||
const handleListOrTypeChange = useCallback(
|
||||
(payload: VarGroupItem) => {
|
||||
setInputs(updateRootVarGroupItem(inputs, payload))
|
||||
},
|
||||
[inputs, setInputs],
|
||||
)
|
||||
|
||||
const handleListOrTypeChangeInGroup = useCallback(
|
||||
(groupId: string) => {
|
||||
return (payload: VarGroupItem) => {
|
||||
setInputs(updateNestedVarGroupItem(inputs, groupId, payload))
|
||||
}
|
||||
},
|
||||
[inputs, setInputs],
|
||||
)
|
||||
|
||||
const getAvailableVars = useGetAvailableVars()
|
||||
|
||||
const [isShowRemoveVarConfirm, setIsShowRemoveVarConfirm] = useState(false)
|
||||
|
||||
const [removedVars, setRemovedVars] = useState<ValueSelector[]>([])
|
||||
const [removeType, setRemoveType] = useState<'group' | 'enableChanged'>('group')
|
||||
const [removedGroupIndex, setRemovedGroupIndex] = useState<number>(-1)
|
||||
const handleGroupRemoved = useCallback(
|
||||
(groupId: string) => {
|
||||
return () => {
|
||||
const groups = inputs.advanced_settings?.groups ?? []
|
||||
const index = groups.findIndex((item) => item.groupId === groupId)
|
||||
if (index < 0) return
|
||||
|
||||
const groupName = groups[index]!.group_name
|
||||
if (isVarUsedInNodes([id, groupName, 'output'])) {
|
||||
setIsShowRemoveVarConfirm(true)
|
||||
setRemovedVars([[id, groupName, 'output']])
|
||||
setRemoveType('group')
|
||||
setRemovedGroupIndex(index)
|
||||
return
|
||||
}
|
||||
setInputs(removeGroupByIndex(inputs, index))
|
||||
}
|
||||
},
|
||||
[id, inputs, isVarUsedInNodes, setInputs],
|
||||
)
|
||||
|
||||
const handleGroupEnabledChange = useCallback(
|
||||
(enabled: boolean) => {
|
||||
const groups = inputs.advanced_settings?.groups ?? []
|
||||
|
||||
if (enabled && groups.length === 0) {
|
||||
handleOutVarRenameChange(id, [id, 'output'], [id, 'Group1', 'output'])
|
||||
}
|
||||
|
||||
if (!enabled && groups.length > 0) {
|
||||
if (groups.length > 1) {
|
||||
const useVars = groups.filter(
|
||||
(item, index) => index > 0 && isVarUsedInNodes([id, item.group_name, 'output']),
|
||||
)
|
||||
if (useVars.length > 0) {
|
||||
setIsShowRemoveVarConfirm(true)
|
||||
setRemovedVars(useVars.map((item) => [id, item.group_name, 'output']))
|
||||
setRemoveType('enableChanged')
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
handleOutVarRenameChange(id, [id, groups[0]!.group_name, 'output'], [id, 'output'])
|
||||
}
|
||||
|
||||
setInputs(toggleGroupEnabled({ inputs, enabled }))
|
||||
deleteNodeInspectorVars(id)
|
||||
},
|
||||
[deleteNodeInspectorVars, handleOutVarRenameChange, id, inputs, isVarUsedInNodes, setInputs],
|
||||
)
|
||||
|
||||
const handleAddGroup = useCallback(() => {
|
||||
setInputs(addGroup(inputs))
|
||||
deleteNodeInspectorVars(id)
|
||||
}, [deleteNodeInspectorVars, id, inputs, setInputs])
|
||||
|
||||
// record the first old name value
|
||||
const oldNameRef = useRef<Record<string, string>>({})
|
||||
|
||||
const { run: renameInspectNameWithDebounce } = useDebounceFn(
|
||||
(id: string, newName: string) => {
|
||||
const oldName = oldNameRef.current[id]
|
||||
renameInspectVarName(id, oldName!, newName)
|
||||
delete oldNameRef.current[id]
|
||||
},
|
||||
{ wait: 500 },
|
||||
)
|
||||
|
||||
const handleVarGroupNameChange = useCallback(
|
||||
(groupId: string) => {
|
||||
return (name: string) => {
|
||||
const groups = inputs.advanced_settings?.groups ?? []
|
||||
const index = groups.findIndex((item) => item.groupId === groupId)
|
||||
if (index < 0) return
|
||||
|
||||
const oldName = groups[index]!.group_name
|
||||
handleOutVarRenameChange(id, [id, oldName, 'output'], [id, name, 'output'])
|
||||
setInputs(renameGroup(inputs, groupId, name))
|
||||
if (!(id in oldNameRef.current)) oldNameRef.current[id] = oldName
|
||||
renameInspectNameWithDebounce(id, name)
|
||||
}
|
||||
},
|
||||
[handleOutVarRenameChange, id, inputs, renameInspectNameWithDebounce, setInputs],
|
||||
)
|
||||
|
||||
const onRemoveVarConfirm = useCallback(() => {
|
||||
removedVars.forEach((v) => {
|
||||
removeUsedVarInNodes(v)
|
||||
})
|
||||
setIsShowRemoveVarConfirm(false)
|
||||
if (removeType === 'group') {
|
||||
if (removedGroupIndex >= 0) setInputs(removeGroupByIndex(inputs, removedGroupIndex))
|
||||
} else {
|
||||
// removeType === 'enableChanged' to enabled
|
||||
setInputs(toggleGroupEnabled({ inputs, enabled: false }))
|
||||
}
|
||||
}, [removedVars, removeType, removeUsedVarInNodes, inputs, setInputs, removedGroupIndex])
|
||||
|
||||
return {
|
||||
readOnly,
|
||||
inputs,
|
||||
handleListOrTypeChange,
|
||||
isEnableGroup,
|
||||
handleGroupEnabledChange,
|
||||
handleAddGroup,
|
||||
handleListOrTypeChangeInGroup,
|
||||
handleGroupRemoved,
|
||||
handleVarGroupNameChange,
|
||||
isShowRemoveVarConfirm,
|
||||
hideRemoveVarConfirm: () => setIsShowRemoveVarConfirm(false),
|
||||
onRemoveVarConfirm,
|
||||
getAvailableVars,
|
||||
filterVar: filterVarByType,
|
||||
}
|
||||
}
|
||||
|
||||
export default useConfig
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import type { RefObject } from 'react'
|
||||
import type { VariableAssignerNodeType } from './types'
|
||||
import type { InputVar, ValueSelector, Variable } from '@/app/components/workflow/types'
|
||||
import { useCallback } from 'react'
|
||||
|
||||
type Params = {
|
||||
id: string
|
||||
payload: VariableAssignerNodeType
|
||||
runInputData: Record<string, unknown>
|
||||
runInputDataRef: RefObject<Record<string, unknown>>
|
||||
getInputVars: (textList: string[]) => InputVar[]
|
||||
setRunInputData: (data: Record<string, unknown>) => void
|
||||
toVarInputs: (variables: Variable[]) => InputVar[]
|
||||
varSelectorsToVarInputs: (variables: ValueSelector[]) => InputVar[]
|
||||
}
|
||||
const useSingleRunFormParams = ({
|
||||
payload,
|
||||
runInputData,
|
||||
setRunInputData,
|
||||
varSelectorsToVarInputs,
|
||||
}: Params) => {
|
||||
const setInputVarValues = useCallback(
|
||||
(newPayload: Record<string, unknown>) => {
|
||||
setRunInputData(newPayload)
|
||||
},
|
||||
[setRunInputData],
|
||||
)
|
||||
const inputVarValues = (() => {
|
||||
const vars: Record<string, unknown> = {}
|
||||
Object.keys(runInputData).forEach((key) => {
|
||||
vars[key] = runInputData[key]
|
||||
})
|
||||
return vars
|
||||
})()
|
||||
|
||||
const forms = (() => {
|
||||
const allInputs: ValueSelector[] = []
|
||||
const isGroupEnabled = !!payload.advanced_settings?.group_enabled
|
||||
if (!isGroupEnabled && payload.variables && payload.variables.length) {
|
||||
payload.variables.forEach((varSelector) => {
|
||||
allInputs.push(varSelector)
|
||||
})
|
||||
}
|
||||
if (
|
||||
isGroupEnabled &&
|
||||
payload.advanced_settings &&
|
||||
payload.advanced_settings.groups &&
|
||||
payload.advanced_settings.groups.length
|
||||
) {
|
||||
payload.advanced_settings.groups.forEach((group) => {
|
||||
group.variables?.forEach((varSelector) => {
|
||||
allInputs.push(varSelector)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const varInputs = varSelectorsToVarInputs(allInputs)
|
||||
// remove duplicate inputs
|
||||
const existVarsKey: Record<string, boolean> = {}
|
||||
const uniqueVarInputs: InputVar[] = []
|
||||
varInputs.forEach((input) => {
|
||||
if (!input) return
|
||||
if (!existVarsKey[input.variable]) {
|
||||
existVarsKey[input.variable] = true
|
||||
uniqueVarInputs.push({
|
||||
...input,
|
||||
required: false, // just one of the inputs is required
|
||||
})
|
||||
}
|
||||
})
|
||||
return [
|
||||
{
|
||||
inputs: uniqueVarInputs,
|
||||
values: inputVarValues,
|
||||
onChange: setInputVarValues,
|
||||
},
|
||||
]
|
||||
})()
|
||||
|
||||
const getDependentVars = () => {
|
||||
if (payload.advanced_settings?.group_enabled) {
|
||||
const vars: ValueSelector[][] = []
|
||||
payload.advanced_settings.groups.forEach((group) => {
|
||||
if (group.variables) vars.push([...group.variables])
|
||||
})
|
||||
return vars
|
||||
}
|
||||
return [payload.variables]
|
||||
}
|
||||
|
||||
return {
|
||||
forms,
|
||||
getDependentVars,
|
||||
}
|
||||
}
|
||||
|
||||
export default useSingleRunFormParams
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { Var } from '../../types'
|
||||
import { VarType } from '../../types'
|
||||
|
||||
export const filterVar = (varType: VarType) => {
|
||||
return (v: Var) => {
|
||||
if (varType === VarType.any) return true
|
||||
if (v.type === VarType.any) return true
|
||||
return v.type === varType
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user