feat: 循环节点

This commit is contained in:
zhanghao 2026-04-13 11:27:13 +08:00
parent 5da44c5588
commit 1918528812
8 changed files with 324 additions and 527 deletions

View File

@ -42,7 +42,7 @@
</el-form>
</div>
<div v-if="props.data.type === 'serviceNode'">
<div v-if="['currentLoop', 'serviceNode'].includes(props.data.type)">
<div class="input__container">
<div class="title">
<div class="left">
@ -342,7 +342,7 @@ watch(
() => {
if (props.data.type === "start") {
formData.inputParams = props.data.properties?.inputParams || [];
} else if (props.data.type === "serviceNode") {
} else if (['currentLoop', 'serviceNode'].includes(props.data.type)) {
formData.nodeParams = props.data.properties.nodeParams;
formData.outputParams = props.data.properties.outputParams;
console.log('formData', formData)

View File

@ -306,7 +306,7 @@ export const collapseList = [
{ name: "input", type: "input", input: "", required: true }
],
outputType: 'json',
outputParams: [{ name: 'result', type: 'Object', children: [], desc: 'js节点返回'}]
outputParams: [{ name: 'result', type: 'object', children: [], desc: 'js节点返回'}]
},
{
icon: microphoneSvg,
@ -316,12 +316,14 @@ export const collapseList = [
action: 'GET_CURRENT_OBJECT',
nodeType: 'getCurrentObject',
nodeParams: [
{ name: "array", type: "input", input: "", disabled: true }
{ name: "array", type: "input", input: "" }
],
outputType: 'json',
outputParams: [
{ name: 'index', type: 'number', desc: '索引', disabled: true},
{ name: 'object', type: 'Object', children: [], desc: '当前循环对象', }
{ name: 'index', type: 'number', desc: '索引'},
{ name: 'object', type: 'object', children: [
{ name: 'test', type: 'string', desc: '占位属性' }
], desc: '当前循环对象', }
]
},
],

View File

@ -282,15 +282,15 @@ const testRun = async () => {
}
let allValid = true;
for (const node of nodes) {
const nodeModel = lf.getNodeModelById(node.id);
if (nodeModel && nodeModel.validateForm) {
const result = await nodeModel.validateForm();
if (!result.valid) {
allValid = false;
}
}
}
// for (const node of nodes) {
// const nodeModel = lf.getNodeModelById(node.id);
// if (nodeModel && nodeModel.validateForm) {
// const result = await nodeModel.validateForm();
// if (!result.valid) {
// allValid = false;
// }
// }
// }
if (allValid) {
isOpen.value = true;
@ -645,7 +645,9 @@ const initFlow = () => {
lf.on("node:mouseleave", ({ data }) => {
const node = lf.getNodeModelById(data.id);
node.setCustomProperties && node.setCustomProperties();
if (node.setCustomProperties) {
node.setCustomProperties();
}
});
lf.on("node:dbclick", ({ data, e }) => {

View File

@ -150,9 +150,9 @@ class ServiceNodeHtmlModel extends HtmlNodeModel {
return result
}
setCustomProperties() {
this.componentInstance.setNodeProperties()
}
// setCustomProperties() {
// this.componentInstance.setNodeProperties()
// }
/**
* 设置节点属性

View File

@ -26,119 +26,8 @@
:nodeName="props.properties.name"
:nodeDesc="props.properties.desc"
:zoom-state="nodeZoom"
@zoom="zoom"
@setNodeName="setNodeName"
/>
<div class="input__container" v-show="nodeZoom">
<div class="title">
<div class="left">
<div class="tag"></div>
<div class="text">输入</div>
</div>
<div class="right" v-if="properties.properties?.canAddFormItem">
<el-button
:disabled="flowStore.disableForm"
@click="addFormItem"
class="addFormItem"
>
<el-icon :size="20"><Plus /></el-icon>
</el-button>
</div>
</div>
<div class="form__container" v-show="nodeZoom">
<el-form
:inline="true"
:model="formData"
:rules="rules"
ref="dynamicForm"
label-position="top"
label-width="auto"
:disabled="flowStore.disableForm"
>
<div v-for="(property, index) in formData.nodeParams" :key="index">
<el-row>
<el-form-item
:label="index === 0 ? '参数名' : ''"
:prop="`nodeParams.${index}.name`"
:rules="[{ required: true, message: '请输入参数名', trigger: 'blur' }]"
>
<el-input
:disabled="property?.disabled || false"
v-model="property.name"
placeholder="请输入"
clearable
/>
</el-form-item>
<el-form-item
:label="index === 0 ? '参数值' : ''"
:prop="`nodeParams.${index}.type`"
>
<el-select v-model="property.type" @change="handleTypeChange(index)">
<el-option label="引用" value="quote" />
<el-option label="输入" value="input" />
</el-select>
<el-form-item
v-if="property.type === 'input'"
:rules="[{ required: true, message: '请输入参数值', trigger: 'blur' }]"
:prop="`nodeParams.${index}.input`"
>
<el-input-number v-if="property.componentType === 'number'" v-model="property.input" :min="0" :controls="false" :step-strictly="true" placeholder="请输入" clearable />
<el-select v-model="property.input" v-else-if="property.componentType === 'select'" >
<el-option v-for="item in property.selectOptions" :key="item" :label="item" :value="item" />
</el-select>
<el-input v-else v-model="property.input" placeholder="请输入" clearable />
</el-form-item>
<el-form-item
v-if="property.type === 'quote'"
:rules="[{ required: true, message: '请选择参数值', trigger: 'blur' }]"
:prop="`nodeParams.${index}.quote`"
>
<el-cascader
:ref="
(el) => {
if (el) cascaderRefs[index] = el;
}
"
v-model="property.quote"
:options="quoteOptions"
placeholder="请选择"
@visible-change="visibleChange"
@change="(value) => cascaderChange(value, index)"
/>
</el-form-item>
</el-form-item>
</el-row>
</div>
</el-form>
</div>
</div>
<div class="output__container" v-if="props.properties?.outputParams?.length > 0">
<div class="title">
<div class="tag"></div>
<div class="text">输出</div>
</div>
<div class="form__container">
<el-form
:inline="true"
label-position="top"
label-width="auto"
:disabled="true"
>
<el-row v-for="(item, index) in props.properties.outputParams">
<el-form-item :label="index === 0 ? '参数名' : ''" >
<el-input :value="item.name" />
</el-form-item>
<el-form-item :label="index === 0 ? '参数类型' : ''" >
<el-input :value="item.type" />
</el-form-item>
<el-form-item :label="index === 0 ? '描述' : ''" >
<el-input :value="item.desc" />
</el-form-item>
</el-row>
</el-form>
</div>
</div>
</div>
</template>
@ -146,7 +35,6 @@
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue";
import { getInput, initNodeZoom } from "@/utils/flow";
import { useFlowStore } from "@/store/modules/flow";
import { Plus } from "@element-plus/icons-vue";
import NodeTitle from "../../components/NodeTitle.vue";
import NodeState from "../../components/NodeState.vue";
import "vue3-json-viewer/dist/index.css";
@ -160,46 +48,11 @@ const props = defineProps({
const emits = defineEmits(["contentChange"]);
const flowStore = useFlowStore();
const formData = reactive({
nodeParams: [],
});
const rules = reactive({});
const quoteOptions = ref([]);
const handleTypeChange = (index) => {
if (formData.nodeParams[index].type === "input") {
formData.nodeParams[index].quote = "";
} else {
formData.nodeParams[index].input = "";
const option = getInput(props.model.id);
if (option) {
quoteOptions.value = option;
}
}
};
const dynamicForm = ref();
const setNodeProperties = async () => {
try {
const result = await dynamicForm.value.validate();
if (result) {
const data = toRaw(formData);
const properties = lf.getProperties(props.model.id);
lf.setProperties(props.model.id, {
...properties,
...data,
zoom: nodeZoom.value
});
emits("contentChange");
}
} catch {
dynamicForm.value.clearValidate();
}
};
const setNodeName = (name) => {
const properties = lf.getProperties(props.model.id);
@ -214,72 +67,6 @@ const nodeOperatingStatus = ref("NORMAL");
const inputJsonData = ref({});
const outputJsonData = ref({});
const visibleChange = (value) => {
if (value) {
const option = getInput(props.model.id);
if (option) {
quoteOptions.value = option;
}
}
};
const cascaderRefs = ref([]);
const cascaderChange = (value, index) => {
const selectedOptions = cascaderRefs.value[index].getCheckedNodes(true);
formData.nodeParams[index].quote = value;
formData.nodeParams[index].quoteType = selectedOptions[0].data.type;
};
const validateForm = async () => {
try {
const result = await dynamicForm.value.validate();
if (result) {
return { valid: true, message: "验证通过" };
} else {
return { valid: false, message: "验证失败" };
}
} catch {
return { valid: false, message: "验证失败" };
}
};
const addFormItem = () => {
formData.nodeParams.push({
name: "",
type: "",
desc: "",
required: false,
children: [],
});
emits("contentChange");
};
const nodeZoom = ref(props?.properties?.zoom ?? true)
const zoom = (flag) => {
nodeZoom.value = flag
initNodeZoom(props.model.id, nodeZoom.value, '.node__box')
}
watch(
() => props.properties,
() => {
if (props.properties.nodeParams && props.properties.nodeParams.length > 0) {
formData.nodeParams = props.properties.nodeParams;
const option = getInput(props.model.id);
if (option) {
quoteOptions.value = option;
}
nextTick(() => {
initNodeZoom(props.model.id, props?.properties?.zoom ?? true, '.node__box', true)
})
}
},
{
immediate: true,
deep: true,
}
);
onMounted(() => {
emitter.on("changeNodeState", (data) => {
if (data.nodeId === props.model.id) {
@ -314,10 +101,6 @@ onUnmounted(() => {
emitter.off("contentChange");
});
defineExpose({
validateForm,
setNodeProperties,
});
</script>
<style lang="scss" scoped>

View File

@ -150,9 +150,9 @@ class CurrentLoopNodeHtmlModel extends HtmlNodeModel {
return result
}
setCustomProperties() {
this.componentInstance.setNodeProperties()
}
// setCustomProperties() {
// this.componentInstance.setNodeProperties()
// }
/**
* 设置节点属性

View File

@ -1,276 +1,278 @@
import { GroupNodeModel } from '@logicflow/extension';
// 导入 Vue 相关方法,用于渲染组件
import { createApp, h, nextTick } from "vue";
import { HtmlNode, h as svgH } from "@logicflow/core";
import ElementPlus from "element-plus";
import Loop from './loop.vue';
class loopBodyModel extends GroupNodeModel {
initNodeData(data) {
super.initNodeData(data);
this.children = new Set(data.children || [])
this.zIndex = 0;
this.isGroup = true;
this.resizable = false;
}
// 保存组件实例引用
setComponentInstance(instance) {
this.componentInstance = instance;
}
// 验证表单
async validateForm() {
if (this.componentInstance && this.componentInstance.validate) {
try {
const result = await this.componentInstance.validate();
if (result) {
return { valid: true, message: "验证通过" };
} else {
return { valid: false, message: "验证失败" };
}
} catch {
return { valid: false, message: "验证失败" };
}
}
return { valid: true, message: "无验证方法" };
}
// 计算子节点的包围盒(包含所有子节点的最小矩形区域)
getChildrenBBox() {
const children = []
Array.from(this.children).forEach((id) => {
const node = this.graphModel.getNodeModelById(id)
if (node) {
children.push(this.graphModel.getNodeModelById(id))
} else {
this.children.delete(id)
}
});
let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
children.forEach((node) => {
let width = node.width === 0 ? 600 : node.width
let height = node.height === 0 ? 200 : node.height
minX = Math.min(minX, node.x - width / 2);
maxX = Math.max(maxX, node.x + width / 2);
minY = Math.min(minY, node.y - height / 2);
maxY = Math.max(maxY, node.y + height / 2);
});
this.width = maxX - minX + 200; // 增加内边距
this.height = maxY - minY + 260;
this.x = (minX + maxX) / 2;
this.y = (minY + maxY) / 2 - 120;
const properties = lf.getProperties(this.id)
this.setProperties({
...properties,
width: this.width,
height: this.height
})
this.getDefaultAnchor()
}
updateSize() {
const children = Array.from(this.children);
if (children.length > 0) {
this.getChildrenBBox();
}
}
// 添加子节点时立即更新大小
addChild(childId) {
super.addChild(childId);
this.updateSize();
}
// 移除子节点时更新大小
removeChild(childId) {
return false
}
// 定义节点只有左右两个锚点. 锚点位置通过中心点和宽度算出来。
getDefaultAnchor() {
let _a = this,
x = _a.x,
y = _a.y,
width = _a.width,
height = _a.height;
return [
{
x: x + width / 2 ,
y: y - 25,
name: "right",
id: "".concat(this.id, "_1"),
properties: { connectionType: "source" },
},
{
x: x - width / 2,
y: y - 25,
name: "left",
id: "".concat(this.id, "_3"),
properties: { connectionType: "target" },
},
];
}
isAllowAppendIn() {
return false;
}
}
class loopBodyView extends HtmlNode {
resizeObserver = null;
isMounted; // 标记组件是否已挂载
r; // 渲染函数
app; // Vue 应用实例
container = null;
static reusePool = new Map(); // 节点复用池
/**
* 构造函数
* @param props 传递给节点的属性包括模型图模型等
*/
constructor(props) {
super(props);
this.initVueApp(props);
}
initVueApp(props) {
this.isMounted = false;
this.hideAnchor = false;
this.autoExpand = true; // 防止锚点被折叠
this.anchorsPreset = "default"; // 重置锚点预设
// 创建 元素的渲染函数
this.r = h(Loop, {
model: props.model,
graphModel: props.graphModel,
properties: {
...props.model.getProperties(),
},
onAddToGroup: this.addChild.bind(this),
onContentChange: this.handleContentChange.bind(this),
onBindRef: this.handleComponentInstance.bind(this)
});
// 创建 Vue 应用实例,并指定渲染函数
this.app = createApp({
render: () => this.r,
});
}
addChild(data) {
this.addToGroup(data);
}
handleComponentInstance(data) {
// 将组件实例保存到节点模型
this.props.model.setComponentInstance(data)
}
handleContentChange() {
// 内容变化时强制更新尺寸
this.props.model.updateSize();
}
// 关键修改重写getShape方法
getShape() {
const { model } = this.props;
const { x, y, width, height } = model;
// 创建自定义HTML内容
const html = super.getShape();
// 创建SVG组包含HTML内容和锚点
return svgH('g', {}, [
// 绘制组节点背景
svgH('rect', {
x: x - width / 2,
y: y - height / 2,
width,
height,
stroke: '#88f',
strokeWidth: 0,
strokeDasharray: '5,5',
fill: 'rgba(136, 136, 255, 0.1)',
rx: 4,
ry: 4
}),
// 添加HTML内容
html,
// 渲染锚点
this.getAnchorShapes()
]);
}
// 创建锚点元素
getAnchorShapes() {
const { model } = this.props;
const anchors = model.anchors || [];
const anchorShapes = anchors.map((offset, index) => {
const {x, y } = offset
return svgH('circle', {
cx: x,
cy: y,
r: 7,
hover: { fill: "#FF5722" }, // 禁用悬停变色
fill: '#FF5722',
stroke: '#FF5722',
strokeWidth: 0,
className: 'lf-node-anchor',
cursor: 'crosshair',
'data-anchor-id': `anchor_${index}`
});
});
return svgH('g', {}, anchorShapes);
}
/**
* HTML 内容设置到指定的根元素上
* @param rootEl 根元素
*/
async setHtml(rootEl) {
const nodeId = this.props.model.id;
if (loopBodyView.reusePool.has(nodeId)) {
rootEl.appendChild(loopBodyView.reusePool.get(nodeId));
return;
}
if (!this.isMounted) {
this.isMounted = true;
this.container = document.createElement("div");
// this.container.style.display = "inline-block"; // 关键:确保容器自适应内容
this.container.style.width = "100%"; // 关键:确保容器自适应内容
this.container.style.height = "100%"; // 关键:确保容器自适应内容
rootEl.appendChild(this.container);
this.app.use(ElementPlus); // 关键单独注册ElementPlus
this.app.mount(this.container);
loopBodyView.reusePool.set(nodeId, this.container);
} else {
this.r.component.props.properties = this.props.model.getProperties();
}
}
addToGroup(childId) {
const groupModel = lf.getNodeModelById(this.props.model.id);
groupModel.addChild(childId);
groupModel.updateSize()
}
}
// 导出方法注册
export function registerLoopBodyNode(lf) {
lf.register({
type: "loop",
view: loopBodyView,
model: loopBodyModel,
});
import { GroupNodeModel } from '@logicflow/extension';
// 导入 Vue 相关方法,用于渲染组件
import { createApp, h, nextTick } from "vue";
import { HtmlNode, h as svgH } from "@logicflow/core";
import ElementPlus from "element-plus";
import Loop from './loop.vue';
class loopBodyModel extends GroupNodeModel {
initNodeData(data) {
super.initNodeData(data);
this.children = new Set(data.children || [])
this.zIndex = 0;
this.isGroup = true;
this.resizable = false;
}
// 保存组件实例引用
setComponentInstance(instance) {
this.componentInstance = instance;
}
// 验证表单
async validateForm() {
if (this.componentInstance && this.componentInstance.validate) {
try {
const result = await this.componentInstance.validate();
if (result) {
return { valid: true, message: "验证通过" };
} else {
return { valid: false, message: "验证失败" };
}
} catch {
return { valid: false, message: "验证失败" };
}
}
return { valid: true, message: "无验证方法" };
}
// 计算子节点的包围盒(包含所有子节点的最小矩形区域)
getChildrenBBox() {
const children = []
Array.from(this.children).forEach((id) => {
const node = this.graphModel.getNodeModelById(id)
if (node) {
children.push(this.graphModel.getNodeModelById(id))
} else {
this.children.delete(id)
}
});
let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
nextTick(() => {
children.forEach((node) => {
let width = node.width === 0 ? 320 : node.width
let height = node.height === 0 ? 200 : node.height
minX = Math.min(minX, node.x - width / 2);
maxX = Math.max(maxX, node.x + width / 2);
minY = Math.min(minY, node.y - height / 2);
maxY = Math.max(maxY, node.y + height / 2);
});
this.width = maxX - minX + 300; // 增加内边距
this.height = maxY - minY + 260;
this.x = (minX + maxX) / 2;
this.y = (minY + maxY) / 2 - 120;
const properties = lf.getProperties(this.id)
this.setProperties({
...properties,
width: this.width,
height: this.height
})
this.getDefaultAnchor()
})
}
updateSize() {
const children = Array.from(this.children);
if (children.length > 0) {
this.getChildrenBBox();
}
}
// 添加子节点时立即更新大小
addChild(childId) {
super.addChild(childId);
this.updateSize();
}
// 移除子节点时更新大小
removeChild(childId) {
return false
}
// 定义节点只有左右两个锚点. 锚点位置通过中心点和宽度算出来。
getDefaultAnchor() {
let _a = this,
x = _a.x,
y = _a.y,
width = _a.width,
height = _a.height;
return [
{
x: x + width / 2 ,
y: y - 25,
name: "right",
id: "".concat(this.id, "_1"),
properties: { connectionType: "source" },
},
{
x: x - width / 2,
y: y - 25,
name: "left",
id: "".concat(this.id, "_3"),
properties: { connectionType: "target" },
},
];
}
isAllowAppendIn() {
return false;
}
}
class loopBodyView extends HtmlNode {
resizeObserver = null;
isMounted; // 标记组件是否已挂载
r; // 渲染函数
app; // Vue 应用实例
container = null;
static reusePool = new Map(); // 节点复用池
/**
* 构造函数
* @param props 传递给节点的属性包括模型图模型等
*/
constructor(props) {
super(props);
this.initVueApp(props);
}
initVueApp(props) {
this.isMounted = false;
this.hideAnchor = false;
this.autoExpand = true; // 防止锚点被折叠
this.anchorsPreset = "default"; // 重置锚点预设
// 创建 元素的渲染函数
this.r = h(Loop, {
model: props.model,
graphModel: props.graphModel,
properties: {
...props.model.getProperties(),
},
onAddToGroup: this.addChild.bind(this),
onContentChange: this.handleContentChange.bind(this),
onBindRef: this.handleComponentInstance.bind(this)
});
// 创建 Vue 应用实例,并指定渲染函数
this.app = createApp({
render: () => this.r,
});
}
addChild(data) {
this.addToGroup(data);
}
handleComponentInstance(data) {
// 将组件实例保存到节点模型
this.props.model.setComponentInstance(data)
}
handleContentChange() {
// 内容变化时强制更新尺寸
this.props.model.updateSize();
}
// 关键修改重写getShape方法
getShape() {
const { model } = this.props;
const { x, y, width, height } = model;
// 创建自定义HTML内容
const html = super.getShape();
// 创建SVG组包含HTML内容和锚点
return svgH('g', {}, [
// 绘制组节点背景
svgH('rect', {
x: x - width / 2,
y: y - height / 2,
width,
height,
stroke: '#88f',
strokeWidth: 0,
strokeDasharray: '5,5',
fill: 'rgba(136, 136, 255, 0.1)',
rx: 4,
ry: 4
}),
// 添加HTML内容
html,
// 渲染锚点
this.getAnchorShapes()
]);
}
// 创建锚点元素
getAnchorShapes() {
const { model } = this.props;
const anchors = model.anchors || [];
const anchorShapes = anchors.map((offset, index) => {
const {x, y } = offset
return svgH('circle', {
cx: x,
cy: y,
r: 7,
hover: { fill: "#FF5722" }, // 禁用悬停变色
fill: '#FF5722',
stroke: '#FF5722',
strokeWidth: 0,
className: 'lf-node-anchor',
cursor: 'crosshair',
'data-anchor-id': `anchor_${index}`
});
});
return svgH('g', {}, anchorShapes);
}
/**
* HTML 内容设置到指定的根元素上
* @param rootEl 根元素
*/
async setHtml(rootEl) {
const nodeId = this.props.model.id;
if (loopBodyView.reusePool.has(nodeId)) {
rootEl.appendChild(loopBodyView.reusePool.get(nodeId));
return;
}
if (!this.isMounted) {
this.isMounted = true;
this.container = document.createElement("div");
// this.container.style.display = "inline-block"; // 关键:确保容器自适应内容
this.container.style.width = "100%"; // 关键:确保容器自适应内容
this.container.style.height = "100%"; // 关键:确保容器自适应内容
rootEl.appendChild(this.container);
this.app.use(ElementPlus); // 关键单独注册ElementPlus
this.app.mount(this.container);
loopBodyView.reusePool.set(nodeId, this.container);
} else {
this.r.component.props.properties = this.props.model.getProperties();
}
}
addToGroup(childId) {
const groupModel = lf.getNodeModelById(this.props.model.id);
groupModel.addChild(childId);
groupModel.updateSize()
}
}
// 导出方法注册
export function registerLoopBodyNode(lf) {
lf.register({
type: "loop",
view: loopBodyView,
model: loopBodyModel,
});
}

View File

@ -35,6 +35,7 @@
>
<el-input
:disabled="index === 0"
class="param-name"
v-model="property.name"
placeholder="请输入"
clearable
@ -45,6 +46,7 @@
:prop="`nodeParams.${index}.type`"
>
<el-select
class="param-type"
v-model="property.type"
@change="handleTypeChange(index)"
>
@ -63,6 +65,7 @@
:prop="`nodeParams.${index}.input`"
>
<el-input-number
class="param-value"
v-model="property.input"
:min="0"
:controls="false"
@ -83,6 +86,7 @@
:prop="`nodeParams.${index}.quote`"
>
<el-cascader
class="param-value"
:ref="
(el) => {
if (el) cascaderRefs[index] = el;
@ -116,7 +120,7 @@
</div>
</template>
<script setup>
import { ref, onMounted, nextTick } from "vue";
import { ref, onMounted } from "vue";
import NodeTitle from "../../components/NodeTitle.vue";
import loop from "../../icon/loop.svg";
import { useFlowStore } from "@/store/modules/flow";
@ -284,21 +288,25 @@ onMounted(() => {
:deep(.loop__container) {
height: auto;
.el-row {
align-items: end;
.el-input {
width: 240px;
}
.el-form-item {
margin-right: 12px;
}
.param-name {
width: 120px;
}
.el-input-number {
width: 92px;
}
.param-type {
width: 80px;
}
.el-select {
width: 120px;
}
.el-cascader {
width: 240px;
.param-desc {
width: 120px;
}
}
}