6 Commits

Author SHA1 Message Date
v-zhangjc9
fad190567b feat(web): 节点描述和名称直接放在节点数据中 2025-07-10 16:34:47 +08:00
v-zhangjc9
333da7ef88 style(web): 移除未使用的引入 2025-07-10 14:35:29 +08:00
v-zhangjc9
d0ca36e9d7 style(web): 优化命名 2025-07-10 14:33:36 +08:00
v-zhangjc9
f70b3b2a32 fix(web): 移除节点未移除节点数据 2025-07-10 14:28:32 +08:00
v-zhangjc9
f707a0d2b5 refactor(web): 优化节点展现 2025-07-10 12:44:37 +08:00
v-zhangjc9
5e763637da refactor(web): 优化流程节点的定义和实现 2025-07-10 12:08:13 +08:00
12 changed files with 477 additions and 434 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, 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,46 @@ const FlowableDiv = styled.div`
} }
` `
type NodeDefine = {
key: string,
name: string,
description: string,
component: any,
}
const nodeDefine: Record<string, NodeDefine> = {
'output-node': {
key: 'output-node',
name: '输出',
description: '定义输出变量',
component: OutputNode,
},
'llm-node': {
key: 'llm-node',
name: '大模型',
description: '使用大模型对话',
component: LlmNode,
},
'knowledge-node': {
key: 'knowledge-node',
name: '知识库',
description: '',
component: KnowledgeNode,
},
'code-node': {
key: 'code-node',
name: '代码执行',
description: '执行自定义的处理代码',
component: CodeNode,
},
'switch-node': {
key: 'switch-node',
name: '分支节点',
description: '根据不同的情况前往不同的分支',
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 +103,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, setDataById} = useDataStore()
useShallow(state => ({
data: state.data,
setData: state.setData,
getDataById: state.getDataById,
setDataById: state.setDataById,
})),
)
const { const {
nodes, nodes,
addNode, addNode,
@@ -126,106 +114,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 +127,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,23 +134,37 @@ 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: Object.keys(nodeDefine).map(key => ({key: key, label: nodeDefine[key]!.name})),
onClick: ({key}) => { onClick: ({key}) => {
try { try {
if (commonInfo.debug) { if (commonInfo.debug) {
console.info('Add', key, JSON.stringify({nodes, edges, data})) console.info('Add', key, JSON.stringify({nodes, edges, data}))
} }
checkAddNode(key, nodes, edges) checkAddNode(key, nodes, edges)
let nodeId = randomId(10, 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM')
let define = nodeDefine[key]
setDataById(
nodeId,
{
node: {
name: define.name,
description: define.description,
},
},
)
addNode({ addNode({
id: randomId(10), id: nodeId,
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 +204,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}
@@ -331,10 +222,7 @@ function FlowEditor(props: FlowEditorProps) {
} }
}} }}
// @ts-ignore // @ts-ignore
nodeTypes={arrToMap( nodeTypes={arrToMap(Object.keys(nodeDefine), key => nodeDefine[key]!.component)}
nodeDef.map(def => def.key),
key => find(nodeDef, def => isEqual(key, def.key))!.component)
}
> >
<Controls/> <Controls/>
<MiniMap/> <MiniMap/>

View File

@@ -1,33 +1,81 @@
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: `${key} (${inputSchema[key]?.label ?? ''})`,
value: key,
}))
let incomerIds = getAllIncomerNodeById(nodeId, nodes, edges)
let incomerVariables: InputFormOptionsGroup[] = []
for (const incomerId of incomerIds) {
let nodeData = data[incomerId] ?? {}
let group = incomerId
if (has(nodeData, 'node') && has(nodeData.node, 'name')) {
group = `${nodeData.node.name} ${incomerId}`
}
if (has(nodeData, 'outputs')) {
let outputs = nodeData?.outputs ?? []
incomerVariables.push({
group: group,
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 +96,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,
], ],
}, },
], ],
@@ -63,14 +107,13 @@ export function inputsFormColumns(props: ColumnsSchemaProps): Schema[] {
] ]
} }
export function outputsFormColumns(editable: boolean = false, required: boolean = false, preload?: any): Schema[] { export function outputsFormColumns(editable: boolean = false, required: boolean = false): Schema[] {
return [ return [
{ {
disabled: !editable, disabled: !editable,
type: 'input-kvs', type: 'input-kvs',
name: 'outputs', name: 'outputs',
label: '输出变量', label: '输出变量',
value: preload,
addButtonText: '新增输出', addButtonText: '新增输出',
draggable: false, draggable: false,
keyItem: { keyItem: {
@@ -110,35 +153,11 @@ 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 extraNodeDescription?: JSX.Element
defaultNodeName: String handler: JSX.Element
defaultNodeDescription?: String columnSchema?: () => Schema[]
extraNodeDescription?: (nodeData: any) => JSX.Element
handlers?: (nodeData: any) => JSX.Element
columnSchema?: (props: ColumnsSchemaProps) => Schema[]
} }
const AmisNodeContainerDiv = styled.div` const AmisNodeContainerDiv = styled.div`
@@ -151,30 +170,142 @@ 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,
defaultNodeDescription,
extraNodeDescription, extraNodeDescription,
handlers, handler,
columnSchema, columnSchema,
}) => { }) => {
const { const {removeNode} = useFlowStore()
removeNode, const {getDataById, setDataById, removeDataById} = 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 = nodeData?.node?.name ?? ''
const nodeDescription = isEmpty(nodeData?.node?.description) ? defaultNodeDescription : nodeData.node?.description const nodeDescription = nodeData?.node?.description ?? ''
const [editDrawerOpen, setEditDrawerOpen] = useState(false)
const [editDrawerForm, setEditDrawerForm] = useState<JSX.Element>(<></>)
const onOpenEditDrawerClick = 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])
const onRemoveClick = useCallback(() => {
removeNode(id)
removeDataById(id)
}, [])
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 +326,7 @@ const AmisNode: (props: AmisNodeProps) => JSX.Element = ({
size="small" size="small"
icon={<EditFilled/>} icon={<EditFilled/>}
block block
// @ts-ignore onClick={() => onOpenEditDrawerClick()}
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"
@@ -232,23 +334,16 @@ const AmisNode: (props: AmisNodeProps) => JSX.Element = ({
size="small" size="small"
icon={<DeleteFilled/>} icon={<DeleteFilled/>}
block block
onClick={() => removeNode(id)} onClick={() => onRemoveClick()}
/>, />,
]} ]}
> >
<div className="card-description p-2 text-secondary text-sm"> <div className="card-description p-2 text-secondary text-sm">
{nodeDescription} {nodeDescription}
{extraNodeDescription?.(nodeData)} {extraNodeDescription}
</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,14 +1,30 @@
import type {NodeProps} from '@xyflow/react' import type {NodeProps} from '@xyflow/react'
import AmisNode, {inputsFormColumns, outputsFormColumns} from './AmisNode.tsx' import React, {useCallback, useEffect} 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, mergeDataById} = useDataStore()
defaultNodeName: '代码执行', const {getInputSchema} = useContextStore()
defaultNodeDescription: '执行自定义的处理代码',
columnSchema: (props) => [ useEffect(() => {
...inputsFormColumns(props), mergeDataById(
props.id,
{
outputs: {
result: {
type: 'string',
},
},
},
)
}, [props.id])
const columnsSchema = useCallback(() => [
...inputsFormColumns(props.id, getInputSchema(), getNodes(), getEdges(), getData()),
{ {
type: 'divider', type: 'divider',
}, },
@@ -45,8 +61,15 @@ const CodeNode = (props: NodeProps) => AmisNode({
{ {
type: 'divider', type: 'divider',
}, },
...outputsFormColumns(true, true, {result: {type: 'string'}}), ...outputsFormColumns(true, true),
], ], [props.id])
}) return (
<AmisNode
nodeProps={props}
columnSchema={columnsSchema}
handler={<NormalNodeHandler/>}
/>
)
}
export default React.memo(CodeNode) export default React.memo(CodeNode)

View File

@@ -1,15 +1,31 @@
import type {NodeProps} from '@xyflow/react' import type {NodeProps} from '@xyflow/react'
import React, {useCallback, useEffect} from 'react'
import {commonInfo} from '../../../util/amis.tsx' import {commonInfo} from '../../../util/amis.tsx'
import AmisNode, {inputsFormColumns, outputsFormColumns} from './AmisNode.tsx' import {useContextStore} from '../store/ContextStore.ts'
import React from 'react' 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, mergeDataById} = useDataStore()
defaultNodeName: '知识库', const {getInputSchema} = useContextStore()
defaultNodeDescription: '查询知识库获取外部知识',
columnSchema: (props) => [ useEffect(() => {
...inputsFormColumns(props), mergeDataById(
props.id,
{
outputs: {
result: {
type: 'array-string',
},
},
},
)
}, [props.id])
const columnsSchema = useCallback(() => [
...inputsFormColumns(props.id, getInputSchema(), getNodes(), getEdges(), getData()),
{ {
type: 'divider', type: 'divider',
}, },
@@ -59,8 +75,15 @@ const KnowledgeNode = (props: NodeProps) => AmisNode({
{ {
type: 'divider', type: 'divider',
}, },
...outputsFormColumns(false, true, {result: {type: 'array-string'}}), ...outputsFormColumns(false, true),
], ], [props.id])
}) return (
<AmisNode
nodeProps={props}
columnSchema={columnsSchema}
handler={<NormalNodeHandler/>}
/>
)
}
export default React.memo(KnowledgeNode) export default React.memo(KnowledgeNode)

View File

@@ -1,29 +1,38 @@
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, {useCallback, useEffect} 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, mergeDataById, getDataById} = useDataStore()
defaultNodeName: '大模型', const {getInputSchema} = useContextStore()
defaultNodeDescription: '使用大模型对话',
extraNodeDescription: nodeData => { const nodeData = getDataById(props.id)
const model = nodeData?.model as string | undefined
return model useEffect(() => {
? <div className="mt-2 flex justify-between"> mergeDataById(
<span></span> props.id,
<Tag className="m-0" color="blue">{modelMap[model]}</Tag> {
</div> outputs: {
: <></> text: {
type: 'string',
}, },
columnSchema: (props) => [ },
...inputsFormColumns(props), },
)
}, [props.id])
const columnsSchema = useCallback(() => [
...inputsFormColumns(props.id, getInputSchema(), getNodes(), getEdges(), getData()),
{ {
type: 'divider', type: 'divider',
}, },
@@ -44,8 +53,23 @@ const LlmNode = (props: NodeProps) => AmisNode({
{ {
type: 'divider', type: 'divider',
}, },
...outputsFormColumns(false, true, {text: {type: 'string'}}), ...outputsFormColumns(false, true),
], ], [props.id])
}) return (
<AmisNode
nodeProps={props}
extraNodeDescription={
nodeData?.model
? <div className="mt-2 flex justify-between">
<span></span>
<Tag className="m-0" color="blue">{modelMap[nodeData.model]}</Tag>
</div>
: <></>
}
columnSchema={columnsSchema}
handler={<NormalNodeHandler/>}
/>
)
}
export default React.memo(LlmNode) export default React.memo(LlmNode)

View File

@@ -1,13 +1,26 @@
import type {NodeProps} from '@xyflow/react' import type {NodeProps} from '@xyflow/react'
import AmisNode, {outputsFormColumns} from './AmisNode.tsx' import React, {useCallback} 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, {EndNodeHandler, inputsFormColumns} from './AmisNode.tsx'
const OutputNode = (props: NodeProps) => AmisNode({ const OutputNode = (props: NodeProps) => {
nodeProps: props, const {getNodes, getEdges} = useFlowStore()
type: 'end', const {getData} = useDataStore()
defaultNodeName: '输出节点', const {getInputSchema} = useContextStore()
defaultNodeDescription: '定义输出变量', const columnsSchema = useCallback(
columnSchema: () => outputsFormColumns(true), () => inputsFormColumns(props.id, getInputSchema(), getNodes(), getEdges(), getData()),
}) [props.id],
)
return (
<AmisNode
nodeProps={props}
columnSchema={columnsSchema}
handler={<EndNodeHandler/>}
/>
)
}
export default React.memo(OutputNode) export default React.memo(OutputNode)

View File

@@ -15,15 +15,11 @@ const cases = [
}, },
] ]
const SwitchNode = (props: NodeProps) => AmisNode({ const SwitchNode = (props: NodeProps) => {
nodeProps: props,
type: 'normal',
defaultNodeName: '分支节点',
defaultNodeDescription: '根据不同的情况前往不同的分支',
columnSchema: () => [],
// @ts-ignore
extraNodeDescription: nodeData => {
return ( return (
<AmisNode
nodeProps={props}
extraNodeDescription={
<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">
@@ -31,11 +27,8 @@ const SwitchNode = (props: NodeProps) => AmisNode({
</div> </div>
))} ))}
</div> </div>
) }
}, handler={
// @ts-ignore
handlers: nodeData => {
return (
<> <>
<Handle type="target" position={Position.Left}/> <Handle type="target" position={Position.Left}/>
{cases.map((item, index) => ( {cases.map((item, index) => (
@@ -48,8 +41,9 @@ const SwitchNode = (props: NodeProps) => AmisNode({
/> />
))} ))}
</> </>
}
/>
) )
}, }
})
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

@@ -6,6 +6,8 @@ export type DataStoreState = {
setData: (data: Record<string, any>) => void, setData: (data: Record<string, any>) => void,
getDataById: (id: string) => any, getDataById: (id: string) => any,
setDataById: (id: string, data: any) => void, setDataById: (id: string, data: any) => void,
mergeDataById: (id: string, data: any) => void,
removeDataById: (id: string) => void,
} }
export const useDataStore = create<DataStoreState>((set, get) => ({ export const useDataStore = create<DataStoreState>((set, get) => ({
@@ -22,4 +24,21 @@ export const useDataStore = create<DataStoreState>((set, get) => ({
data: updateData, data: updateData,
}) })
}, },
mergeDataById: (id, data) => {
let updateData = get().data
updateData[id] = {
...(updateData[id] ?? {}),
...data,
}
set({
data: updateData,
})
},
removeDataById: (id) => {
let data = get().data
delete data[id]
set({
data,
})
},
})) }))

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>
) )
} }

View File

@@ -1,4 +1,4 @@
import {addRule, AlertComponent, attachmentAdpator, makeTranslator, render, type Schema, ToastComponent} from 'amis' import {AlertComponent, attachmentAdpator, makeTranslator, render, type Schema, ToastComponent} from 'amis'
import 'amis/lib/themes/antd.css' import 'amis/lib/themes/antd.css'
import 'amis/lib/helper.css' import 'amis/lib/helper.css'