feat:新增获取当前循环对象节点

This commit is contained in:
zhanghao 2026-03-17 16:30:40 +08:00
parent e5c34df09d
commit 0d70a0ff03
8 changed files with 730 additions and 20 deletions

View File

@ -1,17 +1,17 @@
export const getInput = (nodeId, isStrict = true) => { export const getInput = (nodeId, isStrict = true) => {
const data = lf.getGraphData(); const data = lf.getGraphData();
let flag = false // let flag = false
if (isStrict) { // if (isStrict) {
data.edges.forEach(item => { // data.edges.forEach(item => {
if (item.targetNodeId === nodeId) { // if (item.targetNodeId === nodeId) {
flag = true // flag = true
} // }
}); // });
} else { // } else {
flag = true // flag = true
} // }
if (flag) { // if (flag) {
const arr = [] const arr = []
const filterNodes = ['sleep', 'stopLoop', 'subEnd', 'subStart', 'branch', 'end'] const filterNodes = ['sleep', 'stopLoop', 'subEnd', 'subStart', 'branch', 'end']
data.nodes.forEach(item => { data.nodes.forEach(item => {
@ -51,8 +51,8 @@ export const getInput = (nodeId, isStrict = true) => {
arr.push(obj) arr.push(obj)
}) })
return arr return arr
} // }
return flag // return flag
} }
const transformTree = (arr, parent = [], type) => { const transformTree = (arr, parent = [], type) => {

View File

@ -216,7 +216,7 @@ const loadRobot = async () => {
// 4. // 4.
robot.rotation.x = -Math.PI / 2 robot.rotation.x = -Math.PI / 2
robot.rotation.z = -Math.PI / 2 robot.rotation.z = Math.PI / 2
robot.updateMatrixWorld(true) robot.updateMatrixWorld(true)
// //

View File

@ -226,7 +226,7 @@ export const collapseList = [
{ name: "deviceId", type: "input", input: "", componentType: 'select', selectOptions: deviceOptions(), disabled: true } { name: "deviceId", type: "input", input: "", componentType: 'select', selectOptions: deviceOptions(), disabled: true }
], ],
outputType: 'video', outputType: 'video',
outputParams: [{ name: 'videoUrl', type: 'array<string>', children: [], desc: '视频播放地址数组'}] outputParams: [{ name: 'videoUrl', type: 'array<string>', children: [], desc: '视频播放地址数组', disabled: true}]
} }
], ],
}, },
@ -293,7 +293,7 @@ export const collapseList = [
{ name: "body", type: "input", input: "", disabled: true, required: true }, { name: "body", type: "input", input: "", disabled: true, required: true },
], ],
outputType: 'json', outputType: 'json',
outputParams: [{ name: 'result', type: 'Object', children: [], desc: 'HTTP请求结果'}] outputParams: [{ name: 'result', type: 'Object', children: [], desc: 'HTTP请求结果', disabled: true}]
}, },
{ {
icon: expressionSvg, icon: expressionSvg,
@ -306,8 +306,24 @@ export const collapseList = [
{ name: "input", type: "input", input: "", required: true } { name: "input", type: "input", input: "", required: true }
], ],
outputType: 'json', outputType: 'json',
outputParams: [{ name: 'ret', type: 'Object', children: [], desc: 'js节点返回'}] outputParams: [{ name: 'ret', type: 'Object', children: [], desc: 'js节点返回', disabled: true}]
} },
{
icon: microphoneSvg,
name: "获取当前循环对象",
type: "currentLoop",
desc: "获取当前循环对象",
action: 'GET_CURRENT_OBJECT',
nodeType: 'getCurrentObject',
nodeParams: [
{ name: "array", type: "input", input: "", disabled: true }
],
outputType: 'json',
outputParams: [
{ name: 'index', type: 'number', desc: '索引', disabled: true},
{ name: 'object', type: 'Object', children: [], desc: '当前循环对象', disabled: true}
]
},
], ],
}, },
{ {
@ -382,7 +398,7 @@ export const collapseList = [
{ name: "vehType", type: "input", input: "su7", disabled: true }, { name: "vehType", type: "input", input: "su7", disabled: true },
], ],
outputType: 'json', outputType: 'json',
outputParams: [{ name: 'coordinates', type: 'Object', children: [], desc: '坐标对象'}] outputParams: [{ name: 'coordinates', type: 'Object', children: [], desc: '坐标对象', disabled: true}]
}, { }, {
icon: dialogueSvg, icon: dialogueSvg,
name: "tts语音合成", name: "tts语音合成",

View File

@ -211,7 +211,7 @@ const dragover = (e) => {
const drop = (e) => { const drop = (e) => {
let node = e.dataTransfer.getData("flowNode"); let node = e.dataTransfer.getData("flowNode");
node = JSON.parse(node); node = JSON.parse(node);
if (["stopLoop", "subEnd", "subStart"].includes(node.type)) { if (["stopLoop", "subEnd", "subStart", "current"].includes(node.type)) {
ElMessage.warning("此节点只能拖拽到循环节点的循环体中"); ElMessage.warning("此节点只能拖拽到循环节点的循环体中");
return; return;
} }

View File

@ -0,0 +1,460 @@
<template>
<div class="node__container" :class="props.model.id">
<NodeState :state="nodeOperatingStatus">
<template #input>
<JsonViewer :value="inputJsonData" copyable boxed sort theme="light" />
</template>
<template #output>
<JsonViewer v-if="props.properties.outputType === 'json'" :value="outputJsonData" copyable boxed sort theme="light" />
<el-image
v-if="props.properties.outputType === 'img'"
v-for="item in outputJsonData.imageUrl"
style="width: 60px; height: 60px"
:src="item"
:preview-src-list="outputJsonData.imageUrl"
:preview-teleported="true"
show-progress
fit="fill"
/>
<IPlayer v-if="props.properties.outputType === 'video'" v-for="item in outputJsonData.videoUrl" :videoUrl="item" />
</template>
</NodeState>
<NodeTitle
:icon="props.properties.icon"
:nodeId="props.model.id"
:nodeProperties="props.properties"
: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>
<script setup>
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";
import { emitter } from "@/utils/eventBus";
import IPlayer from "@/views/device/register/components/LogicFlow/IPlayer/index.vue";
const props = defineProps({
model: Object,
properties: Object,
});
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);
lf.setProperties(props.model.id, {
...properties,
name
});
emits("contentChange");
}
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) {
nodeOperatingStatus.value = data.status;
let inputData = {};
let output = {};
try {
inputData = JSON.parse(data.paramsIn) || {};
output = JSON.parse(data.paramsOut) || {};
} catch (error) {
inputData = data.paramsIn || {};
output = data.paramsOut || {};
}
inputJsonData.value = inputData;
outputJsonData.value = output;
emits("contentChange");
}
});
emitter.on("contentChange", (data) => {
if (data.id === props.model.id) {
nodeOperatingStatus.value = "NORMAL";
inputJsonData.value = {};
outputJsonData.value = {};
emits("contentChange");
}
});
});
onUnmounted(() => {
emitter.off("changeNodeState");
emitter.off("contentChange");
});
defineExpose({
validateForm,
setNodeProperties,
});
</script>
<style lang="scss" scoped>
.node__container {
width: 100%;
height: auto;
.input__container {
width: 100%;
background-color: #fafbfc;
padding: 0 16px;
border-radius: 8px;
box-sizing: border-box;
.title {
height: 32px;
display: flex;
align-items: center;
justify-content: space-between;
.left {
display: flex;
align-items: center;
.tag {
width: 3px;
height: 16px;
background: #1664ff;
border-radius: 0 4px 4px 0;
margin-right: 12px;
}
.text {
font-size: 16px;
font-weight: 700;
color: #0c0d0e;
}
}
.right {
.addFormItem {
border: none;
background: transparent;
cursor: pointer;
}
}
}
.form__container {
margin: 12px 0;
.sub-properties {
margin-left: 10px;
.zw {
margin-left: 15px;
&::before {
content: "";
position: absolute;
left: 0;
top: -4px;
width: 10px;
border-left: 1px solid gray;
border-bottom: 1px solid gray;
border-bottom-left-radius: 4px;
background-color: transparent;
height: 24px;
}
}
}
.gSon-properties {
margin-left: 10px;
.zw {
margin-left: 15px;
&::before {
content: "";
position: absolute;
left: 0;
top: -4px;
width: 10px;
border-left: 1px solid gray;
border-bottom: 1px solid gray;
border-bottom-left-radius: 4px;
background-color: transparent;
height: 24px;
}
}
}
}
}
.output__container {
width: 100%;
background-color: #fafbfc;
padding: 0 16px;
border-radius: 8px;
box-sizing: border-box;
.title {
height: 32px;
display: flex;
align-items: center;
.tag {
width: 3px;
height: 16px;
background: #1664ff;
border-radius: 0 4px 4px 0;
margin-right: 12px;
}
.text {
font-size: 16px;
font-weight: 700;
color: #0c0d0e;
}
}
.form__container {
margin: 12px 0;
}
}
:deep(.el-row) {
align-items: end;
.el-input {
--el-input-width: 170px;
}
.el-select {
--el-select-width: 170px;
}
.el-cascader {
--el-form-inline-content-width: 170px;
}
}
}
</style>

View File

@ -0,0 +1,219 @@
// 导入 HtmlNode 及其模型,为后续继承做准备
import { HtmlNode, HtmlNodeModel } from "@logicflow/core";
// 导入 Vue 相关方法,用于渲染组件
import { createApp, h, nextTick } from "vue";
import ElementPlus from "element-plus";
// 导入 Vue 组件
// @ts-ignore
import CurrentLoop from "./currentLoop.vue";
import OuterNode from "../../components/OuterNode.vue";
import JsonViewer from 'vue3-json-viewer'
/**
* 定义一个 元素的 HTML 节点类继承自 HtmlNode
* 该类负责在 HTML 中渲染 元素并处理其交互逻辑
*/
class CurrentLoopNodeHtmlNode 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(OuterNode, {
model: props.model,
component: CurrentLoop,
properties: {
...props.model.getProperties(),
},
onContentChange: this.handleContentChange.bind(this),
onBindRef: this.handleComponentInstance.bind(this)
});
// 创建 Vue 应用实例,并指定渲染函数
this.app = createApp({
render: () => this.r,
});
}
/**
* HTML 内容设置到指定的根元素上
* @param rootEl 根元素
*/
async setHtml(rootEl) {
const nodeId = this.props.model.id;
if (CurrentLoopNodeHtmlNode.reusePool.has(nodeId)) {
rootEl.appendChild(CurrentLoopNodeHtmlNode.reusePool.get(nodeId));
return;
}
if (!this.isMounted) {
this.isMounted = true;
this.container = document.createElement("div");
this.container.style.display = "inline-block"; // 关键:确保容器自适应内容
rootEl.appendChild(this.container);
this.app.use(ElementPlus);
this.app.use(JsonViewer);
this.app.mount(this.container);
await nextTick();
this.setupSizeObserver();
CurrentLoopNodeHtmlNode.reusePool.set(nodeId, this.container);
} else {
this.r.component.props.properties = this.props.model.getProperties();
}
}
/**
* 获取节点文本内容
* 对于元素返回 null因为其内容由特定组件渲染
* @returns {null}
*/
getText() {
return null;
}
handleComponentInstance(data) {
// 将组件实例保存到节点模型
this.props.model.setComponentInstance(data)
}
handleContentChange() {
// 内容变化时强制更新尺寸
this.updateNodeSize();
}
// 渲染完成后获取实际尺寸
updateNodeSize() {
if (this.container) {
const { SCALE_X, SCALE_Y } = this.props.graphModel.transformModel;
const node = this.container.querySelector(".node__container");
const rect = node.getBoundingClientRect();
this.props.model.updateSize(rect.width / SCALE_X, rect.height / SCALE_Y);
}
}
setupSizeObserver() {
// 首次渲染立即检测
requestAnimationFrame(() => {
this.updateNodeSize();
// 持续监听变化
this.resizeObserver = new ResizeObserver(() => {
this.updateNodeSize();
});
this.resizeObserver.observe(this.container);
});
}
// 组件卸载时移除监听
onDestroy() {
this.resizeObserver?.disconnect();
}
}
/**
* 定义一个元素的 HTML 模型类继承自 HtmlNodeModel
* 该类主要设置节点的属性和样式
*/
class CurrentLoopNodeHtmlModel extends HtmlNodeModel {
initNodeData(data) {
super.initNodeData(data);
}
// 保存组件实例引用
setComponentInstance(instance) {
this.componentInstance = instance;
}
// 验证表单
async validateForm() {
const result = this.componentInstance.validateForm()
return result
}
setCustomProperties() {
this.componentInstance.setNodeProperties()
}
/**
* 设置节点属性
* 包括宽度高度文本编辑属性等
*/
setAttributes() {
// 初始设置为0后续动态更新
this.width = 0;
this.height = 0;
this.text.editable = false;
}
updateSize(width, height) {
this.width = width + 24;
this.height = height + 50;
this.initNodeData(this); // 触发节点重绘
}
// 定义节点只有左右两个锚点. 锚点位置通过中心点和宽度算出来。
getDefaultAnchor() {
let _a = this,
x = _a.x,
y = _a.y,
width = _a.width,
height = _a.height;
return [
{
x: x + width / 2 + 4,
y: y,
name: "right",
id: "".concat(this.id, "_1"),
properties: { connectionType: "source" },
},
{
x: x - width / 2,
y: y,
name: "left",
id: "".concat(this.id, "_3"),
properties: { connectionType: "target" },
},
];
}
/**
* 获取节点轮廓样式
* 覆盖父类方法设置 stroke 属性为 none以适应特定的视觉效果
* @returns {object} 节点轮廓样式
*/
getOutlineStyle() {
const style = super.getOutlineStyle();
style.stroke = "none";
style.hover.stroke = "none";
return style;
}
}
// 导出方法注册
export function registerCurrentLoopNode(lf) {
lf.register({
type: "currentLoop",
view: CurrentLoopNodeHtmlNode,
model: CurrentLoopNodeHtmlModel
});
}

View File

@ -6,6 +6,7 @@ import { registerSubStartNode } from './subStart'
import { registerSleepNode } from './sleep' import { registerSleepNode } from './sleep'
import { registerHttpNode } from './httpNode' import { registerHttpNode } from './httpNode'
import { registerCodeNode } from './codeNode' import { registerCodeNode } from './codeNode'
import { registerCurrentLoopNode } from './currentLoopNode'
export const registerFunction = (lf) => { export const registerFunction = (lf) => {
registerLoopBodyNode(lf) registerLoopBodyNode(lf)
@ -16,4 +17,5 @@ export const registerFunction = (lf) => {
registerSleepNode(lf) registerSleepNode(lf)
registerHttpNode(lf) registerHttpNode(lf)
registerCodeNode(lf) registerCodeNode(lf)
registerCurrentLoopNode(lf)
} }

View File

@ -94,10 +94,16 @@
:prop="`nodeParams.${index}.quote`" :prop="`nodeParams.${index}.quote`"
> >
<el-cascader <el-cascader
:ref="
(el) => {
if (el) cascaderRefs[index] = el;
}
"
v-model="property.quote" v-model="property.quote"
:options="quoteOptions" :options="quoteOptions"
placeholder="请选择" placeholder="请选择"
@visible-change="visibleChange" @visible-change="visibleChange"
@change="(value) => cascaderChange(value, index)"
/> />
</el-form-item> </el-form-item>
</el-form-item> </el-form-item>
@ -217,6 +223,13 @@ const visibleChange = (value) => {
} }
}; };
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 () => { const validateForm = async () => {
try { try {
const result = await dynamicForm.value.validate(); const result = await dynamicForm.value.validate();