refactor(web): 优化流程节点的定义和实现

This commit is contained in:
v-zhangjc9
2025-07-10 12:08:13 +08:00
parent 898e20d5d7
commit 5e763637da
10 changed files with 467 additions and 513 deletions

View File

@@ -1,23 +1,12 @@
import {PlusCircleFilled, RollbackOutlined, SaveFilled} from '@ant-design/icons' import {PlusCircleFilled, RollbackOutlined, SaveFilled} from '@ant-design/icons'
import { import {Background, BackgroundVariant, Controls, type Edge, MiniMap, type Node, ReactFlow} from '@xyflow/react'
Background, import {Button, Dropdown, message, Popconfirm, Space} from 'antd'
BackgroundVariant, import {arrToMap, find, isEqual, randomId} from 'licia'
Controls, import {useEffect} from 'react'
type Edge,
MiniMap,
type Node,
type NodeProps,
ReactFlow,
} from '@xyflow/react'
import type {Schema} from 'amis'
import {Button, Drawer, Dropdown, message, Popconfirm, Space} from 'antd'
import {arrToMap, find, isEqual, isNil, randomId} from 'licia'
import {type JSX, type MemoExoticComponent, useEffect, useState} from 'react'
import {useNavigate} from 'react-router' import {useNavigate} from 'react-router'
import styled from 'styled-components' import styled from 'styled-components'
import '@xyflow/react/dist/style.css' import '@xyflow/react/dist/style.css'
import {useShallow} from 'zustand/react/shallow' import {commonInfo} from '../../util/amis.tsx'
import {amisRender, commonInfo, horizontalFormOptions} from '../../util/amis.tsx'
import {checkAddConnection, checkAddNode, checkSave} from './FlowChecker.tsx' import {checkAddConnection, checkAddNode, checkSave} from './FlowChecker.tsx'
import CodeNode from './node/CodeNode.tsx' import CodeNode from './node/CodeNode.tsx'
import KnowledgeNode from './node/KnowledgeNode.tsx' import KnowledgeNode from './node/KnowledgeNode.tsx'
@@ -29,8 +18,6 @@ import {useDataStore} from './store/DataStore.ts'
import {useFlowStore} from './store/FlowStore.ts' import {useFlowStore} from './store/FlowStore.ts'
const FlowableDiv = styled.div` const FlowableDiv = styled.div`
height: 100%;
.react-flow__node.selectable { .react-flow__node.selectable {
&:focus { &:focus {
box-shadow: 0 0 20px 1px #e8e8e8; box-shadow: 0 0 20px 1px #e8e8e8;
@@ -65,6 +52,34 @@ const FlowableDiv = styled.div`
} }
` `
const nodeDefine = [
{
key: 'output-node',
name: '输出',
component: OutputNode,
},
{
key: 'llm-node',
name: '大模型',
component: LlmNode,
},
{
key: 'knowledge-node',
name: '知识库',
component: KnowledgeNode,
},
{
key: 'code-node',
name: '代码执行',
component: CodeNode,
},
{
key: 'switch-node',
name: '条件分支',
component: SwitchNode,
},
]
export type GraphData = { nodes: Node[], edges: Edge[], data: any } export type GraphData = { nodes: Node[], edges: Edge[], data: any }
export type FlowEditorProps = { export type FlowEditorProps = {
@@ -76,47 +91,8 @@ export type FlowEditorProps = {
function FlowEditor(props: FlowEditorProps) { function FlowEditor(props: FlowEditorProps) {
const navigate = useNavigate() const navigate = useNavigate()
const [messageApi, contextHolder] = message.useMessage() const [messageApi, contextHolder] = message.useMessage()
const [nodeDef] = useState<{
key: string,
name: string,
component: MemoExoticComponent<(props: NodeProps) => JSX.Element>
}[]>([
{
key: 'output-node',
name: '输出',
component: OutputNode,
},
{
key: 'llm-node',
name: '大模型',
component: LlmNode,
},
{
key: 'knowledge-node',
name: '知识库',
component: KnowledgeNode,
},
{
key: 'code-node',
name: '代码执行',
component: CodeNode,
},
{
key: 'switch-node',
name: '条件分支',
component: SwitchNode,
},
])
const [open, setOpen] = useState(false)
const {data, setData, getDataById, setDataById} = useDataStore( const {data, setData} = useDataStore()
useShallow(state => ({
data: state.data,
setData: state.setData,
getDataById: state.getDataById,
setDataById: state.setDataById,
})),
)
const { const {
nodes, nodes,
addNode, addNode,
@@ -126,106 +102,9 @@ function FlowEditor(props: FlowEditorProps) {
setEdges, setEdges,
onEdgesChange, onEdgesChange,
onConnect, onConnect,
} = useFlowStore( } = useFlowStore()
useShallow(state => ({
nodes: state.nodes,
getNodes: state.getNodes,
addNode: state.addNode,
removeNode: state.removeNode,
setNodes: state.setNodes,
onNodesChange: state.onNodesChange,
edges: state.edges,
getEdges: state.getEdges,
setEdges: state.setEdges,
onEdgesChange: state.onEdgesChange,
onConnect: state.onConnect,
})),
)
const { const {setInputSchema} = useContextStore()
setInputSchema,
} = useContextStore()
const [currentNodeForm, setCurrentNodeForm] = useState<JSX.Element>()
const editNode = (id: string, columnSchema?: Schema[]) => {
if (!isNil(columnSchema)) {
setCurrentNodeForm(
amisRender(
{
type: 'wrapper',
size: 'none',
body: [
{
debug: commonInfo.debug,
type: 'form',
...horizontalFormOptions(),
wrapWithPanel: false,
onEvent: {
submitSucc: {
actions: [
{
actionType: 'custom',
// @ts-ignore
script: (context, action, event) => {
setDataById(
id,
{
...context.props.data,
finished: true,
},
)
setOpen(false)
},
},
],
},
},
body: [
...(columnSchema ?? []),
{
type: 'wrapper',
size: 'none',
className: 'space-x-2 text-right',
body: [
{
type: 'action',
label: '取消',
onEvent: {
click: {
actions: [
{
actionType: 'custom',
// @ts-ignore
script: (context, action, event) => {
setOpen(false)
},
},
],
},
},
},
{
type: 'submit',
label: '保存',
level: 'primary',
},
],
},
],
},
],
},
getDataById(id),
),
)
setOpen(true)
}
}
// 用于透传node操作到主流程
const initialNodeHandlers = {
editNode,
}
useEffect(() => { useEffect(() => {
// language=JSON // language=JSON
@@ -236,10 +115,6 @@ function FlowEditor(props: FlowEditorProps) {
let initialNodeData = props.graphData?.data ?? {} let initialNodeData = props.graphData?.data ?? {}
setData(initialNodeData) setData(initialNodeData)
for (let node of initialNodes) {
node.data = initialNodeHandlers
}
setNodes(initialNodes) setNodes(initialNodes)
setEdges(initialEdges) setEdges(initialEdges)
@@ -247,12 +122,12 @@ function FlowEditor(props: FlowEditorProps) {
}, [props.graphData]) }, [props.graphData])
return ( return (
<FlowableDiv> <FlowableDiv className="h-full w-full">
{contextHolder} {contextHolder}
<Space className="toolbar"> <Space className="toolbar">
<Dropdown <Dropdown
menu={{ menu={{
items: nodeDef.map(def => ({key: def.key, label: def.name})), items: nodeDefine.map(def => ({key: def.key, label: def.name})),
onClick: ({key}) => { onClick: ({key}) => {
try { try {
if (commonInfo.debug) { if (commonInfo.debug) {
@@ -263,7 +138,7 @@ function FlowEditor(props: FlowEditorProps) {
id: randomId(10), id: randomId(10),
type: key, type: key,
position: {x: 100, y: 100}, position: {x: 100, y: 100},
data: initialNodeHandlers, data: {},
}) })
} catch (e) { } catch (e) {
// @ts-ignore // @ts-ignore
@@ -303,16 +178,6 @@ function FlowEditor(props: FlowEditorProps) {
</Button> </Button>
</Space> </Space>
<Drawer
title="节点编辑"
open={open}
closeIcon={false}
maskClosable={false}
destroyOnHidden
size="large"
>
{currentNodeForm}
</Drawer>
<ReactFlow <ReactFlow
nodes={nodes} nodes={nodes}
edges={edges} edges={edges}
@@ -332,8 +197,8 @@ function FlowEditor(props: FlowEditorProps) {
}} }}
// @ts-ignore // @ts-ignore
nodeTypes={arrToMap( nodeTypes={arrToMap(
nodeDef.map(def => def.key), nodeDefine.map(def => def.key),
key => find(nodeDef, def => isEqual(key, def.key))!.component) key => find(nodeDefine, def => isEqual(key, def.key))!.component)
} }
> >
<Controls/> <Controls/>

View File

@@ -1,33 +1,78 @@
import {CopyFilled, DeleteFilled, EditFilled} from '@ant-design/icons' import {CopyFilled, DeleteFilled, EditFilled} from '@ant-design/icons'
import {Handle, type HandleProps, type Node, type NodeProps, Position, useNodeConnections} from '@xyflow/react' import {type Edge, getIncomers, Handle, type Node, type NodeProps, Position} from '@xyflow/react'
import type {Schema} from 'amis' import type {Schema} from 'amis'
import {Button, Card} from 'antd' import {Button, Card, Drawer} from 'antd'
import {has, isEmpty, isEqual, isNil} from 'licia' import {find, has, isEmpty, isEqual, unique} from 'licia'
import {type JSX} from 'react' import {type JSX, useCallback, useState} from 'react'
import styled from 'styled-components' import styled from 'styled-components'
import {horizontalFormOptions} from '../../../util/amis.tsx' import Queue from 'yocto-queue'
import {useContextStore} from '../store/ContextStore.ts' import {amisRender, commonInfo, horizontalFormOptions} from '../../../util/amis.tsx'
import {useDataStore} from '../store/DataStore.ts' import {useDataStore} from '../store/DataStore.ts'
import {useFlowStore} from '../store/FlowStore.ts' import {useFlowStore} from '../store/FlowStore.ts'
export type AmisNodeType = 'normal' | 'start' | 'end' export type InputFormOptions = {
label: string
value: string
}
export function inputsFormColumns(props: ColumnsSchemaProps): Schema[] { export type InputFormOptionsGroup = {
let incomers = props.getAllIncomerNodeById(props.nodeId) group: string,
let groups = [] variables: InputFormOptions[],
for (const incomer of incomers) { }
let data = props.getNodeDataById(incomer.id)
if (has(data, 'outputs')) { const getAllIncomerNodeById: (id: string, nodes: Node[], edges: Edge[]) => string[] = (id, nodes, edges) => {
let outputs = data?.outputs ?? [] let queue = new Queue<Node>()
groups.push({ queue.enqueue(find(nodes, node => isEqual(node.id, id))!)
label: incomer.id, let result: string[] = []
children: Object.keys(outputs).map(key => ({ while (queue.size !== 0) {
value: `${incomer.id}.${key}`, let currentNode = queue.dequeue()!
for (const incomer of getIncomers(currentNode, nodes, edges)) {
result.push(incomer.id)
queue.enqueue(incomer)
}
}
return unique(result, (a, b) => isEqual(a, b))
}
export function inputsFormColumns(
nodeId: string,
inputSchema: Record<string, Record<string, any>>,
nodes: Node[],
edges: Edge[],
data: any,
): Schema[] {
let inputSchemaVariables: InputFormOptions[] = Object.keys(inputSchema).map(key => ({
label: inputSchema[key]?.label ?? '',
value: key,
}))
let incomerIds = getAllIncomerNodeById(nodeId, nodes, edges)
console.log(incomerIds, nodes, edges)
let incomerVariables: InputFormOptionsGroup[] = []
for (const incomerId of incomerIds) {
let nodeData = data[incomerId] ?? {}
if (has(nodeData, 'outputs')) {
let outputs = nodeData?.outputs ?? []
incomerVariables.push({
group: incomerId,
variables: Object.keys(outputs).map(key => ({
value: `${incomerId}.${key}`,
label: key, label: key,
})), })),
}) })
} }
} }
let inputVariables = [
...(isEmpty(inputSchemaVariables) ? [] : [
{
group: '流程入参',
variables: inputSchemaVariables,
},
]),
...incomerVariables,
]
return [ return [
{ {
type: 'input-kvs', type: 'input-kvs',
@@ -48,14 +93,10 @@ export function inputsFormColumns(props: ColumnsSchemaProps): Schema[] {
required: true, required: true,
selectMode: 'group', selectMode: 'group',
options: [ options: [
{ ...inputVariables.map(item => ({
label: '流程参数', label: item.group,
children: Object.keys(props.inputSchema).map(key => ({ children: item.variables,
label: props.inputSchema[key]?.label ?? '', })),
value: key,
})),
},
...groups,
], ],
}, },
], ],
@@ -110,35 +151,13 @@ export function outputsFormColumns(editable: boolean = false, required: boolean
] ]
} }
export const LimitHandler = (props: HandleProps & { limit: number }) => {
const connections = useNodeConnections({
handleType: props.type,
})
return (
<Handle
{...props}
isConnectable={connections.length < props.limit}
/>
)
}
type ColumnsSchemaProps = {
// getInputSchema: () => Record<string, Record<string, any>>,
inputSchema: Record<string, Record<string, any>>,
nodeId: string,
nodeData: any,
getNodeDataById: (id: string) => any,
getAllIncomerNodeById: (id: string) => Node[],
}
type AmisNodeProps = { type AmisNodeProps = {
nodeProps: NodeProps nodeProps: NodeProps
type: AmisNodeType
defaultNodeName: String defaultNodeName: String
defaultNodeDescription?: String defaultNodeDescription?: String
extraNodeDescription?: (nodeData: any) => JSX.Element extraNodeDescription?: (nodeData: any) => JSX.Element
handlers?: (nodeData: any) => JSX.Element handler: JSX.Element
columnSchema?: (props: ColumnsSchemaProps) => Schema[] columnSchema?: () => Schema[]
} }
const AmisNodeContainerDiv = styled.div` const AmisNodeContainerDiv = styled.div`
@@ -151,30 +170,140 @@ const AmisNodeContainerDiv = styled.div`
} }
` `
export const StartNodeHandler = () => {
return <Handle type="source" position={Position.Right} id="source"/>
}
export const EndNodeHandler = () => {
return <Handle type="target" position={Position.Left} id="target"/>
}
export const NormalNodeHandler = () => {
return (
<>
<StartNodeHandler/>
<EndNodeHandler/>
</>
)
}
const AmisNode: (props: AmisNodeProps) => JSX.Element = ({ const AmisNode: (props: AmisNodeProps) => JSX.Element = ({
nodeProps, nodeProps,
type,
defaultNodeName, defaultNodeName,
defaultNodeDescription, defaultNodeDescription,
extraNodeDescription, extraNodeDescription,
handlers, handler,
columnSchema, columnSchema,
}) => { }) => {
const { const {removeNode} = useFlowStore()
removeNode, const {getDataById, setDataById} = useDataStore()
getAllIncomerNodeById, const {id} = nodeProps
} = useFlowStore()
const {getDataById} = useDataStore()
const {inputSchema} = useContextStore()
const {id, data} = nodeProps
const {editNode} = data
// @ts-ignore // @ts-ignore
const nodeData = getDataById(id) const nodeData = getDataById(id)
const nodeName = isEmpty(nodeData?.node?.name) ? defaultNodeName : nodeData.node.name const nodeName = isEmpty(nodeData?.node?.name) ? defaultNodeName : nodeData.node.name
const nodeDescription = isEmpty(nodeData?.node?.description) ? defaultNodeDescription : nodeData.node?.description const nodeDescription = isEmpty(nodeData?.node?.description) ? defaultNodeDescription : nodeData.node?.description
const [editDrawerOpen, setEditDrawerOpen] = useState(false)
const [editDrawerForm, setEditDrawerForm] = useState<JSX.Element>(<></>)
const openEditDrawer = useCallback(() => {
setEditDrawerForm(
amisRender(
{
type: 'wrapper',
size: 'none',
body: [
{
debug: commonInfo.debug,
type: 'form',
...horizontalFormOptions(),
wrapWithPanel: false,
onEvent: {
submitSucc: {
actions: [
{
actionType: 'custom',
// @ts-ignore
script: (context, action, event) => {
setDataById(
id,
{
...context.props.data,
finished: true,
},
)
setEditDrawerOpen(false)
},
},
],
},
},
body: [
{
type: 'input-text',
name: 'node.name',
label: '节点名称',
placeholder: nodeName,
},
{
type: 'textarea',
name: 'node.description',
label: '节点描述',
placeholder: nodeDescription,
},
{
type: 'divider',
},
...(columnSchema?.() ?? []),
{
type: 'wrapper',
size: 'none',
className: 'space-x-2 text-right',
body: [
{
type: 'action',
label: '取消',
onEvent: {
click: {
actions: [
{
actionType: 'custom',
// @ts-ignore
script: (context, action, event) => {
setEditDrawerOpen(false)
},
},
],
},
},
},
{
type: 'submit',
label: '保存',
level: 'primary',
},
],
},
],
},
],
},
getDataById(id),
),
)
setEditDrawerOpen(true)
}, [nodeData])
return ( return (
<AmisNodeContainerDiv className="w-64"> <AmisNodeContainerDiv className="w-64">
<Drawer
title="节点编辑"
open={editDrawerOpen}
closeIcon={false}
maskClosable={false}
destroyOnHidden
size="large"
>
{editDrawerForm}
</Drawer>
<Card <Card
className="node-card" className="node-card"
title={nodeName} title={nodeName}
@@ -195,36 +324,7 @@ const AmisNode: (props: AmisNodeProps) => JSX.Element = ({
size="small" size="small"
icon={<EditFilled/>} icon={<EditFilled/>}
block block
// @ts-ignore onClick={() => openEditDrawer()}
onClick={() => editNode(
id,
[
{
type: 'input-text',
name: 'node.name',
label: '节点名称',
placeholder: nodeName,
},
{
type: 'textarea',
name: 'node.description',
label: '节点描述',
placeholder: nodeDescription,
},
{
type: 'divider',
},
...(
columnSchema?.({
inputSchema,
nodeId: id,
nodeData,
getNodeDataById: getDataById,
getAllIncomerNodeById,
}) ?? []
),
],
)}
/>, />,
<Button <Button
className="text-secondary" className="text-secondary"
@@ -241,14 +341,7 @@ const AmisNode: (props: AmisNodeProps) => JSX.Element = ({
{extraNodeDescription?.(nodeData)} {extraNodeDescription?.(nodeData)}
</div> </div>
</Card> </Card>
{isNil(handlers) {handler}
? <>
{isEqual(type, 'start') || isEqual(type, 'normal')
? <Handle type="source" position={Position.Right} id="source"/> : undefined}
{isEqual(type, 'end') || isEqual(type, 'normal')
? <Handle type="target" position={Position.Left} id="target"/> : undefined}
</>
: handlers?.(nodeData)}
</AmisNodeContainerDiv> </AmisNodeContainerDiv>
) )
} }

View File

@@ -1,52 +1,62 @@
import type {NodeProps} from '@xyflow/react' import type {NodeProps} from '@xyflow/react'
import AmisNode, {inputsFormColumns, outputsFormColumns} from './AmisNode.tsx'
import React from 'react' import React from 'react'
import {useContextStore} from '../store/ContextStore.ts'
import {useDataStore} from '../store/DataStore.ts'
import {useFlowStore} from '../store/FlowStore.ts'
import AmisNode, {inputsFormColumns, NormalNodeHandler, outputsFormColumns} from './AmisNode.tsx'
const CodeNode = (props: NodeProps) => AmisNode({ const CodeNode = (props: NodeProps) => {
nodeProps: props, const {getNodes, getEdges} = useFlowStore()
type: 'normal', const {getData} = useDataStore()
defaultNodeName: '代码执行', const {getInputSchema} = useContextStore()
defaultNodeDescription: '执行自定义的处理代码', return (
columnSchema: (props) => [ <AmisNode
...inputsFormColumns(props), nodeProps={props}
{ defaultNodeName="代码执行"
type: 'divider', defaultNodeDescription="执行自定义的处理代码"
}, columnSchema={() => [
{ ...inputsFormColumns(props.id, getInputSchema(), getNodes(), getEdges(), getData()),
type: 'select',
name: 'type',
label: '代码类型',
required: true,
options: [
{ {
value: 'javascript', type: 'divider',
label: 'JavaScript',
}, },
{ {
value: 'python', type: 'select',
label: 'Python', name: 'type',
label: '代码类型',
required: true,
options: [
{
value: 'javascript',
label: 'JavaScript',
},
{
value: 'python',
label: 'Python',
},
{
value: 'lua',
label: 'Lua',
},
],
}, },
{ {
value: 'lua', type: 'editor',
label: 'Lua', required: true,
label: '代码内容',
name: 'content',
language: '${type}',
options: {
wordWrap: 'bounded',
},
}, },
], {
}, type: 'divider',
{ },
type: 'editor', ...outputsFormColumns(true, true, {result: {type: 'string'}}),
required: true, ]}
label: '代码内容', handler={<NormalNodeHandler/>}
name: 'content', />
language: '${type}', )
options: { }
wordWrap: 'bounded',
},
},
{
type: 'divider',
},
...outputsFormColumns(true, true, {result: {type: 'string'}}),
],
})
export default React.memo(CodeNode) export default React.memo(CodeNode)

View File

@@ -1,66 +1,76 @@
import type {NodeProps} from '@xyflow/react' import type {NodeProps} from '@xyflow/react'
import {commonInfo} from '../../../util/amis.tsx'
import AmisNode, {inputsFormColumns, outputsFormColumns} from './AmisNode.tsx'
import React from 'react' import React from 'react'
import {commonInfo} from '../../../util/amis.tsx'
import {useContextStore} from '../store/ContextStore.ts'
import {useDataStore} from '../store/DataStore.ts'
import {useFlowStore} from '../store/FlowStore.ts'
import AmisNode, {inputsFormColumns, NormalNodeHandler, outputsFormColumns} from './AmisNode.tsx'
const KnowledgeNode = (props: NodeProps) => AmisNode({ const KnowledgeNode = (props: NodeProps) => {
nodeProps: props, const {getNodes, getEdges} = useFlowStore()
type: 'normal', const {getData} = useDataStore()
defaultNodeName: '知识库', const {getInputSchema} = useContextStore()
defaultNodeDescription: '查询知识库获取外部知识', return (
columnSchema: (props) => [ <AmisNode
...inputsFormColumns(props), nodeProps={props}
{ defaultNodeName="知识库"
type: 'divider', defaultNodeDescription="查询知识库获取外部知识"
}, columnSchema={() => [
{ ...inputsFormColumns(props.id, getInputSchema(), getNodes(), getEdges(), getData()),
type: 'select', {
name: 'knowledgeId', type: 'divider',
label: '知识库',
required: true,
options: [],
source: {
method: 'get',
url: `${commonInfo.baseAiUrl}/knowledge/list`,
// @ts-ignore
adaptor: (payload, response, api, context) => {
return {
...payload,
data: {
items: payload.data.items.map((item: any) => ({value: item['id'], label: item['name']})),
},
}
}, },
}, {
}, type: 'select',
{ name: 'knowledgeId',
type: 'input-text', label: '知识库',
name: 'query', required: true,
label: '查询文本', options: [],
required: true, source: {
}, method: 'get',
{ url: `${commonInfo.baseAiUrl}/knowledge/list`,
type: 'input-range', // @ts-ignore
name: 'count', adaptor: (payload, response, api, context) => {
label: '返回数量', return {
required: true, ...payload,
value: 3, data: {
max: 10, items: payload.data.items.map((item: any) => ({value: item['id'], label: item['name']})),
}, },
{ }
type: 'input-range', },
name: 'score', },
label: '匹配阀值', },
required: true, {
value: 0.6, type: 'input-text',
max: 1, name: 'query',
step: 0.05, label: '查询文本',
}, required: true,
{ },
type: 'divider', {
}, type: 'input-range',
...outputsFormColumns(false, true, {result: {type: 'array-string'}}), name: 'count',
], label: '返回数量',
}) required: true,
value: 3,
max: 10,
},
{
type: 'input-range',
name: 'score',
label: '匹配阀值',
required: true,
value: 0.6,
max: 1,
step: 0.05,
},
{
type: 'divider',
},
...outputsFormColumns(false, true, {result: {type: 'array-string'}}),
]}
handler={<NormalNodeHandler/>}
/>
)
}
export default React.memo(KnowledgeNode) export default React.memo(KnowledgeNode)

View File

@@ -1,51 +1,61 @@
import type {NodeProps} from '@xyflow/react' import type {NodeProps} from '@xyflow/react'
import {Tag} from 'antd' import {Tag} from 'antd'
import AmisNode, {inputsFormColumns, outputsFormColumns} from './AmisNode.tsx'
import React from 'react' import React from 'react'
import {useContextStore} from '../store/ContextStore.ts'
import {useDataStore} from '../store/DataStore.ts'
import {useFlowStore} from '../store/FlowStore.ts'
import AmisNode, {inputsFormColumns, NormalNodeHandler, outputsFormColumns} from './AmisNode.tsx'
const modelMap: Record<string, string> = { const modelMap: Record<string, string> = {
qwen3: 'Qwen3', qwen3: 'Qwen3',
deepseek: 'Deepseek', deepseek: 'Deepseek',
} }
const LlmNode = (props: NodeProps) => AmisNode({ const LlmNode = (props: NodeProps) => {
nodeProps: props, const {getNodes, getEdges} = useFlowStore()
type: 'normal', const {getData} = useDataStore()
defaultNodeName: '大模型', const {getInputSchema} = useContextStore()
defaultNodeDescription: '使用大模型对话', return (
extraNodeDescription: nodeData => { <AmisNode
const model = nodeData?.model as string | undefined nodeProps={props}
return model defaultNodeName="大模型"
? <div className="mt-2 flex justify-between"> defaultNodeDescription="使用大模型对话"
<span></span> extraNodeDescription={nodeData => {
<Tag className="m-0" color="blue">{modelMap[model]}</Tag> const model = nodeData?.model as string | undefined
</div> return model
: <></> ? <div className="mt-2 flex justify-between">
}, <span></span>
columnSchema: (props) => [ <Tag className="m-0" color="blue">{modelMap[model]}</Tag>
...inputsFormColumns(props), </div>
{ : <></>
type: 'divider', }}
}, columnSchema={() => [
{ ...inputsFormColumns(props.id, getInputSchema(), getNodes(), getEdges(), getData()),
type: 'select', {
name: 'model', type: 'divider',
label: '大模型', },
required: true, {
selectFirst: true, type: 'select',
options: Object.keys(modelMap).map(key => ({label: modelMap[key], value: key})), name: 'model',
}, label: '大模型',
{ required: true,
type: 'textarea', selectFirst: true,
name: 'systemPrompt', options: Object.keys(modelMap).map(key => ({label: modelMap[key], value: key})),
label: '系统提示词', },
required: true, {
}, type: 'textarea',
{ name: 'systemPrompt',
type: 'divider', label: '系统提示词',
}, required: true,
...outputsFormColumns(false, true, {text: {type: 'string'}}), },
], {
}) type: 'divider',
},
...outputsFormColumns(false, true, {text: {type: 'string'}}),
]}
handler={<NormalNodeHandler/>}
/>
)
}
export default React.memo(LlmNode) export default React.memo(LlmNode)

View File

@@ -1,13 +1,17 @@
import type {NodeProps} from '@xyflow/react' import type {NodeProps} from '@xyflow/react'
import AmisNode, {outputsFormColumns} from './AmisNode.tsx'
import React from 'react' import React from 'react'
import AmisNode, {EndNodeHandler, outputsFormColumns} from './AmisNode.tsx'
const OutputNode = (props: NodeProps) => AmisNode({ const OutputNode = (props: NodeProps) => {
nodeProps: props, return (
type: 'end', <AmisNode
defaultNodeName: '输出节点', nodeProps={props}
defaultNodeDescription: '定义输出变量', defaultNodeName="输出节点"
columnSchema: () => outputsFormColumns(true), defaultNodeDescription="定义输出变量"
}) columnSchema={() => outputsFormColumns(true)}
handler={<EndNodeHandler/>}
/>
)
}
export default React.memo(OutputNode) export default React.memo(OutputNode)

View File

@@ -15,41 +15,39 @@ const cases = [
}, },
] ]
const SwitchNode = (props: NodeProps) => AmisNode({ const SwitchNode = (props: NodeProps) => {
nodeProps: props, return (
type: 'normal', <AmisNode
defaultNodeName: '分支节点', nodeProps={props}
defaultNodeDescription: '根据不同的情况前往不同的分支', defaultNodeName="分支节点"
columnSchema: () => [], defaultNodeDescription="根据不同的情况前往不同的分支"
// @ts-ignore extraNodeDescription={() => {
extraNodeDescription: nodeData => { return (
return ( <div className="mt-2">
<div className="mt-2"> {cases.map(item => (
{cases.map(item => ( <div key={item.index} className="mt-1">
<div key={item.index} className="mt-1"> <Tag className="m-0" color="blue"> {item.index}</Tag>
<Tag className="m-0" color="blue"> {item.index}</Tag> </div>
))}
</div> </div>
))} )
</div> }}
) handler={
}, <>
// @ts-ignore <Handle type="target" position={Position.Left}/>
handlers: nodeData => { {cases.map((item, index) => (
return ( <Handle
<> type="source"
<Handle type="target" position={Position.Left}/> position={Position.Right}
{cases.map((item, index) => ( key={item.index}
<Handle id={`${item.index}`}
type="source" style={{top: 85 + (25 * index)}}
position={Position.Right} />
key={item.index} ))}
id={`${item.index}`} </>
style={{top: 85 + (25 * index)}} }
/> />
))} )
</> }
)
},
})
export default React.memo(SwitchNode) export default React.memo(SwitchNode)

View File

@@ -2,10 +2,12 @@ import {create} from 'zustand/react'
export type ContextStoreState = { export type ContextStoreState = {
inputSchema: Record<string, Record<string, any>>, inputSchema: Record<string, Record<string, any>>,
getInputSchema: () => Record<string, Record<string, any>>,
setInputSchema: (inputSchema: Record<string, Record<string, any>>) => void, setInputSchema: (inputSchema: Record<string, Record<string, any>>) => void,
} }
export const useContextStore = create<ContextStoreState>((set) => ({ export const useContextStore = create<ContextStoreState>((set, get) => ({
inputSchema: {}, inputSchema: {},
getInputSchema: () => get().inputSchema,
setInputSchema: (inputSchema: Record<string, Record<string, any>>) => set({inputSchema}), setInputSchema: (inputSchema: Record<string, Record<string, any>>) => set({inputSchema}),
})) }))

View File

@@ -3,14 +3,12 @@ import {
applyEdgeChanges, applyEdgeChanges,
applyNodeChanges, applyNodeChanges,
type Edge, type Edge,
getIncomers,
type Node, type Node,
type OnConnect, type OnConnect,
type OnEdgesChange, type OnEdgesChange,
type OnNodesChange, type OnNodesChange,
} from '@xyflow/react' } from '@xyflow/react'
import {filter, find, isEqual, unique} from 'licia' import {filter, find, isEqual} from 'licia'
import Queue from 'yocto-queue'
import {create} from 'zustand/react' import {create} from 'zustand/react'
export type FlowStoreState = { export type FlowStoreState = {
@@ -18,7 +16,6 @@ export type FlowStoreState = {
getNodes: () => Node[], getNodes: () => Node[],
onNodesChange: OnNodesChange, onNodesChange: OnNodesChange,
getNodeById: (id: string) => Node | undefined, getNodeById: (id: string) => Node | undefined,
getAllIncomerNodeById: (id: string) => Node[],
addNode: (node: Node) => void, addNode: (node: Node) => void,
removeNode: (id: string) => void, removeNode: (id: string) => void,
setNodes: (nodes: Node[]) => void, setNodes: (nodes: Node[]) => void,
@@ -40,21 +37,6 @@ export const useFlowStore = create<FlowStoreState>((set, get) => ({
}) })
}, },
getNodeById: (id: string) => find(get().nodes, node => isEqual(node.id, id)), getNodeById: (id: string) => find(get().nodes, node => isEqual(node.id, id)),
getAllIncomerNodeById: (id: string) => {
let nodes = get().nodes
let edges = get().edges
let queue = new Queue<Node>()
queue.enqueue(find(nodes, node => isEqual(node.id, id))!)
let result: Node[] = []
while (queue.size !== 0) {
let currentNode = queue.dequeue()!
for (const incomer of getIncomers(currentNode, nodes, edges)) {
result.push(incomer)
queue.enqueue(incomer)
}
}
return unique(result, (a, b) => isEqual(a.id, b.id))
},
addNode: node => set({nodes: get().nodes.concat(node)}), addNode: node => set({nodes: get().nodes.concat(node)}),
removeNode: id => { removeNode: id => {
set({ set({

View File

@@ -1,40 +1,20 @@
import {amisRender, commonInfo} from '../util/amis.tsx' import {useState} from 'react'
import FlowEditor, {type GraphData} from '../components/flow/FlowEditor.tsx'
function Test() { function Test() {
const [graphData] = useState<GraphData>({
nodes: [],
edges: [],
data: {},
})
return ( return (
<div> <div className="h-screen">
{amisRender( <FlowEditor
{ inputSchema={{}}
debug: commonInfo.debug, graphData={graphData}
type: 'form', onGraphDataChange={data => console.log(data)}
canAccessSuperData: false, />
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '提交',
},
],
body: [
{
type: 'input-file',
required: true,
name: 'files',
label: '数据文件',
autoUpload: false,
drag: true,
multiple: true,
accept: '*',
maxSize: 104857600,
receiver: `${commonInfo.baseAiUrl}/upload`,
useChunk: false,
},
],
},
)}
</div> </div>
) )
} }