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
@@ -0,0 +1,44 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { createNode } from '@/app/components/workflow/__tests__/fixtures'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import WorkflowPreview from '../index'
|
||||
|
||||
const defaultViewport = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
zoom: 1,
|
||||
}
|
||||
|
||||
describe('WorkflowPreview', () => {
|
||||
it('renders a portable Agent v2 node with its title and description', async () => {
|
||||
render(
|
||||
<div style={{ width: 800, height: 600 }}>
|
||||
<WorkflowPreview
|
||||
nodes={[
|
||||
createNode({
|
||||
id: 'agent-v2-1',
|
||||
type: 'custom',
|
||||
position: { x: 100, y: 100 },
|
||||
data: {
|
||||
type: BlockEnum.Agent,
|
||||
version: '2',
|
||||
agent_node_kind: 'dify_agent',
|
||||
title: 'Research Agent',
|
||||
desc: 'Handles research tasks',
|
||||
agent_binding: {
|
||||
binding_type: 'roster_agent',
|
||||
package_ref: 'agent_1',
|
||||
},
|
||||
},
|
||||
}),
|
||||
]}
|
||||
edges={[]}
|
||||
viewport={defaultViewport}
|
||||
/>
|
||||
</div>,
|
||||
)
|
||||
|
||||
expect(await screen.findByText('Research Agent')).toBeInTheDocument()
|
||||
expect(screen.getByText('Handles research tasks')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import type { NodeProps } from 'reactflow'
|
||||
import type { CommonNodeType } from '@/app/components/workflow/types'
|
||||
import { screen } from '@testing-library/react'
|
||||
import { createNode } from '@/app/components/workflow/__tests__/fixtures'
|
||||
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { ErrorHandleTypeEnum } from '@/app/components/workflow/nodes/_base/components/error-handle/types'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import ErrorHandleOnNode from '../error-handle-on-node'
|
||||
|
||||
const createNodeData = (overrides: Partial<CommonNodeType> = {}): CommonNodeType => ({
|
||||
type: BlockEnum.Code,
|
||||
title: 'Node',
|
||||
desc: '',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const ErrorNode = ({ id, data }: NodeProps<CommonNodeType>) => (
|
||||
<div>
|
||||
<ErrorHandleOnNode id={id} data={data} />
|
||||
</div>
|
||||
)
|
||||
|
||||
const renderErrorNode = (data: CommonNodeType) =>
|
||||
renderWorkflowFlowComponent(<div />, {
|
||||
nodes: [
|
||||
createNode({
|
||||
id: 'node-1',
|
||||
type: 'errorNode',
|
||||
data,
|
||||
}),
|
||||
],
|
||||
edges: [],
|
||||
reactFlowProps: {
|
||||
nodeTypes: { errorNode: ErrorNode },
|
||||
},
|
||||
})
|
||||
|
||||
describe('ErrorHandleOnNode', () => {
|
||||
// Empty and default-value states.
|
||||
describe('Rendering', () => {
|
||||
it('should render the default-value label', async () => {
|
||||
renderErrorNode(createNodeData({ error_strategy: ErrorHandleTypeEnum.defaultValue }))
|
||||
|
||||
expect(await screen.findByText('workflow.common.onFailure')).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByText('workflow.nodes.common.errorHandle.defaultValue.output'),
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
// Fail-branch behavior and warning styling.
|
||||
describe('Effects', () => {
|
||||
it('should render the fail-branch source handle', async () => {
|
||||
const { container } = renderErrorNode(
|
||||
createNodeData({ error_strategy: ErrorHandleTypeEnum.failBranch }),
|
||||
)
|
||||
|
||||
expect(
|
||||
await screen.findByText('workflow.nodes.common.errorHandle.failBranch.title'),
|
||||
).toBeInTheDocument()
|
||||
expect(container.querySelector('[data-handleid="fail-branch"]')).toHaveAttribute(
|
||||
'data-handleid',
|
||||
ErrorHandleTypeEnum.failBranch,
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
import { screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createNode } from '../../../__tests__/fixtures'
|
||||
import { renderWorkflowFlowComponent } from '../../../__tests__/workflow-test-env'
|
||||
import ZoomInOut from '../zoom-in-out'
|
||||
|
||||
const renderZoom = (zoom = 1) =>
|
||||
renderWorkflowFlowComponent(<ZoomInOut />, {
|
||||
nodes: [
|
||||
createNode({ id: 'left', position: { x: 0, y: 0 }, width: 240, height: 80 }),
|
||||
createNode({ id: 'right', position: { x: 1600, y: 400 }, width: 240, height: 80 }),
|
||||
],
|
||||
reactFlowProps: {
|
||||
fitView: false,
|
||||
minZoom: 0.25,
|
||||
maxZoom: 2,
|
||||
defaultViewport: { x: 0, y: 0, zoom },
|
||||
},
|
||||
})
|
||||
|
||||
const zoomLabel = () => screen.getByRole('button', { name: /^\d+%$/ })
|
||||
const openZoomMenu = async (user: ReturnType<typeof userEvent.setup>) => {
|
||||
await user.click(zoomLabel())
|
||||
return within(await screen.findByRole('menu'))
|
||||
}
|
||||
|
||||
describe('workflow preview zoom controls', () => {
|
||||
it('zooms out and in and displays the resulting viewport scale', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderZoom()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.operator.zoomOut' }))
|
||||
await waitFor(() => expect(zoomLabel()).toHaveAccessibleName('83%'))
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.operator.zoomIn' }))
|
||||
await waitFor(() => expect(zoomLabel()).toHaveAccessibleName('100%'))
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ zoom: 0.25, control: 'workflow.operator.zoomOut', label: '25%' },
|
||||
{ zoom: 2, control: 'workflow.operator.zoomIn', label: '200%' },
|
||||
])('disables $control at $label', async ({ zoom, control, label }) => {
|
||||
const user = userEvent.setup()
|
||||
renderZoom(zoom)
|
||||
const button = screen.getByRole('button', { name: control })
|
||||
|
||||
expect(button).toBeDisabled()
|
||||
await user.click(button)
|
||||
expect(zoomLabel()).toHaveAccessibleName(label)
|
||||
})
|
||||
|
||||
it.each(['25%', '50%', '75%', '100%', '200%'])(
|
||||
'applies the %s preset from a click',
|
||||
async (label) => {
|
||||
const user = userEvent.setup()
|
||||
renderZoom(label === '100%' ? 0.75 : 1)
|
||||
const menu = await openZoomMenu(user)
|
||||
|
||||
await user.click(menu.getByRole('menuitem', { name: new RegExp(`^${label}`) }))
|
||||
|
||||
await waitFor(() => expect(zoomLabel()).toHaveAccessibleName(label))
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
},
|
||||
)
|
||||
|
||||
it('fits the graph from the menu', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderZoom()
|
||||
const menu = await openZoomMenu(user)
|
||||
|
||||
await user.click(menu.getByRole('menuitem', { name: /^workflow\.operator\.zoomToFit/ }))
|
||||
|
||||
await waitFor(() => expect(zoomLabel()).toHaveAccessibleName('25%'))
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import type { EdgeProps } from 'reactflow'
|
||||
import { memo, useMemo } from 'react'
|
||||
import { BaseEdge, getBezierPath, Position } from 'reactflow'
|
||||
import CustomEdgeLinearGradientRender from '@/app/components/workflow/custom-edge-linear-gradient-render'
|
||||
import { ErrorHandleTypeEnum } from '@/app/components/workflow/nodes/_base/components/error-handle/types'
|
||||
import { NodeRunningStatus } from '@/app/components/workflow/types'
|
||||
import { getEdgeColor } from '@/app/components/workflow/utils'
|
||||
|
||||
const CustomEdge = ({
|
||||
id,
|
||||
data,
|
||||
sourceHandleId,
|
||||
sourceX,
|
||||
sourceY,
|
||||
targetX,
|
||||
targetY,
|
||||
selected,
|
||||
}: EdgeProps) => {
|
||||
const [edgePath] = getBezierPath({
|
||||
sourceX: sourceX - 8,
|
||||
sourceY,
|
||||
sourcePosition: Position.Right,
|
||||
targetX: targetX + 8,
|
||||
targetY,
|
||||
targetPosition: Position.Left,
|
||||
curvature: 0.16,
|
||||
})
|
||||
const { _sourceRunningStatus, _targetRunningStatus } = data
|
||||
|
||||
const linearGradientId = useMemo(() => {
|
||||
if (
|
||||
(_sourceRunningStatus === NodeRunningStatus.Succeeded ||
|
||||
_sourceRunningStatus === NodeRunningStatus.Failed ||
|
||||
_sourceRunningStatus === NodeRunningStatus.Exception) &&
|
||||
(_targetRunningStatus === NodeRunningStatus.Succeeded ||
|
||||
_targetRunningStatus === NodeRunningStatus.Failed ||
|
||||
_targetRunningStatus === NodeRunningStatus.Exception ||
|
||||
_targetRunningStatus === NodeRunningStatus.Running)
|
||||
) {
|
||||
return id
|
||||
}
|
||||
}, [_sourceRunningStatus, _targetRunningStatus, id])
|
||||
|
||||
const stroke = useMemo(() => {
|
||||
if (selected) return getEdgeColor(NodeRunningStatus.Running)
|
||||
|
||||
if (linearGradientId) return `url(#${linearGradientId})`
|
||||
|
||||
if (data?._connectedNodeIsHovering)
|
||||
return getEdgeColor(
|
||||
NodeRunningStatus.Running,
|
||||
sourceHandleId === ErrorHandleTypeEnum.failBranch,
|
||||
)
|
||||
|
||||
return getEdgeColor()
|
||||
}, [data._connectedNodeIsHovering, linearGradientId, selected, sourceHandleId])
|
||||
|
||||
return (
|
||||
<>
|
||||
{linearGradientId && (
|
||||
<CustomEdgeLinearGradientRender
|
||||
id={linearGradientId}
|
||||
startColor={getEdgeColor(_sourceRunningStatus)}
|
||||
stopColor={getEdgeColor(_targetRunningStatus)}
|
||||
position={{
|
||||
x1: sourceX,
|
||||
y1: sourceY,
|
||||
x2: targetX,
|
||||
y2: targetY,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<BaseEdge
|
||||
id={id}
|
||||
path={edgePath}
|
||||
style={{
|
||||
stroke,
|
||||
strokeWidth: 2,
|
||||
opacity: data._waitingRun ? 0.7 : 1,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(CustomEdge)
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import type { Node } from '@/app/components/workflow/types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { useEffect } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useUpdateNodeInternals } from 'reactflow'
|
||||
import { ErrorHandleTypeEnum } from '@/app/components/workflow/nodes/_base/components/error-handle/types'
|
||||
import { NodeRunningStatus } from '@/app/components/workflow/types'
|
||||
import { NodeSourceHandle } from './node-handle'
|
||||
|
||||
type ErrorHandleOnNodeProps = Pick<Node, 'id' | 'data'>
|
||||
const ErrorHandleOnNode = ({ id, data }: ErrorHandleOnNodeProps) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const { error_strategy } = data
|
||||
const updateNodeInternals = useUpdateNodeInternals()
|
||||
|
||||
useEffect(() => {
|
||||
if (error_strategy === ErrorHandleTypeEnum.failBranch) updateNodeInternals(id)
|
||||
}, [error_strategy, id, updateNodeInternals])
|
||||
|
||||
if (!error_strategy) return null
|
||||
|
||||
return (
|
||||
<div className="relative px-3 pt-1 pb-2">
|
||||
<div
|
||||
className={cn(
|
||||
'relative flex h-6 items-center justify-between rounded-md bg-workflow-block-parma-bg px-1.25',
|
||||
data._runningStatus === NodeRunningStatus.Exception &&
|
||||
'border-[0.5px] border-components-badge-status-light-warning-halo bg-state-warning-hover',
|
||||
)}
|
||||
>
|
||||
<div className="system-xs-medium-uppercase text-text-tertiary">
|
||||
{t(($) => $['common.onFailure'], { ns: 'workflow' })}
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
'system-xs-medium text-text-secondary',
|
||||
data._runningStatus === NodeRunningStatus.Exception && 'text-text-warning',
|
||||
)}
|
||||
>
|
||||
{error_strategy === ErrorHandleTypeEnum.defaultValue &&
|
||||
t(($) => $['nodes.common.errorHandle.defaultValue.output'], { ns: 'workflow' })}
|
||||
{error_strategy === ErrorHandleTypeEnum.failBranch &&
|
||||
t(($) => $['nodes.common.errorHandle.failBranch.title'], { ns: 'workflow' })}
|
||||
</div>
|
||||
{error_strategy === ErrorHandleTypeEnum.failBranch && (
|
||||
<NodeSourceHandle
|
||||
id={id}
|
||||
data={data}
|
||||
handleId={ErrorHandleTypeEnum.failBranch}
|
||||
handleClassName="top-1/2! -right-[21px]! -translate-y-1/2! after:bg-workflow-link-line-failure-button-bg!"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ErrorHandleOnNode
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import type { Node } from '@/app/components/workflow/types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { memo } from 'react'
|
||||
import { Handle, Position } from 'reactflow'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
|
||||
type NodeHandleProps = {
|
||||
handleId: string
|
||||
handleClassName?: string
|
||||
} & Pick<Node, 'id' | 'data'>
|
||||
|
||||
export const NodeTargetHandle = memo(({ data, handleId, handleClassName }: NodeHandleProps) => {
|
||||
const connected = data._connectedTargetHandleIds?.includes(handleId)
|
||||
|
||||
return (
|
||||
<>
|
||||
<Handle
|
||||
id={handleId}
|
||||
type="target"
|
||||
position={Position.Left}
|
||||
className={cn(
|
||||
'z-1 size-4! rounded-none! border-none! bg-transparent! outline-hidden!',
|
||||
'after:absolute after:top-1 after:left-1.5 after:h-2 after:w-0.5 after:bg-workflow-link-line-handle',
|
||||
'transition-all hover:scale-125',
|
||||
!connected && 'after:opacity-0',
|
||||
(data.type === BlockEnum.Start ||
|
||||
data.type === BlockEnum.TriggerWebhook ||
|
||||
data.type === BlockEnum.TriggerSchedule ||
|
||||
data.type === BlockEnum.TriggerPlugin) &&
|
||||
'opacity-0',
|
||||
handleClassName,
|
||||
)}
|
||||
></Handle>
|
||||
</>
|
||||
)
|
||||
})
|
||||
NodeTargetHandle.displayName = 'NodeTargetHandle'
|
||||
|
||||
export const NodeSourceHandle = memo(({ data, handleId, handleClassName }: NodeHandleProps) => {
|
||||
const connected = data._connectedSourceHandleIds?.includes(handleId)
|
||||
|
||||
return (
|
||||
<Handle
|
||||
id={handleId}
|
||||
type="source"
|
||||
position={Position.Right}
|
||||
className={cn(
|
||||
'group/handle z-1 size-4! rounded-none! border-none! bg-transparent! outline-hidden!',
|
||||
'after:absolute after:top-1 after:right-1.5 after:h-2 after:w-0.5 after:bg-workflow-link-line-handle',
|
||||
'transition-all hover:scale-125',
|
||||
!connected && 'after:opacity-0',
|
||||
handleClassName,
|
||||
)}
|
||||
></Handle>
|
||||
)
|
||||
})
|
||||
NodeSourceHandle.displayName = 'NodeSourceHandle'
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
import type { AgentV2NodeType } from '@/app/components/workflow/nodes/agent-v2/types'
|
||||
import { render } from '@testing-library/react'
|
||||
import { ReactFlowProvider } from 'reactflow'
|
||||
import { ErrorHandleTypeEnum } from '@/app/components/workflow/nodes/_base/components/error-handle/types'
|
||||
import { UserActionButtonType } from '@/app/components/workflow/nodes/human-input/types'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import CustomNode from '../index'
|
||||
|
||||
vi.mock('react-i18next', async () => {
|
||||
const { createReactI18nextMock } = await import('@/test/i18n-mock')
|
||||
return createReactI18nextMock({
|
||||
'workflow.nodes.agent.outputRoutes.route': 'Route {{index}}',
|
||||
})
|
||||
})
|
||||
|
||||
describe('workflow preview custom node', () => {
|
||||
it('renders the mapped node component inside the shared base card', () => {
|
||||
const props: React.ComponentProps<typeof CustomNode> = {
|
||||
id: 'classifier-1',
|
||||
type: 'custom-node',
|
||||
selected: false,
|
||||
zIndex: 1,
|
||||
isConnectable: true,
|
||||
dragging: false,
|
||||
xPos: 0,
|
||||
yPos: 0,
|
||||
dragHandle: undefined,
|
||||
data: {
|
||||
type: BlockEnum.QuestionClassifier,
|
||||
title: 'Classifier node',
|
||||
desc: '',
|
||||
classes: [{ id: 'class-a', name: 'Billing' }],
|
||||
},
|
||||
}
|
||||
|
||||
const { container, getByText } = render(<CustomNode {...props} />, {
|
||||
wrapper: ReactFlowProvider,
|
||||
})
|
||||
|
||||
expect(getByText('Classifier node')).toBeInTheDocument()
|
||||
expect(container.querySelector('[data-handleid="class-a"]')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders human input output handles from the mapped node component', () => {
|
||||
const props: React.ComponentProps<typeof CustomNode> = {
|
||||
id: 'human-input-1',
|
||||
type: 'custom-node',
|
||||
selected: false,
|
||||
zIndex: 1,
|
||||
isConnectable: true,
|
||||
dragging: false,
|
||||
xPos: 0,
|
||||
yPos: 0,
|
||||
dragHandle: undefined,
|
||||
data: {
|
||||
type: BlockEnum.HumanInput,
|
||||
title: 'Human Input',
|
||||
desc: '',
|
||||
delivery_methods: [],
|
||||
form_content: '',
|
||||
inputs: [],
|
||||
user_actions: [
|
||||
{ id: 'approve', title: 'Approve', button_style: UserActionButtonType.Primary },
|
||||
],
|
||||
timeout: 1,
|
||||
timeout_unit: 'hour',
|
||||
},
|
||||
}
|
||||
|
||||
const { container, getByText } = render(<CustomNode {...props} />, {
|
||||
wrapper: ReactFlowProvider,
|
||||
})
|
||||
|
||||
expect(getByText('Human Input')).toBeInTheDocument()
|
||||
expect(container.querySelector('[data-handleid="approve"]')).toBeInTheDocument()
|
||||
expect(container.querySelector('[data-handleid="__timeout"]')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([BlockEnum.Agent, BlockEnum.AgentV2])(
|
||||
'renders route labels and connections for %s while preserving the failure exit',
|
||||
(type) => {
|
||||
const data: AgentV2NodeType = {
|
||||
type,
|
||||
title: 'Agent',
|
||||
desc: '',
|
||||
agent_node_kind: 'dify_agent',
|
||||
version: '2',
|
||||
error_strategy: ErrorHandleTypeEnum.failBranch,
|
||||
agent_output_routes: {
|
||||
enabled: true,
|
||||
routes: [
|
||||
{ id: 'accepted', name: 'The request is accepted', label: 'Accepted' },
|
||||
{ id: 'rejected', name: 'The request is rejected' },
|
||||
],
|
||||
},
|
||||
}
|
||||
const props: React.ComponentProps<typeof CustomNode> = {
|
||||
id: 'agent-1',
|
||||
type: 'custom-node',
|
||||
selected: false,
|
||||
zIndex: 1,
|
||||
isConnectable: false,
|
||||
dragging: false,
|
||||
xPos: 0,
|
||||
yPos: 0,
|
||||
dragHandle: undefined,
|
||||
data,
|
||||
}
|
||||
const { container, getByText, queryByText, rerender } = render(<CustomNode {...props} />, {
|
||||
wrapper: ReactFlowProvider,
|
||||
})
|
||||
// ReactFlow resolves the saved edges through these source handle IDs.
|
||||
const sourceHandles = () =>
|
||||
Array.from(container.querySelectorAll('.react-flow__handle.source'), (handle) =>
|
||||
handle.getAttribute('data-handleid'),
|
||||
).sort()
|
||||
|
||||
expect(getByText('Accepted')).toBeInTheDocument()
|
||||
expect(getByText('Route 2')).toBeInTheDocument()
|
||||
expect(sourceHandles()).toEqual(['accepted', 'fail-branch', 'rejected'])
|
||||
|
||||
rerender(
|
||||
<CustomNode
|
||||
{...props}
|
||||
data={{ ...data, agent_output_routes: { ...data.agent_output_routes, enabled: false } }}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(queryByText('Accepted')).not.toBeInTheDocument()
|
||||
expect(sourceHandles()).toEqual(['fail-branch', 'source'])
|
||||
},
|
||||
)
|
||||
})
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
import type { NodeProps } from '@/app/components/workflow/types'
|
||||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import InfoPanel from '@/app/components/workflow/nodes/_base/components/info-panel'
|
||||
import { hasAgentV2OutputRoutes } from '@/app/components/workflow/nodes/agent-v2/types'
|
||||
import { NodeSourceHandle } from '../../node-handle'
|
||||
|
||||
const Node = (props: NodeProps) => {
|
||||
const { data } = props
|
||||
const { t } = useTranslation(['workflow'])
|
||||
|
||||
if (!hasAgentV2OutputRoutes(data)) return null
|
||||
|
||||
return (
|
||||
<div className="mb-1 space-y-0.5 px-3 py-1">
|
||||
{data.agent_output_routes?.routes?.map((route, index) => (
|
||||
<div key={route.id} className="relative">
|
||||
<InfoPanel
|
||||
title={
|
||||
route.label?.trim() ||
|
||||
t(($) => $['nodes.agent.outputRoutes.route'], {
|
||||
ns: 'workflow',
|
||||
index: index + 1,
|
||||
})
|
||||
}
|
||||
content=""
|
||||
/>
|
||||
<NodeSourceHandle
|
||||
{...props}
|
||||
handleId={route.id}
|
||||
handleClassName="top-1/2! -translate-y-1/2! -right-[21px]!"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(Node)
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
import type { ReactElement } from 'react'
|
||||
import type { IterationNodeType } from '@/app/components/workflow/nodes/iteration/types'
|
||||
import type { NodeProps } from '@/app/components/workflow/types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
|
||||
import { cloneElement, memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import BlockIcon from '@/app/components/workflow/block-icon'
|
||||
import { hasAgentV2OutputRoutes } from '@/app/components/workflow/nodes/agent-v2/types'
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import { hasErrorHandleNode } from '@/app/components/workflow/utils'
|
||||
import ErrorHandleOnNode from '../error-handle-on-node'
|
||||
import { NodeSourceHandle, NodeTargetHandle } from '../node-handle'
|
||||
|
||||
type NodeChildElement = ReactElement<Partial<NodeProps>>
|
||||
|
||||
type NodeCardProps = NodeProps & {
|
||||
children?: NodeChildElement
|
||||
}
|
||||
|
||||
const BaseCard = ({ id, data, children }: NodeCardProps) => {
|
||||
const { t } = useTranslation(['workflow', 'workflowLogic'])
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn('flex rounded-2xl border-2 border-transparent')}
|
||||
style={{
|
||||
width:
|
||||
data.type === BlockEnum.Iteration || data.type === BlockEnum.Loop ? data.width : 'auto',
|
||||
height:
|
||||
data.type === BlockEnum.Iteration || data.type === BlockEnum.Loop ? data.height : 'auto',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'group relative pb-1 shadow-xs',
|
||||
'rounded-[15px] border border-transparent',
|
||||
'bg-workflow-block-bg hover:shadow-lg',
|
||||
)}
|
||||
style={{
|
||||
width:
|
||||
data.type === BlockEnum.Iteration || data.type === BlockEnum.Loop
|
||||
? data.width
|
||||
: '240px',
|
||||
height:
|
||||
data.type === BlockEnum.Iteration || data.type === BlockEnum.Loop
|
||||
? data.height
|
||||
: 'auto',
|
||||
}}
|
||||
>
|
||||
<div className={cn('flex items-center rounded-t-2xl px-3 pt-3 pb-2')}>
|
||||
<NodeTargetHandle
|
||||
id={id}
|
||||
data={data}
|
||||
handleClassName="top-4! -left-[9px]! translate-y-0!"
|
||||
handleId="target"
|
||||
/>
|
||||
{data.type !== BlockEnum.IfElse &&
|
||||
data.type !== BlockEnum.QuestionClassifier &&
|
||||
data.type !== BlockEnum.HumanInput &&
|
||||
!hasAgentV2OutputRoutes(data) && (
|
||||
<NodeSourceHandle
|
||||
id={id}
|
||||
data={data}
|
||||
handleClassName="top-4! -right-[9px]! translate-y-0!"
|
||||
handleId="source"
|
||||
/>
|
||||
)}
|
||||
<BlockIcon className="mr-2 shrink-0" type={data.type} size="md" />
|
||||
<div
|
||||
title={data.title}
|
||||
className="mr-1 flex grow items-center truncate system-sm-semibold-uppercase text-text-primary"
|
||||
>
|
||||
<div>{data.title}</div>
|
||||
{data.type === BlockEnum.Iteration && (data as IterationNodeType).is_parallel && (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
openOnHover
|
||||
aria-label={t(($) => $['nodes.iteration.parallelModeEnableTitle'], {
|
||||
ns: 'workflow',
|
||||
})}
|
||||
className="ml-1 flex items-center justify-center rounded-[5px] border border-text-warning bg-transparent px-1.25 py-0.75 system-2xs-medium-uppercase text-text-warning"
|
||||
>
|
||||
{t(($) => $['nodes.iteration.parallelModeUpper'], { ns: 'workflow' })}
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-45 px-3 py-2 system-xs-regular text-text-tertiary">
|
||||
<div className="font-extrabold">
|
||||
{t(($) => $['nodes.iteration.parallelModeEnableTitle'], {
|
||||
ns: 'workflow',
|
||||
})}
|
||||
</div>
|
||||
{t(($) => $['nodes.iteration.parallelModeEnableDesc'], { ns: 'workflow' })}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{data.type !== BlockEnum.Iteration &&
|
||||
data.type !== BlockEnum.Loop &&
|
||||
children &&
|
||||
cloneElement(children, { id, data })}
|
||||
{(data.type === BlockEnum.Iteration || data.type === BlockEnum.Loop) && children && (
|
||||
<div className="h-[calc(100%-42px)] w-full grow pr-1 pb-1 pl-1">
|
||||
{cloneElement(children, { id, data })}
|
||||
</div>
|
||||
)}
|
||||
{hasErrorHandleNode(data.type) && <ErrorHandleOnNode id={id} data={data} />}
|
||||
{data.desc && data.type !== BlockEnum.Iteration && data.type !== BlockEnum.Loop && (
|
||||
<div className="px-3 pt-1 pb-2 system-xs-regular wrap-break-word whitespace-pre-line text-text-tertiary">
|
||||
{data.desc}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(BaseCard)
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { BlockEnum } from '@/app/components/workflow/types'
|
||||
import AgentNode from './agent-v2/node'
|
||||
import HumanInputNode from './human-input/node'
|
||||
import IfElseNode from './if-else/node'
|
||||
import IterationNode from './iteration/node'
|
||||
import LoopNode from './loop/node'
|
||||
import QuestionClassifierNode from './question-classifier/node'
|
||||
|
||||
export const NodeComponentMap: Record<string, any> = {
|
||||
[BlockEnum.Agent]: AgentNode,
|
||||
[BlockEnum.AgentV2]: AgentNode,
|
||||
[BlockEnum.QuestionClassifier]: QuestionClassifierNode,
|
||||
[BlockEnum.IfElse]: IfElseNode,
|
||||
[BlockEnum.HumanInput]: HumanInputNode,
|
||||
[BlockEnum.Iteration]: IterationNode,
|
||||
[BlockEnum.Loop]: LoopNode,
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import type { NodeProps } from 'reactflow'
|
||||
import type { HumanInputNodeType } from '@/app/components/workflow/nodes/human-input/types'
|
||||
import { memo } from 'react'
|
||||
import { NodeSourceHandle } from '../../node-handle'
|
||||
|
||||
function HumanInputNode(props: NodeProps<HumanInputNodeType>) {
|
||||
const { data } = props
|
||||
|
||||
return (
|
||||
<div className="space-y-0.5 px-3 py-1">
|
||||
{data.user_actions.map((userAction) => (
|
||||
<div key={userAction.id} className="relative flex h-6 flex-row-reverse items-center px-1">
|
||||
<span className="truncate system-xs-semibold-uppercase text-text-secondary">
|
||||
{userAction.id}
|
||||
</span>
|
||||
<NodeSourceHandle
|
||||
{...props}
|
||||
handleId={userAction.id}
|
||||
handleClassName="top-1/2! -right-[21px]! -translate-y-1/2!"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<div className="relative flex h-6 flex-row-reverse items-center px-1">
|
||||
<span className="truncate system-xs-semibold-uppercase text-text-secondary">Timeout</span>
|
||||
<NodeSourceHandle
|
||||
{...props}
|
||||
handleId="__timeout"
|
||||
handleClassName="top-1/2! -right-[21px]! -translate-y-1/2!"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(HumanInputNode)
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
import type { FC } from 'react'
|
||||
import type { NodeProps } from 'reactflow'
|
||||
import type { Condition, IfElseNodeType } from '@/app/components/workflow/nodes/if-else/types'
|
||||
import * as React from 'react'
|
||||
import { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import ConditionFilesListValue from '@/app/components/workflow/nodes/if-else/components/condition-files-list-value'
|
||||
import ConditionValue from '@/app/components/workflow/nodes/if-else/components/condition-value'
|
||||
import { isEmptyRelatedOperator } from '@/app/components/workflow/nodes/if-else/utils'
|
||||
import { NodeSourceHandle } from '../../node-handle'
|
||||
|
||||
const i18nPrefix = 'nodes.ifElse'
|
||||
|
||||
const IfElseNode: FC<NodeProps<IfElseNodeType>> = (props) => {
|
||||
const { data } = props
|
||||
const { t } = useTranslation(['workflowLogic'])
|
||||
const { cases } = data
|
||||
const casesLength = cases.length
|
||||
const checkIsConditionSet = useCallback((condition: Condition) => {
|
||||
if (!condition.variable_selector || condition.variable_selector.length === 0) return false
|
||||
|
||||
if (condition.sub_variable_condition) {
|
||||
const isSet = condition.sub_variable_condition.conditions.every((c) => {
|
||||
if (!c.comparison_operator) return false
|
||||
|
||||
if (isEmptyRelatedOperator(c.comparison_operator!)) return true
|
||||
|
||||
return !!c.value
|
||||
})
|
||||
return isSet
|
||||
} else {
|
||||
if (isEmptyRelatedOperator(condition.comparison_operator!)) return true
|
||||
|
||||
return !!condition.value
|
||||
}
|
||||
}, [])
|
||||
const conditionNotSet = (
|
||||
<div className="flex h-6 items-center space-x-1 rounded-md bg-workflow-block-parma-bg px-1 text-xs font-normal text-text-secondary">
|
||||
{t(($) => $[`${i18nPrefix}.conditionNotSetup`], { ns: 'workflowLogic' })}
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="px-3">
|
||||
{cases.map((caseItem, index) => (
|
||||
<div key={caseItem.case_id}>
|
||||
<div className="relative flex h-6 items-center px-1">
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<div className="text-2xs font-semibold text-text-tertiary">
|
||||
{casesLength > 1 && `CASE ${index + 1}`}
|
||||
</div>
|
||||
<div className="text-[12px] font-semibold text-text-secondary">
|
||||
{index === 0 ? 'IF' : 'ELIF'}
|
||||
</div>
|
||||
</div>
|
||||
<NodeSourceHandle
|
||||
{...props}
|
||||
handleId={caseItem.case_id}
|
||||
handleClassName="top-1/2! -right-[21px]! -translate-y-1/2!"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-0.5">
|
||||
{caseItem.conditions.map((condition, i) => (
|
||||
<div key={condition.id} className="relative">
|
||||
{checkIsConditionSet(condition) ? (
|
||||
!isEmptyRelatedOperator(condition.comparison_operator!) &&
|
||||
condition.sub_variable_condition ? (
|
||||
<ConditionFilesListValue condition={condition} />
|
||||
) : (
|
||||
<ConditionValue
|
||||
variableSelector={condition.variable_selector!}
|
||||
operator={condition.comparison_operator!}
|
||||
value={condition.value}
|
||||
/>
|
||||
)
|
||||
) : (
|
||||
conditionNotSet
|
||||
)}
|
||||
{i !== caseItem.conditions.length - 1 && (
|
||||
<div className="absolute right-1 -bottom-2.5 z-10 text-2xs leading-4 font-medium text-text-accent uppercase">
|
||||
{t(($) => $[`${i18nPrefix}.${caseItem.logical_operator}`], {
|
||||
ns: 'workflowLogic',
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<div className="relative flex h-6 items-center px-1">
|
||||
<div className="w-full text-right text-xs font-semibold text-text-secondary">ELSE</div>
|
||||
<NodeSourceHandle
|
||||
{...props}
|
||||
handleId="false"
|
||||
handleClassName="top-1/2! -right-[21px]! -translate-y-1/2!"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(IfElseNode)
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import type { NodeProps } from 'reactflow'
|
||||
import BaseNode from './base'
|
||||
import { NodeComponentMap } from './constants'
|
||||
|
||||
const CustomNode = (props: NodeProps) => {
|
||||
const nodeData = props.data
|
||||
const NodeComponent = NodeComponentMap[nodeData.type]
|
||||
|
||||
return (
|
||||
<>
|
||||
<BaseNode {...props}>{NodeComponent && <NodeComponent />}</BaseNode>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default CustomNode
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import type { NodeProps } from 'reactflow'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import { RiHome5Fill } from '@remixicon/react'
|
||||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { NodeSourceHandle } from '../../node-handle'
|
||||
|
||||
const IterationStartNode = ({ id, data }: NodeProps) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
|
||||
return (
|
||||
<div className="nodrag group mt-1 flex size-11 items-center justify-center rounded-2xl border border-workflow-block-border bg-workflow-block-bg shadow-xs">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
aria-label={t(($) => $['blocks.iteration-start'], { ns: 'workflow' })}
|
||||
className="flex h-6 w-6 items-center justify-center rounded-full border-[0.5px] border-components-panel-border-subtle bg-util-colors-blue-brand-blue-brand-500 p-0"
|
||||
>
|
||||
<RiHome5Fill className="size-3 text-text-primary-on-surface" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t(($) => $['blocks.iteration-start'], { ns: 'workflow' })}</TooltipContent>
|
||||
</Tooltip>
|
||||
<NodeSourceHandle
|
||||
id={id}
|
||||
data={data}
|
||||
handleClassName="top-1/2! -right-[9px]! -translate-y-1/2!"
|
||||
handleId="source"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(IterationStartNode)
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import type { FC } from 'react'
|
||||
import type { IterationNodeType } from '@/app/components/workflow/nodes/iteration/types'
|
||||
import type { NodeProps } from '@/app/components/workflow/types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { memo } from 'react'
|
||||
import { Background, useViewport } from 'reactflow'
|
||||
|
||||
const Node: FC<NodeProps<IterationNodeType>> = ({ id }) => {
|
||||
const { zoom } = useViewport()
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'relative h-full min-h-22.5 w-full min-w-60 rounded-2xl bg-workflow-canvas-workflow-bg',
|
||||
)}
|
||||
>
|
||||
<Background
|
||||
id={`iteration-background-${id}`}
|
||||
className="z-0! rounded-2xl"
|
||||
gap={[14 / zoom, 14 / zoom]}
|
||||
size={2 / zoom}
|
||||
color="var(--color-workflow-canvas-workflow-dot-color)"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(Node)
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import type { NodeProps } from 'reactflow'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import { RiHome5Fill } from '@remixicon/react'
|
||||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { NodeSourceHandle } from '../../node-handle'
|
||||
|
||||
const LoopStartNode = ({ id, data }: NodeProps) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
|
||||
return (
|
||||
<div className="nodrag group mt-1 flex size-11 items-center justify-center rounded-2xl border border-workflow-block-border bg-workflow-block-bg">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
aria-label={t(($) => $['blocks.loop-start'], { ns: 'workflow' })}
|
||||
className="flex h-6 w-6 items-center justify-center rounded-full border-[0.5px] border-components-panel-border-subtle bg-util-colors-blue-brand-blue-brand-500 p-0"
|
||||
>
|
||||
<RiHome5Fill className="size-3 text-text-primary-on-surface" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t(($) => $['blocks.loop-start'], { ns: 'workflow' })}</TooltipContent>
|
||||
</Tooltip>
|
||||
<NodeSourceHandle
|
||||
id={id}
|
||||
data={data}
|
||||
handleClassName="top-1/2! -right-[9px]! -translate-y-1/2!"
|
||||
handleId="source"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(LoopStartNode)
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
import type { Node } from '@/app/components/workflow/types'
|
||||
import { act } from '@testing-library/react'
|
||||
import { useStoreApi } from 'reactflow'
|
||||
import { createLoopNode, createNode } from '@/app/components/workflow/__tests__/fixtures'
|
||||
import { renderWorkflowCanvasHook } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import { LOOP_PADDING } from '@/app/components/workflow/constants'
|
||||
import { useNodeLoopInteractions } from '../hooks'
|
||||
|
||||
const renderInteractions = (nodes: Node[]) =>
|
||||
renderWorkflowCanvasHook(
|
||||
() => ({ interactions: useNodeLoopInteractions(), reactFlowStore: useStoreApi() }),
|
||||
{ nodes },
|
||||
)
|
||||
|
||||
const getNode = (reactFlowStore: ReturnType<typeof useStoreApi>, nodeId: string) =>
|
||||
reactFlowStore
|
||||
.getState()
|
||||
.getNodes()
|
||||
.find((node) => node.id === nodeId)!
|
||||
|
||||
describe('workflow preview loop interactions', () => {
|
||||
it('uses the independently rightmost and bottommost children and leaves unrelated nodes unchanged', () => {
|
||||
const unrelatedNode = createNode({
|
||||
id: 'unrelated',
|
||||
position: { x: 1_000, y: 1_000 },
|
||||
width: 500,
|
||||
height: 500,
|
||||
data: { title: 'Outside the loop' },
|
||||
})
|
||||
const { result } = renderInteractions([
|
||||
createLoopNode({
|
||||
id: 'loop-node',
|
||||
width: 120,
|
||||
height: 80,
|
||||
data: { width: 120, height: 80 },
|
||||
}),
|
||||
createNode({
|
||||
id: 'rightmost-child',
|
||||
parentId: 'loop-node',
|
||||
position: { x: 200, y: 10 },
|
||||
width: 30,
|
||||
height: 20,
|
||||
}),
|
||||
createNode({
|
||||
id: 'bottommost-child',
|
||||
parentId: 'loop-node',
|
||||
position: { x: 10, y: 160 },
|
||||
width: 20,
|
||||
height: 50,
|
||||
}),
|
||||
unrelatedNode,
|
||||
])
|
||||
|
||||
act(() => result.current.interactions.handleNodeLoopRerender('loop-node'))
|
||||
|
||||
const loopNode = getNode(result.current.reactFlowStore, 'loop-node')
|
||||
const expectedWidth = 200 + 30 + LOOP_PADDING.right
|
||||
const expectedHeight = 160 + 50 + LOOP_PADDING.bottom
|
||||
expect(loopNode).toMatchObject({ width: expectedWidth, height: expectedHeight })
|
||||
expect(loopNode.data).toMatchObject({ width: expectedWidth, height: expectedHeight })
|
||||
expect(getNode(result.current.reactFlowStore, 'unrelated')).toMatchObject(unrelatedNode)
|
||||
})
|
||||
|
||||
it.each([
|
||||
{
|
||||
dimension: 'width only',
|
||||
loopSize: { width: 100, height: 300 },
|
||||
child: { position: { x: 100, y: 10 }, width: 50, height: 20 },
|
||||
expected: { width: 150 + LOOP_PADDING.right, height: 300 },
|
||||
},
|
||||
{
|
||||
dimension: 'height only',
|
||||
loopSize: { width: 300, height: 100 },
|
||||
child: { position: { x: 10, y: 100 }, width: 20, height: 50 },
|
||||
expected: { width: 300, height: 150 + LOOP_PADDING.bottom },
|
||||
},
|
||||
])('expands $dimension without changing the other dimension', ({ loopSize, child, expected }) => {
|
||||
const { result } = renderInteractions([
|
||||
createLoopNode({ id: 'loop-node', ...loopSize, data: loopSize }),
|
||||
createNode({ id: 'child-node', parentId: 'loop-node', ...child }),
|
||||
])
|
||||
|
||||
act(() => result.current.interactions.handleNodeLoopRerender('loop-node'))
|
||||
|
||||
const loopNode = getNode(result.current.reactFlowStore, 'loop-node')
|
||||
expect(loopNode).toMatchObject(expected)
|
||||
expect(loopNode.data).toMatchObject(expected)
|
||||
})
|
||||
|
||||
it.each([
|
||||
{
|
||||
scenario: 'children fit',
|
||||
children: [
|
||||
createNode({
|
||||
id: 'child-node',
|
||||
parentId: 'loop-node',
|
||||
position: { x: 20, y: 20 },
|
||||
width: 40,
|
||||
height: 40,
|
||||
}),
|
||||
],
|
||||
},
|
||||
{ scenario: 'there are no children', children: [] },
|
||||
])('does not shrink the loop when $scenario', ({ children }) => {
|
||||
const loopNode = createLoopNode({
|
||||
id: 'loop-node',
|
||||
width: 300,
|
||||
height: 240,
|
||||
data: { width: 300, height: 240 },
|
||||
})
|
||||
const { result } = renderInteractions([loopNode, ...children])
|
||||
|
||||
act(() => result.current.interactions.handleNodeLoopRerender('loop-node'))
|
||||
|
||||
expect(getNode(result.current.reactFlowStore, 'loop-node')).toMatchObject({
|
||||
width: 300,
|
||||
height: 240,
|
||||
data: { width: 300, height: 240 },
|
||||
})
|
||||
})
|
||||
})
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import type { Node } from '@/app/components/workflow/types'
|
||||
import { produce } from 'immer'
|
||||
import { useCallback } from 'react'
|
||||
import { useStoreApi } from 'reactflow'
|
||||
import { LOOP_PADDING } from '@/app/components/workflow/constants'
|
||||
|
||||
export const useNodeLoopInteractions = () => {
|
||||
const store = useStoreApi()
|
||||
|
||||
const handleNodeLoopRerender = useCallback(
|
||||
(nodeId: string) => {
|
||||
const { getNodes, setNodes } = store.getState()
|
||||
|
||||
const nodes = getNodes()
|
||||
const currentNode = nodes.find((n) => n.id === nodeId)!
|
||||
const childrenNodes = nodes.filter((n) => n.parentId === nodeId)
|
||||
let rightNode: Node
|
||||
let bottomNode: Node
|
||||
|
||||
childrenNodes.forEach((n) => {
|
||||
if (rightNode) {
|
||||
if (n.position.x + n.width! > rightNode.position.x + rightNode.width!) rightNode = n
|
||||
} else {
|
||||
rightNode = n
|
||||
}
|
||||
if (bottomNode) {
|
||||
if (n.position.y + n.height! > bottomNode.position.y + bottomNode.height!) bottomNode = n
|
||||
} else {
|
||||
bottomNode = n
|
||||
}
|
||||
})
|
||||
|
||||
const widthShouldExtend =
|
||||
rightNode! && currentNode.width! < rightNode.position.x + rightNode.width!
|
||||
const heightShouldExtend =
|
||||
bottomNode! && currentNode.height! < bottomNode.position.y + bottomNode.height!
|
||||
|
||||
if (widthShouldExtend || heightShouldExtend) {
|
||||
const newNodes = produce(nodes, (draft) => {
|
||||
draft.forEach((n) => {
|
||||
if (n.id === nodeId) {
|
||||
if (widthShouldExtend) {
|
||||
n.data.width = rightNode.position.x + rightNode.width! + LOOP_PADDING.right
|
||||
n.width = rightNode.position.x + rightNode.width! + LOOP_PADDING.right
|
||||
}
|
||||
if (heightShouldExtend) {
|
||||
n.data.height = bottomNode.position.y + bottomNode.height! + LOOP_PADDING.bottom
|
||||
n.height = bottomNode.position.y + bottomNode.height! + LOOP_PADDING.bottom
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
setNodes(newNodes)
|
||||
}
|
||||
},
|
||||
[store],
|
||||
)
|
||||
|
||||
return {
|
||||
handleNodeLoopRerender,
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
import type { FC } from 'react'
|
||||
import type { LoopNodeType } from '@/app/components/workflow/nodes/loop/types'
|
||||
import type { NodeProps } from '@/app/components/workflow/types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { memo, useEffect } from 'react'
|
||||
import { Background, useNodesInitialized, useViewport } from 'reactflow'
|
||||
import { useNodeLoopInteractions } from './hooks'
|
||||
|
||||
const Node: FC<NodeProps<LoopNodeType>> = ({ id, data: _data }) => {
|
||||
const { zoom } = useViewport()
|
||||
const nodesInitialized = useNodesInitialized()
|
||||
const { handleNodeLoopRerender } = useNodeLoopInteractions()
|
||||
|
||||
useEffect(() => {
|
||||
if (nodesInitialized) handleNodeLoopRerender(id)
|
||||
}, [nodesInitialized, id, handleNodeLoopRerender])
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'relative h-full min-h-22.5 w-full min-w-60 rounded-2xl bg-workflow-canvas-workflow-bg',
|
||||
)}
|
||||
// style={{
|
||||
// width: data.width || 'auto',
|
||||
// }}
|
||||
>
|
||||
<Background
|
||||
id={`loop-background-${id}`}
|
||||
className="z-0! rounded-2xl"
|
||||
gap={[14 / zoom, 14 / zoom]}
|
||||
size={2 / zoom}
|
||||
color="var(--color-workflow-canvas-workflow-dot-color)"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(Node)
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import type { FC } from 'react'
|
||||
import type { NodeProps } from 'reactflow'
|
||||
import type { QuestionClassifierNodeType } from '@/app/components/workflow/nodes/question-classifier/types'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { getDisplayClassLabel } from '@/app/components/workflow/nodes/_base/components/branch-list/class-label-utils'
|
||||
import InfoPanel from '@/app/components/workflow/nodes/_base/components/info-panel'
|
||||
import { NodeSourceHandle } from '../../node-handle'
|
||||
|
||||
const Node: FC<NodeProps<QuestionClassifierNodeType>> = (props) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const { data } = props
|
||||
const topics = data.classes
|
||||
|
||||
return (
|
||||
<div className="mb-1 px-3 py-1">
|
||||
{!!topics.length && (
|
||||
<div className="mt-2 space-y-0.5">
|
||||
{topics.map((topic, index) => (
|
||||
<div key={index} className="relative">
|
||||
<InfoPanel title={getDisplayClassLabel(topic.label, index + 1, t)} content="" />
|
||||
<NodeSourceHandle
|
||||
{...props}
|
||||
handleId={topic.id}
|
||||
handleClassName="top-1/2! -translate-y-1/2! -right-[21px]!"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Node)
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import type { NodeProps } from 'reactflow'
|
||||
import type { NoteNodeType } from '@/app/components/workflow/note-node/types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { memo, useRef } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { THEME_MAP } from '@/app/components/workflow/note-node/constants'
|
||||
import {
|
||||
NoteEditor,
|
||||
NoteEditorContextProvider,
|
||||
} from '@/app/components/workflow/note-node/note-editor'
|
||||
|
||||
const NoteNode = ({ data }: NodeProps<NoteNodeType>) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const ref = useRef<HTMLDivElement | null>(null)
|
||||
const theme = data.theme
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'relative flex flex-col rounded-md border shadow-xs hover:shadow-md',
|
||||
THEME_MAP[theme]!.bg,
|
||||
data.selected ? THEME_MAP[theme]!.border : 'border-black/5',
|
||||
)}
|
||||
style={{
|
||||
width: data.width,
|
||||
height: data.height,
|
||||
}}
|
||||
ref={ref}
|
||||
>
|
||||
<NoteEditorContextProvider value={data.text} editable={false}>
|
||||
<>
|
||||
<div
|
||||
className={cn('h-2 shrink-0 rounded-t-md opacity-50', THEME_MAP[theme]!.title)}
|
||||
></div>
|
||||
<div className="grow overflow-y-auto px-3 py-2.5">
|
||||
<div className={cn(data.selected && 'nodrag nopan nowheel cursor-text')}>
|
||||
<NoteEditor
|
||||
containerElement={ref.current}
|
||||
placeholder={t(($) => $['nodes.note.editor.placeholder'], { ns: 'workflow' })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{data.showAuthor && (
|
||||
<div className="p-3 pt-0 text-xs text-text-tertiary">{data.author}</div>
|
||||
)}
|
||||
</>
|
||||
</NoteEditorContextProvider>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(NoteNode)
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
import type { FC } from 'react'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import {
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuPopup,
|
||||
MenuPortal,
|
||||
MenuPositioner,
|
||||
MenuSeparator,
|
||||
MenuTrigger,
|
||||
} from '@langgenius/dify-ui/menu'
|
||||
import { Fragment, memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useReactFlow, useViewport } from 'reactflow'
|
||||
import TipPopup from '@/app/components/workflow/operator/tip-popup'
|
||||
import { ShortcutKbd } from '@/app/components/workflow/shortcuts/shortcut-kbd'
|
||||
|
||||
const ZoomType = {
|
||||
zoomToFit: 'zoomToFit',
|
||||
zoomTo25: 'zoomTo25',
|
||||
zoomTo50: 'zoomTo50',
|
||||
zoomTo75: 'zoomTo75',
|
||||
zoomTo100: 'zoomTo100',
|
||||
zoomTo200: 'zoomTo200',
|
||||
} as const
|
||||
|
||||
type ZoomType = (typeof ZoomType)[keyof typeof ZoomType]
|
||||
|
||||
const ZoomInOut: FC = () => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const { zoomIn, zoomOut, zoomTo, fitView } = useReactFlow()
|
||||
const { zoom } = useViewport()
|
||||
|
||||
const zoomOptions = [
|
||||
[
|
||||
{
|
||||
key: ZoomType.zoomTo200,
|
||||
text: '200%',
|
||||
},
|
||||
{
|
||||
key: ZoomType.zoomTo100,
|
||||
text: '100%',
|
||||
},
|
||||
{
|
||||
key: ZoomType.zoomTo75,
|
||||
text: '75%',
|
||||
},
|
||||
{
|
||||
key: ZoomType.zoomTo50,
|
||||
text: '50%',
|
||||
},
|
||||
{
|
||||
key: ZoomType.zoomTo25,
|
||||
text: '25%',
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
key: ZoomType.zoomToFit,
|
||||
text: t(($) => $['operator.zoomToFit'], { ns: 'workflow' }),
|
||||
},
|
||||
],
|
||||
]
|
||||
|
||||
const handleZoom = (type: ZoomType) => {
|
||||
if (type === ZoomType.zoomToFit) fitView()
|
||||
|
||||
if (type === ZoomType.zoomTo25) zoomTo(0.25)
|
||||
|
||||
if (type === ZoomType.zoomTo50) zoomTo(0.5)
|
||||
|
||||
if (type === ZoomType.zoomTo75) zoomTo(0.75)
|
||||
|
||||
if (type === ZoomType.zoomTo100) zoomTo(1)
|
||||
|
||||
if (type === ZoomType.zoomTo200) zoomTo(2)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'h-9 cursor-pointer rounded-lg border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg',
|
||||
'p-0.5 text-[13px] shadow-lg backdrop-blur-[5px]',
|
||||
'hover:bg-state-base-hover',
|
||||
)}
|
||||
>
|
||||
<div className="flex h-8 w-24.5 items-center justify-between rounded-lg">
|
||||
<TipPopup
|
||||
title={t(($) => $['operator.zoomOut'], { ns: 'workflow' })}
|
||||
shortcut="workflow.zoom-out"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t(($) => $['operator.zoomOut'], { ns: 'workflow' })}
|
||||
disabled={zoom <= 0.25}
|
||||
className={`flex size-8 items-center justify-center rounded-lg ${zoom <= 0.25 ? 'cursor-not-allowed' : 'cursor-pointer hover:bg-black/5'}`}
|
||||
onClick={(e) => {
|
||||
if (zoom <= 0.25) return
|
||||
|
||||
e.stopPropagation()
|
||||
zoomOut()
|
||||
}}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-ri-zoom-out-line size-4 text-text-tertiary hover:text-text-secondary"
|
||||
/>
|
||||
</button>
|
||||
</TipPopup>
|
||||
<Menu>
|
||||
<MenuTrigger className="flex h-8 w-8.5 items-center justify-center rounded-lg system-sm-medium text-text-tertiary hover:bg-black/5 hover:text-text-secondary data-popup-open:bg-black/5 data-popup-open:text-text-secondary">
|
||||
{Number.parseFloat(`${zoom * 100}`).toFixed(0)}%
|
||||
</MenuTrigger>
|
||||
<MenuPortal>
|
||||
<MenuPositioner sideOffset={4} side="top" align="start" alignOffset={-2}>
|
||||
<MenuPopup>
|
||||
<div className="w-36.25 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-[5px]">
|
||||
{zoomOptions.map((options, groupIndex) => (
|
||||
<Fragment key={options[0]!.key}>
|
||||
{groupIndex !== 0 && <MenuSeparator className="my-0" />}
|
||||
<div className="p-1">
|
||||
{options.map((option) => (
|
||||
<MenuItem
|
||||
key={option.key}
|
||||
className="justify-between px-3 py-1.5 system-md-regular text-text-secondary"
|
||||
onClick={() => handleZoom(option.key)}
|
||||
>
|
||||
<span>{option.text}</span>
|
||||
<div className="flex items-center space-x-0.5">
|
||||
{option.key === ZoomType.zoomToFit && (
|
||||
<ShortcutKbd shortcut="workflow.zoom-to-fit" />
|
||||
)}
|
||||
{option.key === ZoomType.zoomTo50 && (
|
||||
<ShortcutKbd shortcut="workflow.zoom-to-50" />
|
||||
)}
|
||||
{option.key === ZoomType.zoomTo100 && (
|
||||
<ShortcutKbd shortcut="workflow.zoom-to-100" />
|
||||
)}
|
||||
</div>
|
||||
</MenuItem>
|
||||
))}
|
||||
</div>
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
</MenuPopup>
|
||||
</MenuPositioner>
|
||||
</MenuPortal>
|
||||
</Menu>
|
||||
<TipPopup
|
||||
title={t(($) => $['operator.zoomIn'], { ns: 'workflow' })}
|
||||
shortcut="workflow.zoom-in"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t(($) => $['operator.zoomIn'], { ns: 'workflow' })}
|
||||
disabled={zoom >= 2}
|
||||
className={`flex size-8 items-center justify-center rounded-lg ${zoom >= 2 ? 'cursor-not-allowed' : 'cursor-pointer hover:bg-black/5'}`}
|
||||
onClick={(e) => {
|
||||
if (zoom >= 2) return
|
||||
|
||||
e.stopPropagation()
|
||||
zoomIn()
|
||||
}}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-ri-zoom-in-line size-4 text-text-tertiary hover:text-text-secondary"
|
||||
/>
|
||||
</button>
|
||||
</TipPopup>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(ZoomInOut)
|
||||
@@ -0,0 +1,128 @@
|
||||
'use client'
|
||||
|
||||
import type { EdgeChange, NodeChange, Viewport } from 'reactflow'
|
||||
import type { Edge, Node } from '@/app/components/workflow/types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { useCallback, useState } from 'react'
|
||||
import ReactFlow, {
|
||||
applyEdgeChanges,
|
||||
applyNodeChanges,
|
||||
Background,
|
||||
MiniMap,
|
||||
ReactFlowProvider,
|
||||
SelectionMode,
|
||||
} from 'reactflow'
|
||||
import { CUSTOM_EDGE, CUSTOM_NODE } from '@/app/components/workflow/constants'
|
||||
import CustomConnectionLine from '@/app/components/workflow/custom-connection-line'
|
||||
import { CUSTOM_ITERATION_START_NODE } from '@/app/components/workflow/nodes/iteration-start/constants'
|
||||
import { CUSTOM_LOOP_START_NODE } from '@/app/components/workflow/nodes/loop-start/constants'
|
||||
import { CUSTOM_NOTE_NODE } from '@/app/components/workflow/note-node/constants'
|
||||
import { CUSTOM_SIMPLE_NODE } from '@/app/components/workflow/simple-node/constants'
|
||||
import { initialEdges, initialNodes } from '@/app/components/workflow/utils/workflow-init'
|
||||
import CustomEdge from './components/custom-edge'
|
||||
import CustomNode from './components/nodes'
|
||||
import IterationStartNode from './components/nodes/iteration-start'
|
||||
import LoopStartNode from './components/nodes/loop-start'
|
||||
import CustomNoteNode from './components/note-node'
|
||||
import ZoomInOut from './components/zoom-in-out'
|
||||
import 'reactflow/dist/style.css'
|
||||
import '../style.css'
|
||||
|
||||
const nodeTypes = {
|
||||
[CUSTOM_NODE]: CustomNode,
|
||||
[CUSTOM_NOTE_NODE]: CustomNoteNode,
|
||||
[CUSTOM_SIMPLE_NODE]: CustomNode,
|
||||
[CUSTOM_ITERATION_START_NODE]: IterationStartNode,
|
||||
[CUSTOM_LOOP_START_NODE]: LoopStartNode,
|
||||
}
|
||||
const edgeTypes = {
|
||||
[CUSTOM_EDGE]: CustomEdge,
|
||||
}
|
||||
|
||||
type WorkflowPreviewProps = {
|
||||
nodes: Node[]
|
||||
edges: Edge[]
|
||||
viewport: Viewport
|
||||
className?: string
|
||||
miniMapToRight?: boolean
|
||||
}
|
||||
const WorkflowPreview = ({
|
||||
nodes,
|
||||
edges,
|
||||
viewport,
|
||||
className,
|
||||
miniMapToRight,
|
||||
}: WorkflowPreviewProps) => {
|
||||
const [nodesData, setNodesData] = useState(() => initialNodes(nodes, edges))
|
||||
const [edgesData, setEdgesData] = useState(() => initialEdges(edges, nodes))
|
||||
|
||||
const onNodesChange = useCallback(
|
||||
(changes: NodeChange[]) => setNodesData((nds) => applyNodeChanges(changes, nds)),
|
||||
[],
|
||||
)
|
||||
const onEdgesChange = useCallback(
|
||||
(changes: EdgeChange[]) => setEdgesData((eds) => applyEdgeChanges(changes, eds)),
|
||||
[],
|
||||
)
|
||||
|
||||
return (
|
||||
<div id="workflow-container" className={cn('relative size-full', className)}>
|
||||
<>
|
||||
<MiniMap
|
||||
pannable
|
||||
zoomable
|
||||
style={{
|
||||
width: 102,
|
||||
height: 72,
|
||||
}}
|
||||
maskColor="var(--color-workflow-minimap-bg)"
|
||||
className={cn(
|
||||
'absolute! bottom-14! z-9 m-0! h-18! w-25.5! rounded-lg! border-[0.5px]! border-divider-subtle! bg-background-default-subtle! shadow-md! shadow-shadow-shadow-5!',
|
||||
miniMapToRight ? 'right-4!' : 'left-4!',
|
||||
)}
|
||||
/>
|
||||
<div className="absolute bottom-4 left-4 z-9 mt-1 flex items-center gap-2">
|
||||
<ZoomInOut />
|
||||
</div>
|
||||
</>
|
||||
<ReactFlow
|
||||
nodeTypes={nodeTypes}
|
||||
edgeTypes={edgeTypes}
|
||||
nodes={nodesData}
|
||||
onNodesChange={onNodesChange}
|
||||
edges={edgesData}
|
||||
onEdgesChange={onEdgesChange}
|
||||
connectionLineComponent={CustomConnectionLine}
|
||||
defaultViewport={viewport}
|
||||
fitView
|
||||
multiSelectionKeyCode={null}
|
||||
deleteKeyCode={null}
|
||||
nodesDraggable={false}
|
||||
nodesConnectable={false}
|
||||
nodesFocusable={false}
|
||||
edgesFocusable={false}
|
||||
panOnScroll={false}
|
||||
selectionKeyCode={null}
|
||||
selectionMode={SelectionMode.Partial}
|
||||
minZoom={0.25}
|
||||
>
|
||||
<Background
|
||||
gap={[14, 14]}
|
||||
size={2}
|
||||
className="bg-workflow-canvas-workflow-bg"
|
||||
color="var(--color-workflow-canvas-workflow-dot-color)"
|
||||
/>
|
||||
</ReactFlow>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const WorkflowPreviewWrapper = (props: WorkflowPreviewProps) => {
|
||||
return (
|
||||
<ReactFlowProvider>
|
||||
<WorkflowPreview {...props} />
|
||||
</ReactFlowProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export default WorkflowPreviewWrapper
|
||||
Reference in new issue
Block a user