Merge branch 'refactor_flow' into 'dev'

Refactor flow

See merge request smart_bench/cmvr-iot-ui!1
This commit is contained in:
zhang hao 2026-04-17 09:13:16 +08:00
commit 9d3ed51349
32 changed files with 4445 additions and 4680 deletions

View File

@ -1,22 +1,22 @@
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
export const useFlowStore = defineStore('flow', { export const useFlowStore = defineStore('flow', {
state: () => ({ state: () => ({
disableForm: false, disableForm: false,
deviceList: [] deviceList: []
}), }),
actions: { actions: {
updateDisableForm(value) { updateDisableForm(value) {
this.disableForm = value this.disableForm = value
}, },
async getDeviceList() { async getDeviceList() {
const data = await new Promise((resolve, reject) => { const data = await new Promise((resolve, reject) => {
resolve( ['cam1', 'cam2', 'cam3', 'cam4']) resolve( ['cam1', 'cam2', 'cam3', 'cam4'])
}) })
this.deviceList = data this.deviceList = data
return data return data
} }
} }
} }
) )

View File

@ -109,7 +109,7 @@ export const recursiveFilter = (data, id, type = ['loop', 'customGroup'], result
data.forEach((item) => { data.forEach((item) => {
if (type.includes(item.type) && item.children && item.children.includes(id)) { if (type.includes(item.type) && item.children && item.children.includes(id)) {
result.push(item) result.push(item)
recursiveFilter(data, item.id, result) recursiveFilter(data, item.id, type, result)
} }
}); });
return result return result
@ -262,5 +262,109 @@ export const convertToTree = (data) => {
} }
}); });
return result;
}
export const filterEmptyName = (obj) => {
// 1. 如果是数组,遍历每一项递归处理
if (Array.isArray(obj)) {
return obj
.map(item => filterEmptyName(item)) // 先递归处理子项
.filter(item => item !== null); // 过滤掉被剔除的空项
}
// 2. 如果是对象,先检查 name 是否为空,为空直接返回 null剔除
if (typeof obj === 'object' && obj !== null) {
// 核心name 为空字符串 → 直接剔除这个对象
if (obj.name === '') {
return null;
}
// 创建新对象,保留原有属性
const newObj = { ...obj };
// 如果有 children递归过滤子节点
if (newObj.children && Array.isArray(newObj.children)) {
newObj.children = filterEmptyName(newObj.children);
}
return newObj;
}
// 基础类型直接返回
return obj;
}
/**
* 将原始表单配置数组 转换为 目标对象格式
* @param {Array} source - 原始数据数组
* @returns {Object} 转换后的目标格式对象
*/
export const transformHttpNodeData = (source) => {
// 初始化结果对象
const result = {};
// 遍历每一个顶级节点
source.forEach(item => {
const { name, children } = item;
if (!name) return; // 过滤无name的无效节点
// 处理普通节点config/headers/params直接取 children 数组
if (name !== 'body') {
result[name] = children || [];
return;
}
// 专门处理 body 节点(特殊结构)
if (name === 'body') {
const bodyObj = {
type: '',
json: '',
formData: []
};
// 遍历body的子项赋值到对应字段
children?.forEach(child => {
const childName = child.name;
if (childName === 'bodyType') {
bodyObj.type = child.input;
}
if (childName === 'json') {
bodyObj.json = child.input;
}
if (childName === 'formData') {
bodyObj.formData = child.children || [];
}
});
result.body = bodyObj;
}
});
return result;
}
export const transformSdAgentNodeData = (source) => {
// 初始化结果对象
const result = {};
// 遍历每一个顶级节点
source.forEach(item => {
const { name, children } = item;
if (!name) return; // 过滤无name的无效节点
// 处理普通节点config/headers/params直接取 children 数组
if (name !== 'invokeTts') {
result[name] = children || [];
return;
}
// 专门处理 tts 节点(特殊结构)
if (name === 'invokeTts') {
result.invokeTts = item.input;
}
});
return result; return result;
} }

View File

@ -6,12 +6,12 @@
<el-row> <el-row>
<!-- 名称输入 --> <!-- 名称输入 -->
<el-form-item <el-form-item
:label="isFirstLevel && index === 0 ? '参数名' : ''" :label="isFirstLevel && index === 0 ? '变量名' : ''"
:prop="`${propPath}.${index}.name`" :prop="`${propPath}.${index}.name`"
:rules="[{ required: true, message: '请输入', trigger: 'blur' }]" :rules="[{ required: true, message: '请输入', trigger: 'blur' }]"
> >
<el-input <el-input
:disabled="item.disabled" class="param-name"
v-model="item.name" v-model="item.name"
placeholder="请输入" placeholder="请输入"
clearable clearable
@ -20,13 +20,13 @@
<!-- 类型选择 --> <!-- 类型选择 -->
<el-form-item <el-form-item
:label="isFirstLevel && index === 0 ? '参数类型' : ''" :label="isFirstLevel && index === 0 ? '变量类型' : ''"
:prop="`${propPath}.${index}.type`" :prop="`${propPath}.${index}.type`"
:rules="[{ required: true, message: '请输入', trigger: 'blur' }]" :rules="[{ required: true, message: '请输入', trigger: 'blur' }]"
> >
<el-select <el-select
:disabled="item.disabled"
v-model="item.type" v-model="item.type"
class="param-type"
@change="handleTypeChange(item)" @change="handleTypeChange(item)"
> >
<el-option label="String" value="string" /> <el-option label="String" value="string" />
@ -47,7 +47,7 @@
:rules="[{ required: true, message: '请输入', trigger: 'blur' }]" :rules="[{ required: true, message: '请输入', trigger: 'blur' }]"
> >
<el-input <el-input
:disabled="item.disabled" class="param-desc"
v-model="item.desc" v-model="item.desc"
placeholder="请输入" placeholder="请输入"
clearable clearable
@ -57,14 +57,12 @@
<!-- 是否必填 --> <!-- 是否必填 -->
<el-form-item v-if="formType === 'input'" :label="isFirstLevel && index === 0 ? '必填' : ''"> <el-form-item v-if="formType === 'input'" :label="isFirstLevel && index === 0 ? '必填' : ''">
<el-switch <el-switch
:disabled="item.disabled"
v-model="item.required" v-model="item.required"
/> />
</el-form-item> </el-form-item>
<!-- 删除按钮第一层第一个不能删 --> <!-- 删除按钮第一层第一个不能删 -->
<el-button <el-button
v-if="!item?.disabled"
:icon="Minus" :icon="Minus"
circle circle
size="small" size="small"
@ -160,7 +158,7 @@ const handleTypeChange = (item) => {
const handleAddChild = (parentItem) => { const handleAddChild = (parentItem) => {
parentItem.children.push({ parentItem.children.push({
name: "", name: "",
type: "", type: "string",
desc: "", desc: "",
required: false, required: false,
children: [], children: [],
@ -184,7 +182,8 @@ const handleChildDelete = (childFullPath) => {
<style lang="scss" scoped> <style lang="scss" scoped>
.nested-form-items { .nested-form-items {
border-left: 1px dashed #ccc; /* 层级连接线 */ border-left: 1px dashed #ccc; /* 层级连接线 */
padding-left: 16px; padding-left: 12px;
margin-left: 0 !important;
margin-top: 8px; margin-top: 8px;
margin-bottom: 8px; margin-bottom: 8px;
} }
@ -201,17 +200,22 @@ const handleChildDelete = (childFullPath) => {
:deep(.el-row) { :deep(.el-row) {
align-items: end; align-items: end;
.el-form-item {
margin-right: 12px;
}
.el-input { .param-name {
--el-input-width: 140px; width: 120px;
} }
.el-select { .param-type {
--el-select-width: 140px; width: 80px;
} }
.el-cascader { .param-desc {
--el-form-inline-content-width: 140px; width: 120px;
} }
} }
</style> </style>

View File

@ -1,151 +1,176 @@
<template> <template>
<div> <div>
<div class="state__container" :class="`nodeState-${props.state}`"> <div class="state__container" :class="`nodeState-${props.state}`">
<div class="context"> <div class="context" v-show="showState !== 'NORMAL'">
<div class="state"> <div class="state">
<el-icon> <el-icon>
<SuccessFilled v-if="props.state === 'SUCCESS'" /> <SuccessFilled v-if="props.state === 'SUCCESS'" />
<CircleCloseFilled v-if="['FAILED', 'STOPPED'].includes(props.state)" /> <CircleCloseFilled v-if="['FAILED', 'STOPPED'].includes(props.state)" />
<VideoPause v-if="props.state === 'PAUSED'" /> <VideoPause v-if="props.state === 'PAUSED'" />
<Loading v-if="props.state === 'RUNNING'" /> <Loading v-if="props.state === 'RUNNING'" />
</el-icon> </el-icon>
<div class="text">{{ getStateText() }}</div> <div class="text">{{ getStateText() }}</div>
</div> <el-tag :type="props.state === 'SUCCESS' ? 'success' : 'danger'">
<div class="resultText" v-popover="popoverRef" @click="popoverVisible = !popoverVisible">{{ popoverVisible ? '隐藏结果' : '展示结果' }}</div> {{ props.runtimes }}ms
</div> </el-tag>
</div> </div>
<div
<el-popover class="resultText"
ref="popoverRef" v-popover="popoverRef"
virtual-triggering @click="popoverVisible = !popoverVisible"
persistent >
placement="right-start" {{ popoverVisible ? "隐藏结果" : "展示结果" }}
:visible="popoverVisible" </div>
:teleported="false" </div>
popper-class="popover__container" </div>
>
<template #default> <el-popover
<div class="params__container input"> ref="popoverRef"
<div class="paramsTitle">输入</div> virtual-triggering
<div> persistent
<slot name="input"></slot> placement="right-start"
</div> :visible="popoverVisible"
</div> :teleported="false"
<div class="params__container output" v-if="slots.output"> popper-class="popover__container"
<div class="paramsTitle">输出</div> >
<div> <template #default>
<slot name="output"></slot> <div class="params__container input">
</div> <div class="paramsTitle">输入</div>
</div> <div>
</template> <slot name="input"></slot>
</el-popover> </div>
</div> </div>
</template> <div class="params__container output" v-if="slots.output">
<script setup lang="js"> <div class="paramsTitle">输出</div>
import { ref, useSlots } from 'vue' <div>
import { SuccessFilled, CircleCloseFilled, Loading, VideoPause } from '@element-plus/icons-vue' <slot name="output"></slot>
</div>
const props = defineProps({ </div>
state: { </template>
type: String, </el-popover>
default: 'NORMAL' </div>
} </template>
}) <script setup lang="js">
import { ref, useSlots, watch } from 'vue'
const slots = useSlots() import { SuccessFilled, CircleCloseFilled, Loading, VideoPause } from '@element-plus/icons-vue'
const getStateText = () => { const props = defineProps({
const map = { state: {
SUCCESS: '成功', type: String,
RUNNING: '运行中', default: 'NORMAL'
FAILED: '失败', },
PAUSED: '已暂停', runtimes: {
STOPPED: '已停止', type: Number,
NORMAL: '' default: 0
} },
return map[props.state] })
}
const slots = useSlots()
const popoverRef = ref();
const popoverVisible = ref(false); const getStateText = () => {
const map = {
</script> SUCCESS: '成功',
<style lang="scss" scoped> RUNNING: '运行中',
.state__container { FAILED: '失败',
display: none; PAUSED: '已暂停',
margin-bottom: 8px; STOPPED: '已停止',
NORMAL: ''
.context { }
display: flex; return map[props.state]
align-items: center; }
justify-content: space-between;
padding: 4px; const popoverRef = ref();
font-size: 12px; const popoverVisible = ref(false);
.state { const showState = ref('NORMAL')
display: flex;
align-items: center; watch(() => props.state, (newVal) => {
showState.value = newVal;
.text { });
margin: 0 8px;
} const closePopover = () => {
} showState.value = 'NORMAL';
popoverVisible.value = false;
.resultText { };
color: #1664ff;
cursor: pointer; defineExpose({ closePopover })
} </script>
} <style lang="scss" scoped>
} .state__container {
display: none;
.nodeState-SUCCESS { margin-bottom: 8px;
display: block;
background-color: #eef9f1; .context {
display: flex;
.el-icon { align-items: center;
font-size: 16px; justify-content: space-between;
color: #309256; padding: 4px;
} font-size: 12px;
}
.state {
.nodeState-FAILED { display: flex;
display: block; align-items: center;
background-color: #fdf5f5;
.text {
.el-icon { margin: 0 8px;
font-size: 16px; }
color: #ee3f38; }
}
} .resultText {
color: #1664ff;
.nodeState-STOPPED { cursor: pointer;
display: block; }
background-color: #fdf5f5; }
}
.el-icon {
font-size: 16px; .nodeState-SUCCESS {
color: #ee3f38; display: block;
} background-color: #eef9f1;
}
.el-icon {
.nodeState-PAUSED { font-size: 16px;
display: block; color: #309256;
background-color: #cbcbcb; }
}
.el-icon {
font-size: 16px; .nodeState-FAILED {
color: #666; display: block;
} background-color: #fdf5f5;
}
.el-icon {
.nodeState-RUNNING { font-size: 16px;
display: block; color: #ee3f38;
background-color: #f4f7ff; }
}
.el-icon {
color: #68a2e4; .nodeState-STOPPED {
font-size: 16px; display: block;
animation: rotateAnimation 2s linear infinite; background-color: #fdf5f5;
}
} .el-icon {
</style> font-size: 16px;
color: #ee3f38;
}
}
.nodeState-PAUSED {
display: block;
background-color: #cbcbcb;
.el-icon {
font-size: 16px;
color: #666;
}
}
.nodeState-RUNNING {
display: block;
background-color: #f4f7ff;
.el-icon {
color: #68a2e4;
font-size: 16px;
animation: rotateAnimation 2s linear infinite;
}
}
</style>

View File

@ -6,9 +6,7 @@
<div class="text__container"> <div class="text__container">
<div class="text__title" v-if="showTextTitle"> <div class="text__title" v-if="showTextTitle">
<span class="text">{{ nodeName }}</span> <span class="text">{{ nodeName }}</span>
<el-icon class="editIcon" @click="showTextTitle = false" <el-icon class="editIcon" @click="showTextTitle = false"><EditPen/></el-icon>
><EditPen
/></el-icon>
</div> </div>
<div class="input_name_container" v-else> <div class="input_name_container" v-else>
<el-input v-model="nodeName" @keydown="handleInputKeydown" /> <el-input v-model="nodeName" @keydown="handleInputKeydown" />
@ -44,7 +42,7 @@
</el-icon> </el-icon>
</el-button> </el-button>
</el-tooltip> </el-tooltip>
<el-tooltip <!-- <el-tooltip
class="box-item" class="box-item"
effect="dark" effect="dark"
:content="zoomState ? '缩小' : '放大'" :content="zoomState ? '缩小' : '放大'"
@ -56,7 +54,7 @@
<ZoomIn v-else /> <ZoomIn v-else />
</el-icon> </el-icon>
</el-button> </el-button>
</el-tooltip> </el-tooltip> -->
<el-tooltip <el-tooltip
class="box-item" class="box-item"
effect="dark" effect="dark"
@ -213,6 +211,7 @@ const imageUrl = () => {
.el-input { .el-input {
margin-left: 12px; margin-left: 12px;
width: 120px;
} }
.input_name_select { .input_name_select {

View File

@ -1,43 +1,43 @@
<template> <template>
<div class="node__box"> <div class="node__box">
<component :is="componentId" :model="props.model" :properties="props.properties" ref="nodeRef" @contentChange="contentChange"></component> <component :is="componentId" :model="props.model" :properties="props.properties" ref="nodeRef" @contentChange="contentChange"></component>
</div> </div>
</template> </template>
<script setup> <script setup>
import { onMounted, ref } from 'vue' import { onMounted, ref } from 'vue'
// import ArmNode from '../nodes/mechanical/arm.vue'; // import ArmNode from '../nodes/mechanical/arm.vue';
const props = defineProps({ const props = defineProps({
model: Object, model: Object,
properties: Object, properties: Object,
component: Object, component: Object,
}); });
const emits = defineEmits(['contentChange', 'bindRef']) const emits = defineEmits(['contentChange', 'bindRef'])
const componentId = ref(props.component) const componentId = ref(props.component)
const contentChange = () => { const contentChange = () => {
emits('contentChange') emits('contentChange')
} }
const nodeRef = ref() const nodeRef = ref()
onMounted(() => { onMounted(() => {
emits('bindRef', nodeRef.value) emits('bindRef', nodeRef.value)
}) })
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.node__box { .node__box {
width: 680px; width: 320px;
height: auto; height: auto;
background: #fff; background: #fff;
padding: 12px; padding: 12px;
cursor: default; cursor: default;
border-radius: 12px; border-radius: 12px;
border: 2px solid white; border: 2px solid white;
box-shadow: 0 5px 15px 0#00000008; box-shadow: 0 5px 15px 0#00000008;
position: relative; position: relative;
} }
</style> </style>

File diff suppressed because it is too large Load Diff

View File

@ -171,6 +171,7 @@ export const collapseList = [
nodeParams: [ nodeParams: [
{ name: "deviceId", type: "input", input: "", componentType: 'select', selectOptions: deviceOptions(), disabled: true } { name: "deviceId", type: "input", input: "", componentType: 'select', selectOptions: deviceOptions(), disabled: true }
], ],
outputParams: [],
outputType: 'json' outputType: 'json'
}, },
{ {
@ -196,6 +197,7 @@ export const collapseList = [
nodeParams: [ nodeParams: [
{ name: "deviceId", type: "input", input: "", componentType: 'select', selectOptions: deviceOptions(), disabled: true } { name: "deviceId", type: "input", input: "", componentType: 'select', selectOptions: deviceOptions(), disabled: true }
], ],
outputParams: [],
outputType: 'json' outputType: 'json'
}, },
], ],
@ -213,6 +215,7 @@ export const collapseList = [
nodeParams: [ nodeParams: [
{ name: "deviceId", type: "input", input: "", componentType: 'select', selectOptions: deviceOptions(), disabled: true } { name: "deviceId", type: "input", input: "", componentType: 'select', selectOptions: deviceOptions(), disabled: true }
], ],
outputParams: [],
outputType: 'json' outputType: 'json'
}, },
{ {
@ -239,6 +242,9 @@ export const collapseList = [
type: "loop", type: "loop",
action: 'START_LOOP', action: 'START_LOOP',
desc: "实现对列表对象循环执行一系列任务", desc: "实现对列表对象循环执行一系列任务",
nodeParams: [{ name: "loopNum", type: "input", input: null, quote: "" }],
outputParams: [],
outputType: 'json'
}, },
{ {
icon: stopLoopSvg, icon: stopLoopSvg,
@ -247,20 +253,20 @@ export const collapseList = [
action: 'STOP_LOOP', action: 'STOP_LOOP',
desc: "用于立即终止当前所在的循环,跳出循环体", desc: "用于立即终止当前所在的循环,跳出循环体",
}, },
{ // {
icon: startSvg, // icon: startSvg,
name: "单次循环开始", // name: "单次循环开始",
type: "subStart", // type: "subStart",
action: 'SUB_START', // action: 'SUB_START',
desc: "循环体内部工作流的开始节点,开始循环体内部的单次流程", // desc: "循环体内部工作流的开始节点,开始循环体内部的单次流程",
}, // },
{ // {
icon: endSvg, // icon: endSvg,
name: "单次循环结束", // name: "单次循环结束",
type: "subEnd", // type: "subEnd",
action: 'SUB_END', // action: 'SUB_END',
desc: "循环体内部工作流的终止节点,结束循环体内部的单次流程", // desc: "循环体内部工作流的终止节点,结束循环体内部的单次流程",
}, // },
{ {
icon: switchSvg, icon: switchSvg,
name: "分支", name: "分支",
@ -275,8 +281,9 @@ export const collapseList = [
desc: "用于睡眠整个流程,表示延迟多少毫秒", desc: "用于睡眠整个流程,表示延迟多少毫秒",
action: 'sleep', action: 'sleep',
nodeParams: [ nodeParams: [
{ name: "delayMs", type: "input", componentType: 'number', input: "", disabled: true } { name: "delayMs", type: "input", componentType: 'number', input: 0, disabled: true }
], ],
outputParams: [],
outputType: 'json' outputType: 'json'
}, },
{ {
@ -285,12 +292,24 @@ export const collapseList = [
type: "http", type: "http",
desc: "HTTP请求", desc: "HTTP请求",
action: 'HTTP', action: 'HTTP',
nodeType: 'HTTP',
nodeParams: [ nodeParams: [
{ name: "url", type: "input", input: "", disabled: true, required: true }, { name: "config", type: "input", input: "", children: [
{ name: "method", type: "input", input: "POST", componentType: 'select', selectOptions: httpMethodOptions(), disabled: true }, { name: "url", type: "input", input: "", disabled: true, required: true },
{ name: "timeout", type: "input", input: "10000", componentType: 'number', required: false }, { name: "method", type: "input", input: "POST", componentType: 'select', selectOptions: httpMethodOptions(), disabled: true },
{ name: "headers", type: "input", input: "", disabled: true, required: false }, { name: "timeout", type: "input", input: "10000", componentType: 'number', required: false, disabled: true }
{ name: "body", type: "input", input: "", disabled: true, required: true }, ], disabled: true, required: true },
{ name: "headers", type: "input", input: "", children: [
{ name: "", type: "input", input: ""}
], disabled: true, required: true },
{ name: "params", type: "input", input: "", children: [
{ name: "", type: "input", input: ""}
], disabled: true, required: true },
{ name: "body", type: "input", input: "", children: [
{ name: 'bodyType', type: "input", input: "json", disabled: true },
{ name: 'json', type: "input", input: '{}' },
{ name: 'formData', type: "input", input: "", children: []}
], required: true },
], ],
outputType: 'json', outputType: 'json',
outputParams: [{ name: 'result', type: 'Object', children: [], desc: 'HTTP请求结果'}] outputParams: [{ name: 'result', type: 'Object', children: [], desc: 'HTTP请求结果'}]
@ -303,10 +322,24 @@ export const collapseList = [
action: 'CODE', action: 'CODE',
canAddFormItem: true, canAddFormItem: true,
nodeParams: [ nodeParams: [
{ name: "input", type: "input", input: "", required: true } { name: "input", type: "input", input: "", required: true },
{ name: "code", type: "input", input: `
// 方法定义不能修改
function handler(params) {
// 返回值是一个可序列化成 json 的 dict 或 object
const result ={
type: 2,
message: params.input
}
return result
}
`, required: true }
], ],
outputType: 'json', outputType: 'json',
outputParams: [{ name: 'result', type: 'Object', children: [], desc: 'js节点返回'}] outputParams: [{ name: 'result', type: 'object', children: [
{name: 'type', type: 'number', desc: '占位属性'},
{name: 'message', type: 'string', desc: '占位属性'}
], desc: 'js节点返回'}]
}, },
{ {
icon: microphoneSvg, icon: microphoneSvg,
@ -314,14 +347,15 @@ export const collapseList = [
type: "currentLoop", type: "currentLoop",
desc: "获取当前循环对象", desc: "获取当前循环对象",
action: 'GET_CURRENT_OBJECT', action: 'GET_CURRENT_OBJECT',
nodeType: 'getCurrentObject',
nodeParams: [ nodeParams: [
{ name: "array", type: "input", input: "", disabled: true } { name: "array", type: "input", input: "" }
], ],
outputType: 'json', outputType: 'json',
outputParams: [ outputParams: [
{ name: 'index', type: 'number', desc: '索引', disabled: true}, { name: 'index', type: 'number', desc: '索引'},
{ name: 'object', type: 'Object', children: [], desc: '当前循环对象', } { name: 'object', type: 'object', children: [
{ name: 'test', type: 'string', desc: '占位属性' }
], desc: '当前循环对象', }
] ]
}, },
], ],
@ -398,7 +432,10 @@ 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: [
{ name: 'x', type: 'number', desc: 'x坐标' },
{ name: 'y', type: 'number', desc: 'y坐标' }
], desc: '坐标对象', }]
}, { }, {
icon: dialogueSvg, icon: dialogueSvg,
name: "tts语音合成", name: "tts语音合成",
@ -422,14 +459,24 @@ export const collapseList = [
}, { }, {
icon: dialogueSvg, icon: dialogueSvg,
name: "商道智能体", name: "商道智能体",
type: "serviceNode", type: "sdAgent",
desc: "通过apiKey调用商道大模型", desc: "通过apiKey调用商道大模型",
action: 'AI_AGENT_PLATFORM', action: 'AI_AGENT_PLATFORM',
nodeType: "LLM", nodeType: "LLM",
outputType: 'json', outputType: 'json',
nodeParams: [ nodeParams: [
{ name: 'apiKey', type: "input", input: "", disabled: true }, { name: "config", type: "input", input: "", children: [
{ name: 'text', type: "input", input: "", disabled: true } { name: 'apiKey', type: "input", input: "", disabled: true },
{ name: 'text', type: "input", input: "", disabled: true },
]},
{ name: 'invokeTts', type: "input", input: false },
{ name: 'tts', type: "input", input: "", children: [
{ name: 'url', type: "input", input: "", disabled: true },
{ name: 'text', type: "input", input: "", disabled: true },
{ name: 'speed', type: "input", input: "", max: 100, disabled: true },
{ name: 'voice', type: "input", input: "", componentType: 'select', selectOptions: voiceOptions(), disabled: true },
{ name: 'volume', type: "input", input: "", componentType: 'number', max: 100, disabled: true }
], disabled: true }
], ],
outputParams: [{ name: 'result', type: 'string', desc: '商道大模型的返回文案', disabled: true}] outputParams: [{ name: 'result', type: 'string', desc: '商道大模型的返回文案', disabled: true}]
}, { }, {

View File

@ -8,21 +8,15 @@
</div> </div>
<div class="btn__container"> <div class="btn__container">
<div class="btn"> <div class="btn">
<el-tag style="margin-right: 12px;" v-if="['testRunError', 'testRunFinish'].includes(flowState)" :type="flowState === 'testRunFinish' ? 'success' : 'danger'">
{{ totalRunningTime }}ms
</el-tag>
<el-button v-if="['testRunError', 'testRunFinish', 'stop'].includes(flowState)" @click="clearRun">清除上一次运行结果</el-button>
<el-button @click="group">分组</el-button> <el-button @click="group">分组</el-button>
<el-button v-if="flowState !== 'testRunning'" @click="testRun" <el-button v-if="flowState !== 'testRunning'" @click="testRun">试运行</el-button>
>试运行</el-button <el-button v-if="flowState === 'testRunning'" @click="flowPauseFn">暂停</el-button>
> <el-button v-if="flowState === 'pause'" @click="flowResumeFn">恢复</el-button>
<el-button v-if="flowState === 'testRunning'" @click="flowPauseFn" <el-button v-if="['testRunning', 'pause'].includes(flowState)" @click="flowStopFn">终止</el-button>
>暂停</el-button
>
<el-button v-if="flowState === 'pause'" @click="flowResumeFn"
>恢复</el-button
>
<el-button
v-if="['testRunning', 'pause'].includes(flowState)"
@click="flowStopFn"
>终止</el-button
>
</div> </div>
<div class="btn"> <div class="btn">
<el-tooltip <el-tooltip
@ -34,9 +28,7 @@
> >
<el-button type="primary" :disabled="true">发布</el-button> <el-button type="primary" :disabled="true">发布</el-button>
</el-tooltip> </el-tooltip>
<el-button v-else @click="deployFlow" type="primary" <el-button v-else @click="deployFlow" type="primary">发布</el-button>
>发布</el-button
>
<el-popover <el-popover
:width="260" :width="260"
@ -95,6 +87,12 @@
@changeState="changeState" @changeState="changeState"
:flowId="flowInfoData.itemId" :flowId="flowInfoData.itemId"
/> />
<ParamsDrawer
:drawer="showParamsDrawer"
:data="paramsDrawerData"
@close="showParamsDrawer = false"
/>
</div> </div>
<el-dialog v-model="visible" width="500" append-to-body> <el-dialog v-model="visible" width="500" append-to-body>
@ -117,9 +115,7 @@
<el-form-item <el-form-item
:label="index === 0 ? '参数名' : ''" :label="index === 0 ? '参数名' : ''"
:prop="`nodeParams.${index}.name`" :prop="`nodeParams.${index}.name`"
:rules="[ :rules="[{ required: true, message: '请输入参数名', trigger: 'blur' }]"
{ required: true, message: '请输入参数名', trigger: 'blur' },
]"
> >
<el-input <el-input
:disabled="property?.disabled || false" :disabled="property?.disabled || false"
@ -131,9 +127,7 @@
<el-form-item <el-form-item
:label="index === 0 ? '参数值' : ''" :label="index === 0 ? '参数值' : ''"
:prop="`nodeParams.${index}.input`" :prop="`nodeParams.${index}.input`"
:rules="[ :rules="[{ required: true, message: '请输入参数值', trigger: 'blur' }]"
{ required: true, message: '请输入参数值', trigger: 'blur' },
]"
> >
<el-input-number <el-input-number
v-if="property.componentType === 'number'" v-if="property.componentType === 'number'"
@ -170,21 +164,20 @@
<template #footer> <template #footer>
<div class="dialog-footer"> <div class="dialog-footer">
<el-button @click="visible = false">取消</el-button> <el-button @click="visible = false">取消</el-button>
<el-button type="primary" @click="execute"> <el-button type="primary" @click="execute"> 确定 </el-button>
确定
</el-button>
</div> </div>
</template> </template>
</el-dialog> </el-dialog>
</template> </template>
<script setup> <script setup>
import { ref, onMounted, onUnmounted, nextTick } from "vue"; import { ref, onMounted, onUnmounted, nextTick } from "vue";
import LogicFlow, { action } from "@logicflow/core"; import LogicFlow from "@logicflow/core";
import "@logicflow/core/es/index.css"; import "@logicflow/core/es/index.css";
import "@logicflow/core/lib/style/index.css"; import "@logicflow/core/lib/style/index.css";
import "@logicflow/extension/lib/style/index.css"; import "@logicflow/extension/lib/style/index.css";
import { lfConfig, registerCustomizeNode } from "./config"; import { lfConfig, registerCustomizeNode } from "./config";
import TestRun from "./components/TestRun.vue"; import TestRun from "./components/TestRun.vue";
import ParamsDrawer from "./components/ParamsDrawer.vue";
import Aside from "./components/Aside.vue"; import Aside from "./components/Aside.vue";
import { ElMessage } from "element-plus"; import { ElMessage } from "element-plus";
import { useFlowStore } from "@/store/modules/flow"; import { useFlowStore } from "@/store/modules/flow";
@ -196,7 +189,7 @@ import {
flowPause, flowPause,
flowResume, flowResume,
flowStop, flowStop,
flowAction flowAction,
} from "@/api/device/flow"; } from "@/api/device/flow";
import { getDetect } from "@/api/test/detect"; import { getDetect } from "@/api/test/detect";
import { Location } from "@element-plus/icons-vue"; import { Location } from "@element-plus/icons-vue";
@ -217,7 +210,7 @@ const drop = (e) => {
} }
const point = lf.getPointByClient(e.clientX, e.clientY); const point = lf.getPointByClient(e.clientX, e.clientY);
const { type, ...other } = node; const { type, ...other } = node;
lf.addNode({ const newNode = lf.addNode({
type, type,
x: point.canvasOverlayPosition.x, x: point.canvasOverlayPosition.x,
y: point.canvasOverlayPosition.y, y: point.canvasOverlayPosition.y,
@ -225,6 +218,13 @@ const drop = (e) => {
...other, ...other,
}, },
}); });
if (
!["selectArea", "branch", "stopLoop", "subStart", "subEnd"].includes(newNode.type)
) {
showParamsDrawer.value = true;
paramsDrawerData.value = newNode;
}
}; };
const flowStore = useFlowStore(); const flowStore = useFlowStore();
@ -274,22 +274,12 @@ const testRun = async () => {
return; return;
} }
let allValid = true; if (nodeErrorList.value.length > 0) {
for (const node of nodes) { ElMessage.warning("存在参数错误的节点,请检查!");
const nodeModel = lf.getNodeModelById(node.id); return;
if (nodeModel && nodeModel.validateForm) {
const result = await nodeModel.validateForm();
if (!result.valid) {
allValid = false;
}
}
} }
if (allValid) { isOpen.value = true;
isOpen.value = true;
} else {
ElMessage.error("部分节点验证失败,请查看详情");
}
}; };
// //
@ -301,6 +291,8 @@ const flowPauseFn = async () => {
} }
}; };
const totalRunningTime = ref(0);
const flowResumeFn = async () => { const flowResumeFn = async () => {
const res = await flowResume(instId.value); const res = await flowResume(instId.value);
if (res.code === 200) { if (res.code === 200) {
@ -427,14 +419,15 @@ const loopFlowView = async (instId, taskId = null) => {
if (!flowInfoData.value.isLog) { if (!flowInfoData.value.isLog) {
flowStore.updateDisableForm(false); flowStore.updateDisableForm(false);
flowState.value = "testRunFinish"; flowState.value = "testRunFinish";
totalRunningTime.value = arr[arr.length - 1].endTime - arr[0].startTime
} }
} else { } else {
if (!flowInfoData.value.isLog) { if (!flowInfoData.value.isLog) {
if (["PAUSED", "STOPPED"].includes(arr[arr.length - 1]?.status)) { if (["PAUSED", "STOPPED"].includes(arr[arr.length - 1]?.status)) {
flowState.value = flowState.value = arr[arr.length - 1]?.status === "PAUSED" ? "pause" : "stop";
arr[arr.length - 1]?.status === "PAUSED" ? "pause" : "stop";
} else { } else {
flowState.value = "testRunError"; flowState.value = "testRunError";
totalRunningTime.value = arr[arr.length - 1].endTime - arr[0].startTime
flowStore.updateDisableForm(false); flowStore.updateDisableForm(false);
} }
} }
@ -549,10 +542,7 @@ const initFlow = () => {
keys: ["backspace", "delete"], // keys: ["backspace", "delete"], //
callback: () => { callback: () => {
const activeElem = document.activeElement; const activeElem = document.activeElement;
if ( if (activeElem.tagName === "INPUT" || activeElem.tagName === "TEXTAREA") {
activeElem.tagName === "INPUT" ||
activeElem.tagName === "TEXTAREA"
) {
return; // return; //
} }
@ -638,7 +628,19 @@ const initFlow = () => {
lf.on("node:mouseleave", ({ data }) => { lf.on("node:mouseleave", ({ data }) => {
const node = lf.getNodeModelById(data.id); const node = lf.getNodeModelById(data.id);
node.setCustomProperties && node.setCustomProperties(); if (node.setCustomProperties) {
node.setCustomProperties();
}
});
lf.on("node:dbclick", ({ data, e }) => {
if (
["selectArea", "branch", "stopLoop", "subStart", "subEnd"].includes(data.type)
) {
return;
}
showParamsDrawer.value = true;
paramsDrawerData.value = data;
}); });
lfRef.value = lf; lfRef.value = lf;
@ -667,6 +669,8 @@ const group = () => {
} }
}); });
if (children.length === 0) { if (children.length === 0) {
lf.clearSelectElements();
lf.extension.selectionSelect.closeSelectionSelect();
return; return;
} }
let width = maxX - minX + PADDING; let width = maxX - minX + PADDING;
@ -710,58 +714,93 @@ const fitView = () => {
}; };
const nodeName = ref(""); const nodeName = ref("");
const visible = ref(false) const visible = ref(false);
const formData = reactive({ const formData = reactive({
nodeParams: [], nodeParams: [],
}) });
const rules = reactive({}) const rules = reactive({});
const executeForm = ref() const executeForm = ref();
const nodeAction = ref('') const nodeAction = ref("");
const singleNodeExecution = (e) => { const singleNodeExecution = (e) => {
const { name, nodeType, nodeParams, action } = e.detail; const { name, nodeType, nodeParams, action } = e.detail;
nodeName.value = name; nodeName.value = name;
visible.value = true; visible.value = true;
nodeAction.value = action nodeAction.value = action;
if (nodeType === 'EDGE') { if (nodeType === "EDGE") {
formData.nodeParams = [ formData.nodeParams = [
{ {
disabled: true, disabled: true,
input: "", input: "",
name: "terminalId", name: "terminalId",
type: "input" type: "input",
}, },
...nodeParams ...nodeParams,
] ];
} else { } else {
formData.nodeParams = nodeParams formData.nodeParams = nodeParams;
} }
}; };
const execute = async () => { const execute = async () => {
const result = await executeForm.value.validate(); const result = await executeForm.value.validate();
if (result) { if (result) {
const obj = {} const obj = {};
formData.nodeParams.forEach(item => { formData.nodeParams.forEach((item) => {
obj[item.name] = item.input obj[item.name] = item.input;
}) });
const res = await flowAction({ const res = await flowAction({
action: nodeAction.value, action: nodeAction.value,
payload: obj payload: obj,
}) });
if (res.code === 200) { if (res.code === 200) {
ElMessage.success('执行成功') ElMessage.success("执行成功");
} else { } else {
ElMessage.error(res.msg) ElMessage.error(res.msg);
} }
} }
};
const showParamsDrawer = ref(false);
const paramsDrawerData = ref({});
const clearRun = () => {
const { nodes } = lf.getGraphData();
nodes.forEach((item) => {
const node = lf.getNodeModelById(item.id);
if (node.closePopover) {
node.closePopover();
}
});
} }
const nodeErrorList = ref([]);
onMounted(() => { onMounted(() => {
justLoadFlow(); justLoadFlow();
initFlow(); initFlow();
document.addEventListener("singleNodeExecution", singleNodeExecution); document.addEventListener("singleNodeExecution", singleNodeExecution);
registerBeforeUnload(); registerBeforeUnload();
emitter.on("openParamsDrawer", (node) => {
showParamsDrawer.value = true;
paramsDrawerData.value = node;
});
emitter.on("throwAnError", (data) => {
//
const { id, hasError } = data;
const element = document.getElementsByClassName(`node__container ${id}`)[0].parentElement;
if (hasError) {
if (!nodeErrorList.value.includes(id)) {
nodeErrorList.value.push(id);
element.style.background = "#ff00001a";
}
} else {
nodeErrorList.value = nodeErrorList.value.filter((item) => item !== id);
element.style.background = "#fff";
}
});
}); });
const operationEdge = (arr) => { const operationEdge = (arr) => {
@ -772,6 +811,9 @@ const operationEdge = (arr) => {
onUnmounted(() => { onUnmounted(() => {
emitter.off("changeNodeState"); emitter.off("changeNodeState");
emitter.off("openParamsDrawer");
emitter.off("throwAnError");
window.removeEventListener("beforeunload", handleBeforeUnload); window.removeEventListener("beforeunload", handleBeforeUnload);
document.removeEventListener("singleNodeExecution", singleNodeExecution); document.removeEventListener("singleNodeExecution", singleNodeExecution);
}); });
@ -849,8 +891,6 @@ onUnmounted(() => {
} }
} }
} }
</style> </style>
<style lang="scss"> <style lang="scss">
.node-relationship-network-popover { .node-relationship-network-popover {
@ -876,16 +916,16 @@ onUnmounted(() => {
} }
.el-dialog { .el-dialog {
.el-input { .el-input {
width: 200px; width: 200px;
} }
.el-select { .el-select {
width: 200px; width: 200px;
} }
.el-textarea { .el-textarea {
width: 200px width: 200px;
} }
} }
</style> </style>

View File

@ -144,14 +144,8 @@ class ServiceNodeHtmlModel extends HtmlNodeModel {
this.componentInstance = instance; this.componentInstance = instance;
} }
// 验证表单 closePopover() {
async validateForm() { this.componentInstance.closePopover()
const result = this.componentInstance.validateForm()
return result
}
setCustomProperties() {
this.componentInstance.setNodeProperties()
} }
/** /**

View File

@ -1,6 +1,6 @@
<template> <template>
<div class="node__container" :class="props.model.id"> <div class="node__container" :class="props.model.id">
<NodeState :state="nodeOperatingStatus"> <NodeState :state="nodeOperatingStatus" :runtimes="runtimes" ref="nodeStateRef">
<template #input> <template #input>
<JsonViewer :value="inputJsonData" copyable boxed sort theme="light" /> <JsonViewer :value="inputJsonData" copyable boxed sort theme="light" />
</template> </template>
@ -41,192 +41,20 @@
:nodeName="props.properties.name" :nodeName="props.properties.name"
:nodeDesc="props.properties.desc" :nodeDesc="props.properties.desc"
:zoom-state="nodeZoom" :zoom-state="nodeZoom"
@zoom="zoom"
@setNodeName="setNodeName" @setNodeName="setNodeName"
/> />
<div class="input__container" v-show="nodeZoom" @mousedown="(e) => e.stopPropagation()" @keydown="handleInputKeydown"> <!-- @zoom="zoom" -->
<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">
<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"
@keydown="handleInputKeydown"
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: property?.required ?? true,
message: '请输入参数值',
trigger: 'blur',
},
]"
:prop="`nodeParams.${index}.input`"
>
<el-input-number
v-if="property.componentType === 'number'"
v-model="property.input"
:min="0"
:max="property.max || Infinity"
:controls="false"
:step-strictly="true"
placeholder="请输入"
clearable
@keydown="handleInputKeydown"
/>
<el-select
v-model="property.input"
v-else-if="property.componentType === 'select'"
>
<el-option
v-for="item in property.selectOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
<el-input
@keydown="handleInputKeydown"
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"
:checkStrictly="true"
:options="quoteOptions"
placeholder="请选择"
@visible-change="
(visible) => visibleChange(visible, index, property.quote)
"
@change="(value) => cascaderChange(value, index)"
/>
</el-form-item>
</el-form-item>
</el-row>
</div>
</el-form>
</div>
</div>
<div class="output__container" v-show="nodeZoom">
<div v-if="props.properties?.outputParams?.length > 0">
<div class="title">
<div class="left">
<div class="tag"></div>
<div class="text">输出</div>
</div>
<div class="right">
<el-button
:disabled="flowStore.disableForm"
@click="addOutputFormItem"
class="addFormItem"
>
<el-icon :size="20"><Plus /></el-icon>
</el-button>
</div>
</div>
<div class="form__container">
<el-form
:inline="true"
:model="formData"
label-position="top"
label-width="auto"
:rules="outputRules"
ref="outputFormRef"
>
<FormItemRecursive
formType="output"
:current-list="formData.outputParams"
prop-path="outputParams"
:depth="0"
:is-first-level="true"
:endDepth="2"
:parent-path="[]"
@delete-item="deleteTopLevelItem"
/>
</el-form>
</div>
</div>
</div>
</div> </div>
</template> </template>
<script setup> <script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue"; import { ref, onMounted, onUnmounted } 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 NodeTitle from "../../components/NodeTitle.vue";
import NodeState from "../../components/NodeState.vue"; import NodeState from "../../components/NodeState.vue";
import "vue3-json-viewer/dist/index.css"; import "vue3-json-viewer/dist/index.css";
import { emitter } from "@/utils/eventBus"; import { emitter } from "@/utils/eventBus";
import IPlayer from "@/views/device/register/components/LogicFlow/IPlayer/index.vue"; import IPlayer from "@/views/device/register/components/LogicFlow/IPlayer/index.vue";
import FormItemRecursive from "./FormItemRecursive.vue";
const props = defineProps({ const props = defineProps({
model: Object, model: Object,
@ -235,70 +63,6 @@ const props = defineProps({
const emits = defineEmits(["contentChange"]); const emits = defineEmits(["contentChange"]);
const flowStore = useFlowStore();
const formData = reactive({
nodeParams: [],
outputParams: [],
});
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 cascaderRefs = ref([]);
const outputRules = reactive({});
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 addOutputFormItem = () => {
formData.outputParams.push({
name: "",
type: "",
desc: "",
children: [],
});
};
const dynamicForm = ref();
const outputFormRef = ref();
const setNodeProperties = async () => {
try {
const result = await dynamicForm.value.validate();
let flag = true;
if (outputFormRef.value) {
flag = await outputFormRef.value.validate();
}
if (result && flag) {
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 setNodeName = (name) => {
const properties = lf.getProperties(props.model.id); const properties = lf.getProperties(props.model.id);
lf.setProperties(props.model.id, { lf.setProperties(props.model.id, {
@ -309,124 +73,27 @@ const setNodeName = (name) => {
} }
const nodeOperatingStatus = ref("NORMAL"); const nodeOperatingStatus = ref("NORMAL");
const runtimes = ref(0);
const inputJsonData = ref({}); const inputJsonData = ref({});
const outputJsonData = ref({}); const outputJsonData = ref({});
const errorInfoData = ref(''); const errorInfoData = ref('');
const visibleChange = (value, index, quote) => { const nodeStateRef = ref(null);
if (value) {
const option = getInput(props.model.id); const closePopover = () => {
if (option) { if (nodeStateRef.value) {
quoteOptions.value = option; nodeStateRef.value.closePopover();
const currentValue = [...quote];
//
if (cascaderRefs.value[index]) {
// DOMoptions
setTimeout(() => {
//
if (currentValue.length) {
formData.nodeParams[index].quote = [];
//
setTimeout(() => {
formData.nodeParams[index].quote = currentValue;
}, 0);
}
//
// cascaderRefs.value[index].updatePopper();
}, 0);
}
}
} }
};
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 deleteTopLevelItem = (fullPath) => {
//
let currentLevel = formData.outputParams;
//
for (let i = 0; i < fullPath.length - 1; i++) {
const index = fullPath[i];
//
currentLevel = currentLevel[index].children;
}
//
const lastIndex = fullPath[fullPath.length - 1];
currentLevel.splice(lastIndex, 1);
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)
})
}
if (
props.properties.outputParams &&
props.properties.outputParams.length > 0
) {
formData.outputParams = props.properties.outputParams;
}
},
{
immediate: true,
deep: true,
}
);
const handleInputKeydown = (e) => {
// Logic Flow
e.stopPropagation();
// Ctrl+V
if ((e.ctrlKey || e.metaKey) && e.key === "v") {
e.returnValue = true; //
}
};
onMounted(() => { onMounted(() => {
emitter.on("changeNodeState", (data) => { emitter.on("changeNodeState", (data) => {
if (data.nodeId === props.model.id) { if (data.nodeId === props.model.id) {
nodeOperatingStatus.value = data.status; nodeOperatingStatus.value = data.status;
if (data.endTime && data.startTime) {
runtimes.value = data.endTime - data.startTime;
}
let inputData = {}; let inputData = {};
let output = {}; let output = {};
errorInfoData.value = data?.message || '' errorInfoData.value = data?.message || ''
@ -451,168 +118,27 @@ onMounted(() => {
emits("contentChange"); emits("contentChange");
} }
}); });
emitter.on("setProperties", (data) => {
if (data.id === props.model.id) {
emits("contentChange");
}
});
}); });
onUnmounted(() => { onUnmounted(() => {
emitter.off("changeNodeState"); emitter.off("changeNodeState");
emitter.off("contentChange"); emitter.off("contentChange");
emitter.off("setProperties");
}); });
defineExpose({ defineExpose({ closePopover })
validateForm,
setNodeProperties,
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.node__container { .node__container {
width: 100%; width: 100%;
height: auto; 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;
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;
}
}
:deep(.el-row) {
align-items: end;
.el-input {
--el-input-width: 148px;
}
.el-select {
--el-select-width: 148px;
}
.el-cascader {
--el-form-inline-content-width: 148px;
}
}
} }
</style> </style>

View File

@ -1,209 +1,204 @@
// 导入 HtmlNode 及其模型,为后续继承做准备 // 导入 HtmlNode 及其模型,为后续继承做准备
import { HtmlNode, HtmlNodeModel } from '@logicflow/core'; import { HtmlNode, HtmlNodeModel } from '@logicflow/core';
// 导入 Vue 相关方法,用于渲染组件 // 导入 Vue 相关方法,用于渲染组件
import { createApp, h, nextTick } from 'vue'; import { createApp, h, nextTick } from 'vue';
import ElementPlus from 'element-plus' import ElementPlus from 'element-plus'
// 导入 Vue 组件 // 导入 Vue 组件
import StartNode from './startNode.vue'; import StartNode from './startNode.vue';
import OuterNode from "../../components/OuterNode.vue"; import OuterNode from "../../components/OuterNode.vue";
import JsonViewer from 'vue3-json-viewer' import JsonViewer from 'vue3-json-viewer'
/** /**
* 定义一个 元素的 HTML 节点类继承自 HtmlNode * 定义一个 元素的 HTML 节点类继承自 HtmlNode
* 该类负责在 HTML 中渲染 元素并处理其交互逻辑 * 该类负责在 HTML 中渲染 元素并处理其交互逻辑
*/ */
class StartNodeHtmlNode extends HtmlNode { class StartNodeHtmlNode extends HtmlNode {
resizeObserver = null; resizeObserver = null;
isMounted; // 标记组件是否已挂载 isMounted; // 标记组件是否已挂载
r; // 渲染函数 r; // 渲染函数
app; // Vue 应用实例 app; // Vue 应用实例
container = null; container = null;
static reusePool = new Map(); // 节点复用池 static reusePool = new Map(); // 节点复用池
/** /**
* 构造函数 * 构造函数
* @param props 传递给节点的属性包括模型图模型等 * @param props 传递给节点的属性包括模型图模型等
*/ */
constructor(props) { constructor(props) {
super(props); super(props);
this.initVueApp(props) this.initVueApp(props)
} }
initVueApp(props) { initVueApp(props) {
this.isMounted = false; this.isMounted = false;
this.hideAnchor = false; this.hideAnchor = false;
this.autoExpand = true; // 防止锚点被折叠 this.autoExpand = true; // 防止锚点被折叠
this.anchorsPreset = "default"; // 重置锚点预设 this.anchorsPreset = "default"; // 重置锚点预设
// 创建 元素的渲染函数 // 创建 元素的渲染函数
this.r = h(OuterNode, { this.r = h(OuterNode, {
model: props.model, model: props.model,
component: StartNode, component: StartNode,
properties: { properties: {
...props.model.getProperties() ...props.model.getProperties()
}, },
onContentChange: this.handleContentChange.bind(this), onContentChange: this.handleContentChange.bind(this),
onBindRef: this.handleComponentInstance.bind(this) onBindRef: this.handleComponentInstance.bind(this)
}); });
// 创建 Vue 应用实例,并指定渲染函数 // 创建 Vue 应用实例,并指定渲染函数
this.app = createApp({ this.app = createApp({
render: () => this.r render: () => this.r
}); });
} }
/** /**
* HTML 内容设置到指定的根元素上 * HTML 内容设置到指定的根元素上
* @param rootEl 根元素 * @param rootEl 根元素
*/ */
async setHtml(rootEl) { async setHtml(rootEl) {
const nodeId = this.props.model.id; const nodeId = this.props.model.id;
if (StartNodeHtmlNode.reusePool.has(nodeId)) { if (StartNodeHtmlNode.reusePool.has(nodeId)) {
rootEl.appendChild(StartNodeHtmlNode.reusePool.get(nodeId)); rootEl.appendChild(StartNodeHtmlNode.reusePool.get(nodeId));
return; return;
} }
if (!this.isMounted) { if (!this.isMounted) {
this.isMounted = true; this.isMounted = true;
this.container = document.createElement('div'); this.container = document.createElement('div');
this.container.style.display = 'inline-block'; // 关键:确保容器自适应内容 this.container.style.display = 'inline-block'; // 关键:确保容器自适应内容
rootEl.appendChild(this.container); rootEl.appendChild(this.container);
this.app.use(ElementPlus) // 关键单独注册ElementPlus this.app.use(ElementPlus) // 关键单独注册ElementPlus
this.app.use(JsonViewer) this.app.use(JsonViewer)
this.app.mount(this.container); this.app.mount(this.container);
await nextTick(); await nextTick();
this.setupSizeObserver(); this.setupSizeObserver();
StartNodeHtmlNode.reusePool.set(nodeId, this.container); StartNodeHtmlNode.reusePool.set(nodeId, this.container);
} else { } else {
this.r.component.props.properties = this.props.model.getProperties(); this.r.component.props.properties = this.props.model.getProperties();
} }
} }
/** /**
* 获取节点文本内容 * 获取节点文本内容
* 对于元素返回 null因为其内容由特定组件渲染 * 对于元素返回 null因为其内容由特定组件渲染
* @returns {null} * @returns {null}
*/ */
getText() { getText() {
return null; return null;
} }
handleComponentInstance(data) { handleComponentInstance(data) {
// 将组件实例保存到节点模型 // 将组件实例保存到节点模型
this.props.model.setComponentInstance(data) this.props.model.setComponentInstance(data)
} }
handleContentChange() { handleContentChange() {
// 内容变化时强制更新尺寸 // 内容变化时强制更新尺寸
this.updateNodeSize(); this.updateNodeSize();
} }
// 渲染完成后获取实际尺寸 // 渲染完成后获取实际尺寸
updateNodeSize () { updateNodeSize () {
if (this.container) { if (this.container) {
const { SCALE_X, SCALE_Y } = this.props.graphModel.transformModel; const { SCALE_X, SCALE_Y } = this.props.graphModel.transformModel;
const node = this.container.querySelector('.node__box') const node = this.container.querySelector('.node__box')
const rect = node.getBoundingClientRect(); const rect = node.getBoundingClientRect();
this.props.model.updateSize(rect.width / SCALE_X, rect.height / SCALE_Y); this.props.model.updateSize(rect.width / SCALE_X, rect.height / SCALE_Y);
} }
} }
setupSizeObserver() { setupSizeObserver() {
// 首次渲染立即检测 // 首次渲染立即检测
requestAnimationFrame(() => { requestAnimationFrame(() => {
this.updateNodeSize(); this.updateNodeSize();
// 持续监听变化 // 持续监听变化
this.resizeObserver = new ResizeObserver(() => { this.resizeObserver = new ResizeObserver(() => {
this.updateNodeSize(); this.updateNodeSize();
}); });
this.resizeObserver.observe(this.container); this.resizeObserver.observe(this.container);
}); });
} }
// 组件卸载时移除监听 // 组件卸载时移除监听
onDestroy() { onDestroy() {
this.resizeObserver?.disconnect(); this.resizeObserver?.disconnect();
} }
} }
/** /**
* 定义一个元素的 HTML 模型类继承自 HtmlNodeModel * 定义一个元素的 HTML 模型类继承自 HtmlNodeModel
* 该类主要设置节点的属性和样式 * 该类主要设置节点的属性和样式
*/ */
class StartNodeHtmlModel extends HtmlNodeModel { class StartNodeHtmlModel extends HtmlNodeModel {
initNodeData(data) { initNodeData(data) {
super.initNodeData(data); super.initNodeData(data);
} }
// 保存组件实例引用 // 保存组件实例引用
setComponentInstance(instance) { setComponentInstance(instance) {
this.componentInstance = instance; this.componentInstance = instance;
} }
// 验证表单 closePopover() {
async validateForm() { this.componentInstance.closePopover()
const result = this.componentInstance.validateForm() }
return result
} /**
* 设置节点属性
setCustomProperties() { * 包括宽度高度文本编辑属性等
this.componentInstance.setNodeProperties() */
} setAttributes() {
// 初始设置为0后续动态更新
/** this.width = 0;
* 设置节点属性 this.height = 0;
* 包括宽度高度文本编辑属性等 this.text.editable = false;
*/ this.deletable = false; // 关键代码:禁止删除节点
setAttributes() { }
// 初始设置为0后续动态更新
this.width = 0; updateSize(width, height) {
this.height = 0; this.width = width + 24;
this.text.editable = false; this.height = height + 50;
this.deletable = false; // 关键代码:禁止删除节点 this.initNodeData(this); // 触发节点重绘
} }
updateSize(width, height) { // 定义节点只有左右两个锚点. 锚点位置通过中心点和宽度算出来。
this.width = width + 24; getDefaultAnchor() {
this.height = height + 50; let _a = this, x = _a.x, y = _a.y, width = _a.width, height = _a.height;
this.initNodeData(this); // 触发节点重绘 return [
} { x: x + width / 2 - 24, y: y - 25, name: 'right', id: "".concat(this.id, "_1"), properties: { connectionType: 'source' }, onlyAsSource: true },
];
// 定义节点只有左右两个锚点. 锚点位置通过中心点和宽度算出来。 }
getDefaultAnchor() {
let _a = this, x = _a.x, y = _a.y, width = _a.width, height = _a.height; /**
return [ * 获取节点轮廓样式
{ x: x + width / 2 - 24, y: y - 25, name: 'right', id: "".concat(this.id, "_1"), properties: { connectionType: 'source' }, onlyAsSource: true }, * 覆盖父类方法设置 stroke 属性为 none以适应特定的视觉效果
]; * @returns {object} 节点轮廓样式
} */
getOutlineStyle() {
/** const style = super.getOutlineStyle();
* 获取节点轮廓样式 style.stroke = 'none';
* 覆盖父类方法设置 stroke 属性为 none以适应特定的视觉效果 style.hover.stroke = 'none';
* @returns {object} 节点轮廓样式 return style;
*/ }
getOutlineStyle() { }
const style = super.getOutlineStyle();
style.stroke = 'none'; // 导出方法注册
style.hover.stroke = 'none'; export function registerStartNode(lf) {
return style; lf.register({
} type: "start",
} view: StartNodeHtmlNode,
model: StartNodeHtmlModel,
// 导出方法注册 effect: ['status'],
export function registerStartNode(lf) { events: {
lf.register({ remove: (event) => {
type: "start", // 阻止默认的删除事件
view: StartNodeHtmlNode, event.preventDefault();
model: StartNodeHtmlModel, // 可以在此处添加自定义的删除逻辑,例如弹出提示框
events: { alert('此节点不可删除');
remove: (event) => { },
// 阻止默认的删除事件 }
event.preventDefault(); })
// 可以在此处添加自定义的删除逻辑,例如弹出提示框
alert('此节点不可删除');
},
}
})
} }

View File

@ -1,7 +1,7 @@
<template> <template>
<div class="node__container" :class="props.model.id"> <div class="node__container" :class="props.model.id">
<keep-alive> <keep-alive>
<NodeState :state="nodeOperatingStatus"> <NodeState :state="nodeOperatingStatus" :runtimes="runtimes" ref="nodeStateRef">
<template #input> <template #input>
<JsonViewer :value="inputJsonData" copyable boxed sort theme="light" /> <JsonViewer :value="inputJsonData" copyable boxed sort theme="light" />
</template> </template>
@ -16,75 +16,17 @@
<img src="../../icon/start.svg" alt="" /> <img src="../../icon/start.svg" alt="" />
<span class="text">Start</span> <span class="text">Start</span>
</div> </div>
<div class="right">
<el-tooltip
class="box-item"
effect="dark"
:content="nodeZoom ? '缩小' : '放大'"
placement="top"
>
<el-button circle @click="zoom">
<el-icon>
<ZoomOut v-if="nodeZoom" />
<ZoomIn v-else />
</el-icon>
</el-button>
</el-tooltip>
</div>
</div> </div>
<div class="subTitle">工作流的起始节点用于设定启动工作流需要的信息</div> <div class="subTitle">工作流的起始节点用于设定启动工作流需要的信息</div>
</div> </div>
<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">
<el-button
:disabled="flowStore.disableForm"
@click="addFormItem"
class="addFormItem"
>
<el-icon :size="20"><Plus /></el-icon>
</el-button>
</div>
</div>
<div class="form__container">
<el-form
:inline="true"
:model="formData"
:rules="rules"
ref="dynamicForm"
label-position="top"
label-width="auto"
:disabled="flowStore.disableForm"
>
<FormItemRecursive
formType="input"
:current-list="formData.inputParams"
prop-path="inputParams"
:depth="0"
:is-first-level="true"
:endDepth="2"
:parent-path="[]"
@delete-item="deleteTopLevelItem"
/>
</el-form>
</div>
</div>
</div> </div>
</template> </template>
<script setup> <script setup>
import { watch, reactive, toRaw, ref, onMounted, onUnmounted, nextTick } from "vue"; import { ref, onMounted, onUnmounted } from "vue";
import { Plus, ZoomOut, ZoomIn } from "@element-plus/icons-vue";
import { useFlowStore } from "@/store/modules/flow";
import { initNodeZoom } from "@/utils/flow";
import NodeState from "../../components/NodeState.vue"; import NodeState from "../../components/NodeState.vue";
import "vue3-json-viewer/dist/index.css"; import "vue3-json-viewer/dist/index.css";
import { emitter } from "@/utils/eventBus"; import { emitter } from "@/utils/eventBus";
import FormItemRecursive from "./FormItemRecursive.vue";
const props = defineProps({ const props = defineProps({
model: Object, model: Object,
@ -92,96 +34,27 @@ const props = defineProps({
}); });
const emits = defineEmits(["contentChange"]); const emits = defineEmits(["contentChange"]);
const flowStore = useFlowStore();
const formData = reactive({
inputParams: [
{
name: "terminalId",
type: "string",
desc: "机器人ip",
disabled: true,
required: true,
children: [],
},
],
});
const rules = reactive({});
const addFormItem = () => {
formData.inputParams.push({
name: "",
type: "",
desc: "",
required: false,
children: [],
});
emits("contentChange");
};
const dynamicForm = ref();
const setNodeProperties = async () => {
try {
const result = await dynamicForm.value.validate();
if (result) {
const data = toRaw(formData);
lf.setProperties(props.model.id, {
...props.properties,
...data,
zoom: nodeZoom.value
});
emits("contentChange");
}
} catch {
dynamicForm.value.clearValidate()
}
};
const nodeOperatingStatus = ref("NORMAL"); const nodeOperatingStatus = ref("NORMAL");
const runtimes = ref(0);
const inputJsonData = ref({}); const inputJsonData = ref({});
const outputJsonData = ref({}); const outputJsonData = ref({});
watch( const nodeStateRef = ref(null);
() => props.properties,
() => {
if (props.properties.inputParams && props.properties.inputParams.length > 0) {
formData.inputParams = props.properties.inputParams;
nextTick(() => {
initNodeZoom(props.model.id, props?.properties?.zoom ?? true, '.node__box', true)
})
}
},
{
immediate: true,
deep: true,
}
);
// const closePopover = () => {
const deleteTopLevelItem = (fullPath) => { if (nodeStateRef.value) {
// nodeStateRef.value.closePopover();
let currentLevel = formData.inputParams;
//
for (let i = 0; i < fullPath.length - 1; i++) {
const index = fullPath[i];
//
currentLevel = currentLevel[index].children;
} }
//
const lastIndex = fullPath[fullPath.length - 1];
currentLevel.splice(lastIndex, 1);
emits("contentChange");
} }
onMounted(() => { onMounted(() => {
setNodeProperties();
emitter.on("changeNodeState", (data) => { emitter.on("changeNodeState", (data) => {
if (data.nodeId === props.model.id) { if (data.nodeId === props.model.id) {
nodeOperatingStatus.value = data.status; nodeOperatingStatus.value = data.status;
if (data.endTime && data.startTime) {
runtimes.value = data.endTime - data.startTime;
}
let inputData = {}; let inputData = {};
let output = {}; let output = {};
try { try {
@ -207,36 +80,23 @@ onMounted(() => {
emits("contentChange"); emits("contentChange");
} }
}); });
emitter.on("setProperties", (data) => {
if (data.id === props.model.id) {
emits("contentChange");
}
});
}); });
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 nodeZoom = ref(props?.properties?.zoom ?? true)
const zoom = () => {
nodeZoom.value = !nodeZoom.value
initNodeZoom(props.model.id, nodeZoom.value, '.node__box')
}
onUnmounted(() => { onUnmounted(() => {
emitter.off("changeNodeState"); emitter.off("changeNodeState");
emitter.off("contentChange"); emitter.off("contentChange");
emitter.off("setProperties");
}); });
defineExpose({ defineExpose({ closePopover })
validateForm,
setNodeProperties
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@ -277,116 +137,6 @@ defineExpose({
margin: 8px 0; margin: 8px 0;
} }
} }
.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;
}
}
}
.deleteBtn {
margin-bottom: 22px;
cursor: pointer;
}
.addBtn {
margin-bottom: 22px;
cursor: pointer;
}
:deep(.el-row) {
align-items: end;
.el-input {
--el-input-width: 120px;
}
.el-select {
--el-select-width: 120px;
}
.el-cascader {
--el-form-inline-content-width: 120px;
}
}
}
}
} }
</style> </style>

View File

@ -144,14 +144,8 @@ class CodeNodeHtmlModel extends HtmlNodeModel {
this.componentInstance = instance; this.componentInstance = instance;
} }
// 验证表单 closePopover() {
async validateForm() { this.componentInstance.closePopover()
const result = this.componentInstance.validateForm()
return result
}
setCustomProperties() {
this.componentInstance.setNodeProperties()
} }
/** /**

View File

@ -1,6 +1,6 @@
<template> <template>
<div class="node__container" :class="props.model.id"> <div class="node__container" :class="props.model.id">
<NodeState :state="nodeOperatingStatus"> <NodeState :state="nodeOperatingStatus" :runtimes="runtimes" ref="nodeStateRef">
<template #input> <template #input>
<JsonViewer :value="inputJsonData" copyable boxed sort theme="light" /> <JsonViewer :value="inputJsonData" copyable boxed sort theme="light" />
</template> </template>
@ -40,196 +40,17 @@
:nodeType="props.properties.nodeType || 'NONE'" :nodeType="props.properties.nodeType || 'NONE'"
:nodeName="props.properties.name" :nodeName="props.properties.name"
:nodeDesc="props.properties.desc" :nodeDesc="props.properties.desc"
:zoom-state="nodeZoom"
@zoom="zoom"
@setNodeName="setNodeName" @setNodeName="setNodeName"
/> />
<div class="input__container" v-show="nodeZoom" @mousedown="(e) => e.stopPropagation()" @keydown="handleInputKeydown">
<div class="title">
<div class="left">
<div class="tag"></div>
<div class="text">输入</div>
</div>
<div class="right" v-if="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">
<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 v-if="property.name !== 'code'">
<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"
@keydown="handleInputKeydown"
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: property?.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
@keydown="handleInputKeydown"
/>
<el-select
v-model="property.input"
v-else-if="property.componentType === 'select'"
>
<el-option
v-for="item in property.selectOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
<el-input
@keydown="handleInputKeydown"
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"
:checkStrictly="true"
:options="quoteOptions"
placeholder="请选择"
@visible-change="
(visible) => visibleChange(visible, index, property.quote)
"
@change="(value) => cascaderChange(value, index)"
/>
</el-form-item>
</el-form-item>
</el-row>
</div>
</el-form>
</div>
<div class="code__container">
<div ref="codeRef" style="width: 100%; height: 100%"></div>
</div>
</div>
<div class="output__container" v-show="nodeZoom">
<div v-if="props.properties?.outputParams?.length > 0">
<div class="title">
<div class="left">
<div class="tag"></div>
<div class="text">输出</div>
</div>
<div class="right">
<el-button
:disabled="flowStore.disableForm"
@click="addOutputFormItem"
class="addFormItem"
>
<el-icon :size="20"><Plus /></el-icon>
</el-button>
</div>
</div>
<div class="form__container">
<el-form
:inline="true"
:model="formData"
label-position="top"
label-width="auto"
:rules="outputRules"
ref="outputFormRef"
>
<FormItemRecursive
formType="output"
:current-list="formData.outputParams"
prop-path="outputParams"
:depth="0"
:is-first-level="true"
:endDepth="2"
:parent-path="[]"
@delete-item="deleteTopLevelItem"
/>
</el-form>
</div>
</div>
</div>
</div> </div>
</template> </template>
<script setup> <script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue"; import { ref, onMounted, onUnmounted } 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 NodeTitle from "../../components/NodeTitle.vue";
import NodeState from "../../components/NodeState.vue"; import NodeState from "../../components/NodeState.vue";
import "vue3-json-viewer/dist/index.css";
import { emitter } from "@/utils/eventBus"; import { emitter } from "@/utils/eventBus";
import IPlayer from "@/views/device/register/components/LogicFlow/IPlayer/index.vue"; import IPlayer from "@/views/device/register/components/LogicFlow/IPlayer/index.vue";
import FormItemRecursive from "../common/FormItemRecursive.vue";
import * as monaco from 'monaco-editor';
const props = defineProps({ const props = defineProps({
model: Object, model: Object,
@ -238,87 +59,6 @@ const props = defineProps({
const emits = defineEmits(["contentChange"]); const emits = defineEmits(["contentChange"]);
const codeRef = ref()
let editorInstance
const flowStore = useFlowStore();
const formData = reactive({
nodeParams: [],
outputParams: [],
});
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 cascaderRefs = ref([]);
const outputRules = reactive({});
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 addOutputFormItem = () => {
formData.outputParams.push({
name: "",
type: "",
desc: "",
children: [],
});
};
const dynamicForm = ref();
const outputFormRef = ref();
const setNodeProperties = async () => {
try {
const result = await dynamicForm.value.validate();
let flag = true;
if (outputFormRef.value) {
flag = await outputFormRef.value.validate();
}
if (hasErrors()) {
console.log('编辑器中有错误')
return
}
if (result && flag) {
const data = toRaw(formData);
const targetObj = data.nodeParams.find(item => item.name === 'code');
if (targetObj) {
// input
targetObj.input = editorInstance.getValue();
} else {
data.nodeParams.push(
{ name: "code", type: "input", input: editorInstance.getValue() }
)
}
const properties = lf.getProperties(props.model.id);
lf.setProperties(props.model.id, {
...properties,
...data,
zoom: nodeZoom.value
});
emits("contentChange");
}
} catch {
console.log(12323)
// dynamicForm.value.clearValidate();
}
};
const setNodeName = (name) => { const setNodeName = (name) => {
const properties = lf.getProperties(props.model.id); const properties = lf.getProperties(props.model.id);
lf.setProperties(props.model.id, { lf.setProperties(props.model.id, {
@ -329,211 +69,27 @@ const setNodeName = (name) => {
} }
const nodeOperatingStatus = ref("NORMAL"); const nodeOperatingStatus = ref("NORMAL");
const runtimes = ref(0);
const inputJsonData = ref({}); const inputJsonData = ref({});
const outputJsonData = ref({}); const outputJsonData = ref({});
const errorInfoData = ref(''); const errorInfoData = ref('');
const visibleChange = (value, index, quote) => { const nodeStateRef = ref(null);
if (value) {
const option = getInput(props.model.id);
if (option) {
quoteOptions.value = option;
const currentValue = [...quote];
//
if (cascaderRefs.value[index]) {
// DOMoptions
setTimeout(() => {
//
if (currentValue.length) {
formData.nodeParams[index].quote = [];
//
setTimeout(() => {
formData.nodeParams[index].quote = currentValue;
}, 0);
}
//
// cascaderRefs.value[index].updatePopper();
}, 0);
}
}
}
};
const validateForm = async () => { const closePopover = () => {
try { if (nodeStateRef.value) {
const result = await dynamicForm.value.validate(); nodeStateRef.value.closePopover();
if (result) {
return { valid: true, message: "验证通过" };
} else {
return { valid: false, message: "验证失败" };
}
} catch {
return { valid: false, message: "验证失败" };
}
};
const addFormItem = () => {
formData.nodeParams.push({
name: "",
type: "input",
desc: "",
required: false,
children: [],
});
emits("contentChange");
};
//
const deleteTopLevelItem = (fullPath) => {
//
let currentLevel = formData.outputParams;
//
for (let i = 0; i < fullPath.length - 1; i++) {
const index = fullPath[i];
//
currentLevel = currentLevel[index].children;
}
//
const lastIndex = fullPath[fullPath.length - 1];
currentLevel.splice(lastIndex, 1);
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) {
// .filter(item => item.name !== 'code')
formData.nodeParams = props.properties.nodeParams;
const codeParams = props.properties.nodeParams.find(item => item.name === 'code')
if (codeParams) {
nextTick(() => {
if (editorInstance) {
setValue(codeParams.input)
}
})
}
const option = getInput(props.model.id);
if (option) {
quoteOptions.value = option;
}
nextTick(() => {
initNodeZoom(props.model.id, props?.properties?.zoom ?? true, '.node__box', true)
})
}
if (
props.properties.outputParams &&
props.properties.outputParams.length > 0
) {
formData.outputParams = props.properties.outputParams;
}
},
{
immediate: true,
deep: true,
}
);
const handleInputKeydown = (e) => {
// Logic Flow
e.stopPropagation();
// Ctrl+V
if ((e.ctrlKey || e.metaKey) && e.key === "v") {
e.returnValue = true; //
}
};
function hasErrors() {
const model = editorInstance.getModel();
if (!model) return false;
//
const markers = monaco.editor.getModelMarkers({ resource: model.uri });
//
return markers.some(marker => marker.severity === monaco.MarkerSeverity.Error);
}
const initEditor = () => {
monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
target: monaco.languages.typescript.ScriptTarget.ES2020,
allowNonTsExtensions: true, // ts .js
checkJs: true, // .js
strict: true, //
noImplicitAny: false, // any
noUnusedLocals: true, // 使
noUnusedParameters: true, // 使
});
//
monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
noSemanticValidation: false, //
noSyntaxValidation: false, //
});
editorInstance = monaco.editor.create(codeRef.value, {
value: [`
//
function handler(params) {
// json dict object
const ret={
result: {
type: 2,
message: params.input
}
}
return ret
}`].join('\n'),
language: 'javascript',
fontSize: 14,
lineNumbers: 'on',
roundedSelection: true,
scrollBeyondLastLine: false,
formatOnPaste: true,
formatOnType: true,
quickSuggestions: true,
suggestOnTriggerCharacters: true,
//
suggest: {
showWords: true,
showFunctions: true,
showVariables: true,
showClasses: true,
showModules: true,
},
});
}
//
const setValue = (value) => {
if (editorInstance) {
editorInstance.setValue(value)
} }
} }
//
const disposeEditor = () => {
if (editorInstance) {
editorInstance.dispose()
editorInstance = null
}
}
onMounted(() => { onMounted(() => {
emitter.on("changeNodeState", (data) => { emitter.on("changeNodeState", (data) => {
if (data.nodeId === props.model.id) { if (data.nodeId === props.model.id) {
nodeOperatingStatus.value = data.status; nodeOperatingStatus.value = data.status;
if (data.endTime && data.startTime) {
runtimes.value = data.endTime - data.startTime;
}
let inputData = {}; let inputData = {};
let output = {}; let output = {};
errorInfoData.value = data?.message || '' errorInfoData.value = data?.message || ''
@ -559,179 +115,25 @@ onMounted(() => {
} }
}); });
initEditor() emitter.on("setProperties", (data) => {
if (data.id === props.model.id) {
emits("contentChange");
}
});
}) })
onUnmounted(() => { onUnmounted(() => {
emitter.off("changeNodeState"); emitter.off("changeNodeState");
emitter.off("contentChange"); emitter.off("contentChange");
disposeEditor() emitter.off("setProperties");
}); });
defineExpose({ defineExpose({ closePopover })
validateForm,
setNodeProperties,
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.node__container { .node__container {
width: 100%; width: 100%;
height: auto; 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;
}
}
}
.code__container {
display: flex;
position: relative;
text-align: initial;
width: 100%;
height: 300px;
margin: 12px 0;
}
.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;
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;
}
}
:deep(.el-row) {
align-items: end;
.el-input {
--el-input-width: 148px;
}
.el-select {
--el-select-width: 148px;
}
.el-cascader {
--el-form-inline-content-width: 148px;
}
}
} }
</style> </style>

View File

@ -1,6 +1,6 @@
<template> <template>
<div class="node__container" :class="props.model.id"> <div class="node__container" :class="props.model.id">
<NodeState :state="nodeOperatingStatus"> <NodeState :state="nodeOperatingStatus" :runtimes="runtimes" ref="nodeStateRef">
<template #input> <template #input>
<JsonViewer :value="inputJsonData" copyable boxed sort theme="light" /> <JsonViewer :value="inputJsonData" copyable boxed sort theme="light" />
</template> </template>
@ -26,127 +26,13 @@
:nodeName="props.properties.name" :nodeName="props.properties.name"
:nodeDesc="props.properties.desc" :nodeDesc="props.properties.desc"
:zoom-state="nodeZoom" :zoom-state="nodeZoom"
@zoom="zoom"
@setNodeName="setNodeName" @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> </div>
</template> </template>
<script setup> <script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue"; import { ref, reactive, onMounted, onUnmounted } 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 NodeTitle from "../../components/NodeTitle.vue";
import NodeState from "../../components/NodeState.vue"; import NodeState from "../../components/NodeState.vue";
import "vue3-json-viewer/dist/index.css"; import "vue3-json-viewer/dist/index.css";
@ -160,47 +46,6 @@ const props = defineProps({
const emits = defineEmits(["contentChange"]); 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 setNodeName = (name) => {
const properties = lf.getProperties(props.model.id); const properties = lf.getProperties(props.model.id);
lf.setProperties(props.model.id, { lf.setProperties(props.model.id, {
@ -211,79 +56,25 @@ const setNodeName = (name) => {
} }
const nodeOperatingStatus = ref("NORMAL"); const nodeOperatingStatus = ref("NORMAL");
const runtimes = ref(0);
const inputJsonData = ref({}); const inputJsonData = ref({});
const outputJsonData = ref({}); const outputJsonData = ref({});
const visibleChange = (value) => { const nodeStateRef = ref(null);
if (value) {
const option = getInput(props.model.id); const closePopover = () => {
if (option) { if (nodeStateRef.value) {
quoteOptions.value = option; nodeStateRef.value.closePopover();
}
} }
};
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(() => { onMounted(() => {
emitter.on("changeNodeState", (data) => { emitter.on("changeNodeState", (data) => {
if (data.nodeId === props.model.id) { if (data.nodeId === props.model.id) {
nodeOperatingStatus.value = data.status; nodeOperatingStatus.value = data.status;
if (data.endTime && data.startTime) {
runtimes.value = data.endTime - data.startTime;
}
let inputData = {}; let inputData = {};
let output = {}; let output = {};
try { try {
@ -307,17 +98,22 @@ onMounted(() => {
emits("contentChange"); emits("contentChange");
} }
}); });
emitter.on("setProperties", (data) => {
if (data.id === props.model.id) {
emits("contentChange");
}
});
}); });
onUnmounted(() => { onUnmounted(() => {
emitter.off("changeNodeState"); emitter.off("changeNodeState");
emitter.off("contentChange"); emitter.off("contentChange");
emitter.off("setProperties");
}); });
defineExpose({ defineExpose({ closePopover })
validateForm,
setNodeProperties,
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -150,8 +150,8 @@ class CurrentLoopNodeHtmlModel extends HtmlNodeModel {
return result return result
} }
setCustomProperties() { closePopover() {
this.componentInstance.setNodeProperties() this.componentInstance.closePopover()
} }
/** /**

View File

@ -144,14 +144,8 @@ class HttpNodeHtmlModel extends HtmlNodeModel {
this.componentInstance = instance; this.componentInstance = instance;
} }
// 验证表单 closePopover() {
async validateForm() { this.componentInstance.closePopover()
const result = this.componentInstance.validateForm()
return result
}
setCustomProperties() {
this.componentInstance.setNodeProperties()
} }
/** /**

View File

@ -1,6 +1,6 @@
<template> <template>
<div class="node__container" :class="props.model.id"> <div class="node__container" :class="props.model.id">
<NodeState :state="nodeOperatingStatus"> <NodeState :state="nodeOperatingStatus" :runtimes="runtimes" ref="nodeStateRef">
<template #input> <template #input>
<JsonViewer :value="inputJsonData" copyable boxed sort theme="light" /> <JsonViewer :value="inputJsonData" copyable boxed sort theme="light" />
</template> </template>
@ -44,188 +44,16 @@
@zoom="zoom" @zoom="zoom"
@setNodeName="setNodeName" @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">
<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"
@keydown="handleInputKeydown"
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: property?.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
@keydown="handleInputKeydown"
/>
<el-select
v-model="property.input"
v-else-if="property.componentType === 'select'"
>
<el-option
v-for="item in property.selectOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
<el-input
@keydown="handleInputKeydown"
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"
:checkStrictly="true"
:options="quoteOptions"
placeholder="请选择"
@visible-change="
(visible) => visibleChange(visible, index, property.quote)
"
@change="(value) => cascaderChange(value, index)"
/>
</el-form-item>
</el-form-item>
</el-row>
</div>
</el-form>
</div>
</div>
<div class="output__container" v-show="nodeZoom">
<div v-if="props.properties?.outputParams?.length > 0">
<div class="title">
<div class="left">
<div class="tag"></div>
<div class="text">输出</div>
</div>
<div class="right">
<el-button
:disabled="flowStore.disableForm"
@click="addOutputFormItem"
class="addFormItem"
>
<el-icon :size="20"><Plus /></el-icon>
</el-button>
</div>
</div>
<div class="form__container">
<el-form
:inline="true"
:model="formData"
label-position="top"
label-width="auto"
:rules="outputRules"
ref="outputFormRef"
>
<FormItemRecursive
formType="output"
:current-list="formData.outputParams"
prop-path="outputParams"
:depth="0"
:is-first-level="true"
:endDepth="2"
:parent-path="[]"
@delete-item="deleteTopLevelItem"
/>
</el-form>
</div>
</div>
</div>
</div> </div>
</template> </template>
<script setup> <script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue"; import { ref, onMounted, onUnmounted } 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 NodeTitle from "../../components/NodeTitle.vue";
import NodeState from "../../components/NodeState.vue"; import NodeState from "../../components/NodeState.vue";
import "vue3-json-viewer/dist/index.css"; import "vue3-json-viewer/dist/index.css";
import { emitter } from "@/utils/eventBus"; import { emitter } from "@/utils/eventBus";
import IPlayer from "@/views/device/register/components/LogicFlow/IPlayer/index.vue"; import IPlayer from "@/views/device/register/components/LogicFlow/IPlayer/index.vue";
import FormItemRecursive from "../common/FormItemRecursive.vue";
const props = defineProps({ const props = defineProps({
model: Object, model: Object,
@ -234,70 +62,6 @@ const props = defineProps({
const emits = defineEmits(["contentChange"]); const emits = defineEmits(["contentChange"]);
const flowStore = useFlowStore();
const formData = reactive({
nodeParams: [],
outputParams: [],
});
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 cascaderRefs = ref([]);
const outputRules = reactive({});
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 addOutputFormItem = () => {
formData.outputParams.push({
name: "",
type: "",
desc: "",
children: [],
});
};
const dynamicForm = ref();
const outputFormRef = ref();
const setNodeProperties = async () => {
try {
const result = await dynamicForm.value.validate();
let flag = true;
if (outputFormRef.value) {
flag = await outputFormRef.value.validate();
}
if (result && flag) {
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 setNodeName = (name) => {
const properties = lf.getProperties(props.model.id); const properties = lf.getProperties(props.model.id);
lf.setProperties(props.model.id, { lf.setProperties(props.model.id, {
@ -308,124 +72,26 @@ const setNodeName = (name) => {
} }
const nodeOperatingStatus = ref("NORMAL"); const nodeOperatingStatus = ref("NORMAL");
const runtimes = ref(0);
const inputJsonData = ref({}); const inputJsonData = ref({});
const outputJsonData = ref({}); const outputJsonData = ref({});
const errorInfoData = ref(''); const errorInfoData = ref('');
const visibleChange = (value, index, quote) => { const nodeStateRef = ref(null);
if (value) {
const option = getInput(props.model.id); const closePopover = () => {
if (option) { if (nodeStateRef.value) {
quoteOptions.value = option; nodeStateRef.value.closePopover();
const currentValue = [...quote];
//
if (cascaderRefs.value[index]) {
// DOMoptions
setTimeout(() => {
//
if (currentValue.length) {
formData.nodeParams[index].quote = [];
//
setTimeout(() => {
formData.nodeParams[index].quote = currentValue;
}, 0);
}
//
// cascaderRefs.value[index].updatePopper();
}, 0);
}
}
} }
};
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 deleteTopLevelItem = (fullPath) => {
//
let currentLevel = formData.outputParams;
//
for (let i = 0; i < fullPath.length - 1; i++) {
const index = fullPath[i];
//
currentLevel = currentLevel[index].children;
}
//
const lastIndex = fullPath[fullPath.length - 1];
currentLevel.splice(lastIndex, 1);
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)
})
}
if (
props.properties.outputParams &&
props.properties.outputParams.length > 0
) {
formData.outputParams = props.properties.outputParams;
}
},
{
immediate: true,
deep: true,
}
);
const handleInputKeydown = (e) => {
// Logic Flow
e.stopPropagation();
// Ctrl+V
if ((e.ctrlKey || e.metaKey) && e.key === "v") {
e.returnValue = true; //
}
};
onMounted(() => { onMounted(() => {
emitter.on("changeNodeState", (data) => { emitter.on("changeNodeState", (data) => {
if (data.nodeId === props.model.id) { if (data.nodeId === props.model.id) {
nodeOperatingStatus.value = data.status; nodeOperatingStatus.value = data.status;
if (data.endTime && data.startTime) {
runtimes.value = data.endTime - data.startTime;
}
let inputData = {}; let inputData = {};
let output = {}; let output = {};
errorInfoData.value = data?.message || '' errorInfoData.value = data?.message || ''
@ -450,168 +116,26 @@ onMounted(() => {
emits("contentChange"); emits("contentChange");
} }
}); });
emitter.on("setProperties", (data) => {
if (data.id === props.model.id) {
emits("contentChange");
}
});
}); });
onUnmounted(() => { onUnmounted(() => {
emitter.off("changeNodeState"); emitter.off("changeNodeState");
emitter.off("contentChange"); emitter.off("contentChange");
emitter.off("setProperties");
}); });
defineExpose({ defineExpose({ closePopover })
validateForm,
setNodeProperties,
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.node__container { .node__container {
width: 100%; width: 100%;
height: auto; 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;
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;
}
}
:deep(.el-row) {
align-items: end;
.el-input {
--el-input-width: 148px;
}
.el-select {
--el-select-width: 148px;
}
.el-cascader {
--el-form-inline-content-width: 148px;
}
}
} }
</style> </style>

View File

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

View File

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

View File

@ -9,118 +9,22 @@
:showZoom="false" :showZoom="false"
@setNodeName="setNodeName" @setNodeName="setNodeName"
/> />
<div class="loop__container"> <div>循环体</div>
<div> <div
<el-form class="child__container"
:inline="true" @drop="handleDrop"
:model="formData" @dragover="handleDragover"
:rules="rules" >
ref="dynamicForm" <slot></slot>
label-position="top" </div>
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="index === 0"
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-model="property.input"
:min="0"
:controls="false"
:step-strictly="true"
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"
:checkStrictly="true"
:options="quoteOptions"
placeholder="请选择"
@visible-change="
(visible) =>
visibleChange(visible, index, property.quote)
"
@change="(value) => cascaderChange(value, index)"
/>
</el-form-item>
</el-form-item>
</el-row>
</div>
</el-form>
</div>
</div>
<div>循环体</div>
<div
class="child__container"
@drop="handleDrop"
@dragover="handleDragover"
>
<slot></slot>
</div>
</div> </div>
</template> </template>
<script setup> <script setup>
import { ref, onMounted, nextTick } from "vue";
import NodeTitle from "../../components/NodeTitle.vue"; import NodeTitle from "../../components/NodeTitle.vue";
import loop from "../../icon/loop.svg"; import loop from "../../icon/loop.svg";
import { useFlowStore } from "@/store/modules/flow"; import { addNewEdge } from "@/utils/flow";
import { addNewEdge, getInput } from "@/utils/flow"; import { emitter } from "@/utils/eventBus";
import { onUnmounted } from "vue";
const props = defineProps({ const props = defineProps({
model: Object, model: Object,
@ -129,25 +33,6 @@ const props = defineProps({
nowTime: Number, nowTime: Number,
}); });
const flowStore = useFlowStore();
const formData = reactive({
nodeParams: [{ name: "loopNum", type: "input", input: null, quote: "" }],
});
const quoteOptions = ref([]);
const handleTypeChange = (index) => {
if (formData.nodeParams[index].type === "input") {
formData.nodeParams[index].quote = "";
} else {
formData.nodeParams[index].input = null;
const option = getInput(props.model.id);
if (option) {
quoteOptions.value = option;
}
}
};
const rules = reactive({});
const emits = defineEmits(["bindRef", "addToGroup", "contentChange"]); const emits = defineEmits(["bindRef", "addToGroup", "contentChange"]);
@ -172,6 +57,11 @@ const handleDrop = (e) => {
...other, ...other,
}, },
}); });
if (
!["selectArea", "branch", "stopLoop", "subStart", "subEnd"].includes(node.type)
) {
emitter.emit("openParamsDrawer", node);
}
emits("addToGroup", node.id); emits("addToGroup", node.id);
setTimeout(() => { setTimeout(() => {
@ -179,26 +69,6 @@ const handleDrop = (e) => {
}, 50); }, 50);
}; };
const dynamicForm = ref();
const setNodeProperties = async () => {
try {
const valid = await dynamicForm.value.validate();
if (valid) {
const data = toRaw(formData);
setTimeout(() => {
const properties = lf.getProperties(props.model.id);
window.lf.setProperties(props.model.id, {
...properties,
...data,
});
}, 50);
}
} catch (error) {
dynamicForm.value.clearValidate();
}
};
const setNodeName = (name) => { const setNodeName = (name) => {
const properties = lf.getProperties(props.model.id); const properties = lf.getProperties(props.model.id);
lf.setProperties(props.model.id, { lf.setProperties(props.model.id, {
@ -208,60 +78,10 @@ const setNodeName = (name) => {
emits("contentChange"); emits("contentChange");
} }
const visibleChange = async (value, index, quote) => { onUnmounted(() => {
if (value) { emitter.off("openParamsDrawer");
const option = getInput(props.model.id); })
if (option) {
quoteOptions.value = option;
const currentValue = [...quote];
//
if (cascaderRefs.value[index]) {
// DOMoptions
setTimeout(() => {
//
if (currentValue.length) {
formData.nodeParams[index].quote = [];
//
setTimeout(() => {
console.log(1247);
formData.nodeParams[index].quote = currentValue;
}, 0);
}
//
// cascaderRefs.value[index].updatePopper();
}, 0);
}
}
}
};
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;
};
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;
}
}
},
{
immediate: true,
deep: true,
}
);
onMounted(() => {
emits("bindRef", dynamicForm.value);
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.group__container { .group__container {
@ -282,26 +102,6 @@ onMounted(() => {
height: 40px; height: 40px;
} }
:deep(.loop__container) {
height: auto;
.el-input {
width: 240px;
}
.el-input-number {
width: 92px;
}
.el-select {
width: 120px;
}
.el-cascader {
width: 240px;
}
}
.child__container { .child__container {
min-height: 100px; min-height: 100px;
flex: 1; flex: 1;

View File

@ -0,0 +1,213 @@
// 导入 HtmlNode 及其模型,为后续继承做准备
import { HtmlNode, HtmlNodeModel } from "@logicflow/core";
// 导入 Vue 相关方法,用于渲染组件
import { createApp, h, nextTick } from "vue";
import ElementPlus from "element-plus";
// 导入 Vue 组件
// @ts-ignore
import SdAgent from "./sdAgent.vue";
import OuterNode from "../../components/OuterNode.vue";
import JsonViewer from 'vue3-json-viewer'
/**
* 定义一个 元素的 HTML 节点类继承自 HtmlNode
* 该类负责在 HTML 中渲染 元素并处理其交互逻辑
*/
class SdAgentNodeHtmlNode 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: SdAgent,
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 (SdAgentNodeHtmlNode.reusePool.has(nodeId)) {
rootEl.appendChild(SdAgentNodeHtmlNode.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();
SdAgentNodeHtmlNode.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 SdAgentNodeHtmlModel extends HtmlNodeModel {
initNodeData(data) {
super.initNodeData(data);
}
// 保存组件实例引用
setComponentInstance(instance) {
this.componentInstance = instance;
}
closePopover() {
this.componentInstance.closePopover()
}
/**
* 设置节点属性
* 包括宽度高度文本编辑属性等
*/
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 registerSdAgentNode(lf) {
lf.register({
type: "sdAgent",
view: SdAgentNodeHtmlNode,
model: SdAgentNodeHtmlModel
});
}

View File

@ -0,0 +1,126 @@
<template>
<div class="node__container" :class="props.model.id">
<NodeState :state="nodeOperatingStatus" :runtimes="runtimes" ref="nodeStateRef">
<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"
:nodeType="props.properties.nodeType || 'NONE'"
:nodeDesc="props.properties.desc"
:zoom-state="nodeZoom"
@zoom="zoom"
@setNodeName="setNodeName"
/>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from "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 setNodeName = (name) => {
const properties = lf.getProperties(props.model.id);
lf.setProperties(props.model.id, {
...properties,
name
});
emits("contentChange");
}
const nodeOperatingStatus = ref("NORMAL");
const runtimes = ref(0);
const inputJsonData = ref({});
const outputJsonData = ref({});
const nodeStateRef = ref(null);
const closePopover = () => {
if (nodeStateRef.value) {
nodeStateRef.value.closePopover();
}
}
onMounted(() => {
emitter.on("changeNodeState", (data) => {
if (data.nodeId === props.model.id) {
nodeOperatingStatus.value = data.status;
if (data.endTime && data.startTime) {
runtimes.value = data.endTime - data.startTime;
}
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");
}
});
emitter.on("setProperties", (data) => {
if (data.id === props.model.id) {
emits("contentChange");
}
});
});
onUnmounted(() => {
emitter.off("changeNodeState");
emitter.off("contentChange");
emitter.off("setProperties");
});
defineExpose({ closePopover })
</script>
<style lang="scss" scoped>
.node__container {
width: 100%;
height: auto;
}
</style>

View File

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

View File

@ -1,6 +1,6 @@
<template> <template>
<div class="node__container" :class="props.model.id"> <div class="node__container" :class="props.model.id">
<NodeState :state="nodeOperatingStatus"> <NodeState :state="nodeOperatingStatus" :runtimes="runtimes" ref="nodeStateRef">
<template #input> <template #input>
<JsonViewer :value="inputJsonData" copyable boxed sort theme="light" /> <JsonViewer :value="inputJsonData" copyable boxed sort theme="light" />
</template> </template>
@ -29,124 +29,11 @@
@zoom="zoom" @zoom="zoom"
@setNodeName="setNodeName" @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="参数名" >
<el-input :value="item.name" />
</el-form-item>
<el-form-item label="参数类型" >
<el-input :value="item.type" />
</el-form-item>
<el-form-item label="描述" >
<el-input :value="item.desc" />
</el-form-item>
</el-row>
</el-form>
</div>
</div>
</div> </div>
</template> </template>
<script setup> <script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue"; import { ref, onMounted, onUnmounted } 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 NodeTitle from "../../components/NodeTitle.vue";
import NodeState from "../../components/NodeState.vue"; import NodeState from "../../components/NodeState.vue";
import "vue3-json-viewer/dist/index.css"; import "vue3-json-viewer/dist/index.css";
@ -160,47 +47,6 @@ const props = defineProps({
const emits = defineEmits(["contentChange"]); 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 setNodeName = (name) => {
const properties = lf.getProperties(props.model.id); const properties = lf.getProperties(props.model.id);
lf.setProperties(props.model.id, { lf.setProperties(props.model.id, {
@ -211,79 +57,25 @@ const setNodeName = (name) => {
} }
const nodeOperatingStatus = ref("NORMAL"); const nodeOperatingStatus = ref("NORMAL");
const runtimes = ref(0);
const inputJsonData = ref({}); const inputJsonData = ref({});
const outputJsonData = ref({}); const outputJsonData = ref({});
const visibleChange = (value) => { const nodeStateRef = ref(null);
if (value) {
const option = getInput(props.model.id); const closePopover = () => {
if (option) { if (nodeStateRef.value) {
quoteOptions.value = option; nodeStateRef.value.closePopover();
}
} }
};
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(() => { onMounted(() => {
emitter.on("changeNodeState", (data) => { emitter.on("changeNodeState", (data) => {
if (data.nodeId === props.model.id) { if (data.nodeId === props.model.id) {
nodeOperatingStatus.value = data.status; nodeOperatingStatus.value = data.status;
if (data.endTime && data.startTime) {
runtimes.value = data.endTime - data.startTime;
}
let inputData = {}; let inputData = {};
let output = {}; let output = {};
try { try {
@ -307,154 +99,27 @@ onMounted(() => {
emits("contentChange"); emits("contentChange");
} }
}); });
emitter.on("setProperties", (data) => {
if (data.id === props.model.id) {
emits("contentChange");
}
});
}); });
onUnmounted(() => { onUnmounted(() => {
emitter.off("changeNodeState"); emitter.off("changeNodeState");
emitter.off("contentChange"); emitter.off("contentChange");
emitter.off("setProperties");
}); });
defineExpose({
validateForm, defineExpose({ closePopover })
setNodeProperties,
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.node__container { .node__container {
width: 100%; width: 100%;
height: auto; 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> </style>

View File

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

View File

@ -1,203 +1,186 @@
// 导入 HtmlNode 及其模型,为后续继承做准备 // 导入 HtmlNode 及其模型,为后续继承做准备
import { HtmlNode, HtmlNodeModel } from "@logicflow/core"; import { HtmlNode, HtmlNodeModel } from "@logicflow/core";
// 导入 Vue 相关方法,用于渲染组件 // 导入 Vue 相关方法,用于渲染组件
import { createApp, h, nextTick } from "vue"; import { createApp, h, nextTick } from "vue";
import ElementPlus from "element-plus"; import ElementPlus from "element-plus";
// 导入 Vue 组件 // 导入 Vue 组件
import SubEndNode from "./subEnd.vue"; import SubEndNode from "./subEnd.vue";
/** /**
* 定义一个 元素的 HTML 节点类继承自 HtmlNode * 定义一个 元素的 HTML 节点类继承自 HtmlNode
* 该类负责在 HTML 中渲染 元素并处理其交互逻辑 * 该类负责在 HTML 中渲染 元素并处理其交互逻辑
*/ */
class SubEndNodeHtmlNode extends HtmlNode { class SubEndNodeHtmlNode extends HtmlNode {
resizeObserver = null; resizeObserver = null;
isMounted; // 标记组件是否已挂载 isMounted; // 标记组件是否已挂载
r; // 渲染函数 r; // 渲染函数
app; // Vue 应用实例 app; // Vue 应用实例
container = null; container = null;
/** /**
* 构造函数 * 构造函数
* @param props 传递给节点的属性包括模型图模型等 * @param props 传递给节点的属性包括模型图模型等
*/ */
constructor(props) { constructor(props) {
super(props); super(props);
this.initVueApp(props); this.initVueApp(props);
} }
initVueApp(props) { initVueApp(props) {
this.isMounted = false; this.isMounted = false;
this.hideAnchor = false; this.hideAnchor = false;
this.autoExpand = true; // 防止锚点被折叠 this.autoExpand = true; // 防止锚点被折叠
this.anchorsPreset = "default"; // 重置锚点预设 this.anchorsPreset = "default"; // 重置锚点预设
// 创建 元素的渲染函数 // 创建 元素的渲染函数
this.r = h(SubEndNode, { this.r = h(SubEndNode, {
model: props.model, model: props.model,
graphModel: props.graphModel, graphModel: props.graphModel,
properties: { properties: {
...props.model.getProperties(), ...props.model.getProperties(),
} }
}); });
// 创建 Vue 应用实例,并指定渲染函数 // 创建 Vue 应用实例,并指定渲染函数
this.app = createApp({ this.app = createApp({
render: () => this.r, render: () => this.r,
}); });
} }
/** /**
* HTML 内容设置到指定的根元素上 * HTML 内容设置到指定的根元素上
* @param rootEl 根元素 * @param rootEl 根元素
*/ */
async setHtml(rootEl) { async setHtml(rootEl) {
if (!this.isMounted) { if (!this.isMounted) {
this.isMounted = true; this.isMounted = true;
this.container = document.createElement("div"); this.container = document.createElement("div");
this.container.style.display = "inline-block"; // 关键:确保容器自适应内容 this.container.style.display = "inline-block"; // 关键:确保容器自适应内容
rootEl.appendChild(this.container); rootEl.appendChild(this.container);
this.app.use(ElementPlus); // 关键单独注册ElementPlus this.app.use(ElementPlus); // 关键单独注册ElementPlus
this.app.mount(this.container); this.app.mount(this.container);
await nextTick(); await nextTick();
this.setupSizeObserver(); this.setupSizeObserver();
} else { } else {
this.r.component.props.properties = this.props.model.getProperties(); this.r.component.props.properties = this.props.model.getProperties();
} }
} }
/** /**
* 获取节点文本内容 * 获取节点文本内容
* 对于元素返回 null因为其内容由特定组件渲染 * 对于元素返回 null因为其内容由特定组件渲染
* @returns {null} * @returns {null}
*/ */
getText() { getText() {
return null; return null;
} }
handleComponentInstance(data) { handleComponentInstance(data) {
// 将组件实例保存到节点模型 // 将组件实例保存到节点模型
this.props.model.setComponentInstance(data); this.props.model.setComponentInstance(data);
} }
handleContentChange() { handleContentChange() {
// 内容变化时强制更新尺寸 // 内容变化时强制更新尺寸
this.updateNodeSize(); this.updateNodeSize();
} }
// 渲染完成后获取实际尺寸 // 渲染完成后获取实际尺寸
updateNodeSize() { updateNodeSize() {
if (this.container) { if (this.container) {
const { SCALE_X, SCALE_Y } = this.props.graphModel.transformModel; const { SCALE_X, SCALE_Y } = this.props.graphModel.transformModel;
const node = this.container.querySelector(".node__container"); const node = this.container.querySelector(".node__container");
const rect = node.getBoundingClientRect(); const rect = node.getBoundingClientRect();
this.props.model.updateSize(rect.width / SCALE_X, rect.height / SCALE_Y); this.props.model.updateSize(rect.width / SCALE_X, rect.height / SCALE_Y);
} }
} }
setupSizeObserver() { setupSizeObserver() {
// 首次渲染立即检测 // 首次渲染立即检测
requestAnimationFrame(() => { requestAnimationFrame(() => {
this.updateNodeSize(); this.updateNodeSize();
// 持续监听变化 // 持续监听变化
this.resizeObserver = new ResizeObserver(() => { this.resizeObserver = new ResizeObserver(() => {
this.updateNodeSize(); this.updateNodeSize();
}); });
this.resizeObserver.observe(this.container); this.resizeObserver.observe(this.container);
}); });
} }
// 组件卸载时移除监听 // 组件卸载时移除监听
onDestroy() { onDestroy() {
this.resizeObserver?.disconnect(); this.resizeObserver?.disconnect();
} }
} }
/** /**
* 定义一个元素的 HTML 模型类继承自 HtmlNodeModel * 定义一个元素的 HTML 模型类继承自 HtmlNodeModel
* 该类主要设置节点的属性和样式 * 该类主要设置节点的属性和样式
*/ */
class SubEndNodeHtmlModel extends HtmlNodeModel { class SubEndNodeHtmlModel extends HtmlNodeModel {
initNodeData(data) { initNodeData(data) {
super.initNodeData(data); super.initNodeData(data);
} }
// 保存组件实例引用 // 保存组件实例引用
setComponentInstance(instance) { setComponentInstance(instance) {
this.componentInstance = instance; this.componentInstance = instance;
} }
// 验证表单 /**
async validateForm() { * 设置节点属性
if (this.componentInstance && this.componentInstance.validate) { * 包括宽度高度文本编辑属性等
try { */
const result = await this.componentInstance.validate(); setAttributes() {
if (result) { // 初始设置为0后续动态更新
return { valid: true, message: "验证通过" }; this.width = 0;
} else { this.height = 0;
return { valid: false, message: "验证失败" }; this.text.editable = false;
} }
} catch {
return { valid: false, message: "验证失败" }; updateSize(width, height) {
} this.width = width + 24;
} this.height = height + 50;
return { valid: true, message: "无验证方法" }; this.initNodeData(this); // 触发节点重绘
} }
/** // 定义节点只有左右两个锚点. 锚点位置通过中心点和宽度算出来。
* 设置节点属性 getDefaultAnchor() {
* 包括宽度高度文本编辑属性等 let _a = this,
*/ x = _a.x,
setAttributes() { y = _a.y,
// 初始设置为0后续动态更新 width = _a.width,
this.width = 0; height = _a.height;
this.height = 0; return [
this.text.editable = false; {
} x: x - width / 2,
y: y - 25,
updateSize(width, height) { name: "left",
this.width = width + 24; id: "".concat(this.id, "_3"),
this.height = height + 50; properties: { connectionType: "target" },
this.initNodeData(this); // 触发节点重绘 },
} ];
}
// 定义节点只有左右两个锚点. 锚点位置通过中心点和宽度算出来。
getDefaultAnchor() { /**
let _a = this, * 获取节点轮廓样式
x = _a.x, * 覆盖父类方法设置 stroke 属性为 none以适应特定的视觉效果
y = _a.y, * @returns {object} 节点轮廓样式
width = _a.width, */
height = _a.height; getOutlineStyle() {
return [ const style = super.getOutlineStyle();
{ style.stroke = "none";
x: x - width / 2, style.hover.stroke = "none";
y: y - 25, return style;
name: "left", }
id: "".concat(this.id, "_3"), }
properties: { connectionType: "target" },
}, // 导出方法注册
]; export function registerSubEndNode(lf) {
} lf.register({
type: "subEnd",
/** view: SubEndNodeHtmlNode,
* 获取节点轮廓样式 model: SubEndNodeHtmlModel,
* 覆盖父类方法设置 stroke 属性为 none以适应特定的视觉效果 });
* @returns {object} 节点轮廓样式 }
*/
getOutlineStyle() {
const style = super.getOutlineStyle();
style.stroke = "none";
style.hover.stroke = "none";
return style;
}
}
// 导出方法注册
export function registerSubEndNode(lf) {
lf.register({
type: "subEnd",
view: SubEndNodeHtmlNode,
model: SubEndNodeHtmlModel,
});
}

View File

@ -1,202 +1,185 @@
// 导入 HtmlNode 及其模型,为后续继承做准备 // 导入 HtmlNode 及其模型,为后续继承做准备
import { HtmlNode, HtmlNodeModel } from "@logicflow/core"; import { HtmlNode, HtmlNodeModel } from "@logicflow/core";
// 导入 Vue 相关方法,用于渲染组件 // 导入 Vue 相关方法,用于渲染组件
import { createApp, h, nextTick } from "vue"; import { createApp, h, nextTick } from "vue";
import ElementPlus from "element-plus"; import ElementPlus from "element-plus";
// 导入 Vue 组件 // 导入 Vue 组件
import SubStartNode from "./subStart.vue"; import SubStartNode from "./subStart.vue";
/** /**
* 定义一个 元素的 HTML 节点类继承自 HtmlNode * 定义一个 元素的 HTML 节点类继承自 HtmlNode
* 该类负责在 HTML 中渲染 元素并处理其交互逻辑 * 该类负责在 HTML 中渲染 元素并处理其交互逻辑
*/ */
class SubStartNodeHtmlNode extends HtmlNode { class SubStartNodeHtmlNode extends HtmlNode {
resizeObserver = null; resizeObserver = null;
isMounted; // 标记组件是否已挂载 isMounted; // 标记组件是否已挂载
r; // 渲染函数 r; // 渲染函数
app; // Vue 应用实例 app; // Vue 应用实例
container = null; container = null;
/** /**
* 构造函数 * 构造函数
* @param props 传递给节点的属性包括模型图模型等 * @param props 传递给节点的属性包括模型图模型等
*/ */
constructor(props) { constructor(props) {
super(props); super(props);
this.initVueApp(props); this.initVueApp(props);
} }
initVueApp(props) { initVueApp(props) {
this.isMounted = false; this.isMounted = false;
this.hideAnchor = false; this.hideAnchor = false;
this.autoExpand = true; // 防止锚点被折叠 this.autoExpand = true; // 防止锚点被折叠
this.anchorsPreset = "default"; // 重置锚点预设 this.anchorsPreset = "default"; // 重置锚点预设
// 创建 元素的渲染函数 // 创建 元素的渲染函数
this.r = h(SubStartNode, { this.r = h(SubStartNode, {
model: props.model, model: props.model,
graphModel: props.graphModel, graphModel: props.graphModel,
properties: { properties: {
...props.model.getProperties(), ...props.model.getProperties(),
} }
}); });
// 创建 Vue 应用实例,并指定渲染函数 // 创建 Vue 应用实例,并指定渲染函数
this.app = createApp({ this.app = createApp({
render: () => this.r, render: () => this.r,
}); });
} }
/** /**
* HTML 内容设置到指定的根元素上 * HTML 内容设置到指定的根元素上
* @param rootEl 根元素 * @param rootEl 根元素
*/ */
async setHtml(rootEl) { async setHtml(rootEl) {
if (!this.isMounted) { if (!this.isMounted) {
this.isMounted = true; this.isMounted = true;
this.container = document.createElement("div"); this.container = document.createElement("div");
this.container.style.display = "inline-block"; // 关键:确保容器自适应内容 this.container.style.display = "inline-block"; // 关键:确保容器自适应内容
rootEl.appendChild(this.container); rootEl.appendChild(this.container);
this.app.use(ElementPlus); // 关键单独注册ElementPlus this.app.use(ElementPlus); // 关键单独注册ElementPlus
this.app.mount(this.container); this.app.mount(this.container);
await nextTick(); await nextTick();
this.setupSizeObserver(); this.setupSizeObserver();
} else { } else {
this.r.component.props.properties = this.props.model.getProperties(); this.r.component.props.properties = this.props.model.getProperties();
} }
} }
/** /**
* 获取节点文本内容 * 获取节点文本内容
* 对于元素返回 null因为其内容由特定组件渲染 * 对于元素返回 null因为其内容由特定组件渲染
* @returns {null} * @returns {null}
*/ */
getText() { getText() {
return null; return null;
} }
handleComponentInstance(data) { handleComponentInstance(data) {
// 将组件实例保存到节点模型 // 将组件实例保存到节点模型
this.props.model.setComponentInstance(data); this.props.model.setComponentInstance(data);
} }
handleContentChange() { handleContentChange() {
// 内容变化时强制更新尺寸 // 内容变化时强制更新尺寸
this.updateNodeSize(); this.updateNodeSize();
} }
// 渲染完成后获取实际尺寸 // 渲染完成后获取实际尺寸
updateNodeSize() { updateNodeSize() {
if (this.container) { if (this.container) {
const { SCALE_X, SCALE_Y } = this.props.graphModel.transformModel; const { SCALE_X, SCALE_Y } = this.props.graphModel.transformModel;
const node = this.container.querySelector(".node__container"); const node = this.container.querySelector(".node__container");
const rect = node.getBoundingClientRect(); const rect = node.getBoundingClientRect();
this.props.model.updateSize(rect.width / SCALE_X, rect.height / SCALE_Y); this.props.model.updateSize(rect.width / SCALE_X, rect.height / SCALE_Y);
} }
} }
setupSizeObserver() { setupSizeObserver() {
// 首次渲染立即检测 // 首次渲染立即检测
requestAnimationFrame(() => { requestAnimationFrame(() => {
this.updateNodeSize(); this.updateNodeSize();
// 持续监听变化 // 持续监听变化
this.resizeObserver = new ResizeObserver(() => { this.resizeObserver = new ResizeObserver(() => {
this.updateNodeSize(); this.updateNodeSize();
}); });
this.resizeObserver.observe(this.container); this.resizeObserver.observe(this.container);
}); });
} }
// 组件卸载时移除监听 // 组件卸载时移除监听
onDestroy() { onDestroy() {
this.resizeObserver?.disconnect(); this.resizeObserver?.disconnect();
} }
} }
/** /**
* 定义一个元素的 HTML 模型类继承自 HtmlNodeModel * 定义一个元素的 HTML 模型类继承自 HtmlNodeModel
* 该类主要设置节点的属性和样式 * 该类主要设置节点的属性和样式
*/ */
class SubStartNodeHtmlModel extends HtmlNodeModel { class SubStartNodeHtmlModel extends HtmlNodeModel {
initNodeData(data) { initNodeData(data) {
super.initNodeData(data); super.initNodeData(data);
} }
// 保存组件实例引用 // 保存组件实例引用
setComponentInstance(instance) { setComponentInstance(instance) {
this.componentInstance = instance; this.componentInstance = instance;
} }
// 验证表单 /**
async validateForm() { * 设置节点属性
if (this.componentInstance && this.componentInstance.validate) { * 包括宽度高度文本编辑属性等
try { */
const result = await this.componentInstance.validate(); setAttributes() {
if (result) { // 初始设置为0后续动态更新
return { valid: true, message: "验证通过" }; this.width = 0;
} else { this.height = 0;
return { valid: false, message: "验证失败" }; this.text.editable = false;
} }
} catch {
return { valid: false, message: "验证失败" }; updateSize(width, height) {
} this.width = width + 24;
} this.height = height + 50;
return { valid: true, message: "无验证方法" }; this.initNodeData(this); // 触发节点重绘
} }
/** // 定义节点只有左右两个锚点. 锚点位置通过中心点和宽度算出来。
* 设置节点属性 getDefaultAnchor() {
* 包括宽度高度文本编辑属性等 let _a = this,
*/ x = _a.x,
setAttributes() { y = _a.y,
// 初始设置为0后续动态更新 width = _a.width,
this.width = 0; height = _a.height;
this.height = 0; return [
this.text.editable = false; {
} x: x + width / 2 - 24,
y: y - 25,
updateSize(width, height) { name: "right",
this.width = width + 24; id: "".concat(this.id, "_1")
this.height = height + 50; },
this.initNodeData(this); // 触发节点重绘 ];
} }
// 定义节点只有左右两个锚点. 锚点位置通过中心点和宽度算出来。 /**
getDefaultAnchor() { * 获取节点轮廓样式
let _a = this, * 覆盖父类方法设置 stroke 属性为 none以适应特定的视觉效果
x = _a.x, * @returns {object} 节点轮廓样式
y = _a.y, */
width = _a.width, getOutlineStyle() {
height = _a.height; const style = super.getOutlineStyle();
return [ style.stroke = "none";
{ style.hover.stroke = "none";
x: x + width / 2 - 24, return style;
y: y - 25, }
name: "right", }
id: "".concat(this.id, "_1")
}, // 导出方法注册
]; export function registerSubStartNode(lf) {
} lf.register({
type: "subStart",
/** view: SubStartNodeHtmlNode,
* 获取节点轮廓样式 model: SubStartNodeHtmlModel,
* 覆盖父类方法设置 stroke 属性为 none以适应特定的视觉效果 });
* @returns {object} 节点轮廓样式 }
*/
getOutlineStyle() {
const style = super.getOutlineStyle();
style.stroke = "none";
style.hover.stroke = "none";
return style;
}
}
// 导出方法注册
export function registerSubStartNode(lf) {
lf.register({
type: "subStart",
view: SubStartNodeHtmlNode,
model: SubStartNodeHtmlModel,
});
}

View File

@ -1,314 +1,318 @@
// 导入 HtmlNode 及其模型,为后续继承做准备 // 导入 HtmlNode 及其模型,为后续继承做准备
import { HtmlNode, HtmlNodeModel, h as svgH } from "@logicflow/core"; import { HtmlNode, HtmlNodeModel, h as svgH } from "@logicflow/core";
// 导入 Vue 相关方法,用于渲染组件 // 导入 Vue 相关方法,用于渲染组件
import { createApp, h, nextTick } from "vue"; import { createApp, h, nextTick } from "vue";
import ElementPlus from "element-plus"; import ElementPlus from "element-plus";
// 导入 Vue 组件 // 导入 Vue 组件
import Switch from "./switch.vue"; import Switch from "./switch.vue";
import JsonViewer from 'vue3-json-viewer' import JsonViewer from 'vue3-json-viewer'
/** /**
* 定义一个 元素的 HTML 节点类继承自 HtmlNode * 定义一个 元素的 HTML 节点类继承自 HtmlNode
* 该类负责在 HTML 中渲染 元素并处理其交互逻辑 * 该类负责在 HTML 中渲染 元素并处理其交互逻辑
*/ */
class SwitchHtmlNode extends HtmlNode { class SwitchHtmlNode extends HtmlNode {
resizeObserver = null; resizeObserver = null;
isMounted; // 标记组件是否已挂载 isMounted; // 标记组件是否已挂载
r; // 渲染函数 r; // 渲染函数
app; // Vue 应用实例 app; // Vue 应用实例
container = null; container = null;
static reusePool = new Map(); // 节点复用池 static reusePool = new Map(); // 节点复用池
/** /**
* 构造函数 * 构造函数
* @param props 传递给节点的属性包括模型图模型等 * @param props 传递给节点的属性包括模型图模型等
*/ */
constructor(props) { constructor(props) {
super(props); super(props);
this.initVueApp(props); this.initVueApp(props);
} }
initVueApp(props) { initVueApp(props) {
this.isMounted = false; this.isMounted = false;
this.hideAnchor = false; this.hideAnchor = false;
this.autoExpand = true; // 防止锚点被折叠 this.autoExpand = true; // 防止锚点被折叠
this.anchorsPreset = "default"; // 重置锚点预设 this.anchorsPreset = "default"; // 重置锚点预设
// 创建 元素的渲染函数 // 创建 元素的渲染函数
this.r = h(Switch, { this.r = h(Switch, {
model: props.model, model: props.model,
graphModel: props.graphModel, graphModel: props.graphModel,
properties: { properties: {
...props.model.getProperties(), ...props.model.getProperties(),
}, },
text: props.model.text.value, text: props.model.text.value,
onContentChange: this.handleContentChange.bind(this), onContentChange: this.handleContentChange.bind(this),
onBindRef: this.handleComponentInstance.bind(this), onBindRef: this.handleComponentInstance.bind(this),
// 添加锚点相关回调 // 添加锚点相关回调
onAddAnchor: this.handleAddAnchor.bind(this), onAddAnchor: this.handleAddAnchor.bind(this),
onRemoveAnchor: this.handleRemoveAnchor.bind(this), onRemoveAnchor: this.handleRemoveAnchor.bind(this),
onChangeAnchor: this.handleChangeAnchor.bind(this) onChangeAnchor: this.handleChangeAnchor.bind(this)
}); });
// 创建 Vue 应用实例,并指定渲染函数 // 创建 Vue 应用实例,并指定渲染函数
this.app = createApp({ this.app = createApp({
render: () => this.r, render: () => this.r,
}); });
} }
/** /**
* HTML 内容设置到指定的根元素上 * HTML 内容设置到指定的根元素上
* @param rootEl 根元素 * @param rootEl 根元素
*/ */
async setHtml(rootEl) { async setHtml(rootEl) {
const nodeId = this.props.model.id; const nodeId = this.props.model.id;
if (SwitchHtmlNode.reusePool.has(nodeId)) { if (SwitchHtmlNode.reusePool.has(nodeId)) {
rootEl.appendChild(SwitchHtmlNode.reusePool.get(nodeId)); rootEl.appendChild(SwitchHtmlNode.reusePool.get(nodeId));
return; return;
} }
if (!this.isMounted) { if (!this.isMounted) {
this.isMounted = true; this.isMounted = true;
this.container = document.createElement("div"); this.container = document.createElement("div");
this.container.style.display = "inline-block"; // 关键:确保容器自适应内容 this.container.style.display = "inline-block"; // 关键:确保容器自适应内容
rootEl.appendChild(this.container); rootEl.appendChild(this.container);
this.app.use(ElementPlus); this.app.use(ElementPlus);
this.app.use(JsonViewer); this.app.use(JsonViewer);
this.app.mount(this.container); this.app.mount(this.container);
await nextTick(); await nextTick();
this.setupSizeObserver(); this.setupSizeObserver();
SwitchHtmlNode.reusePool.set(nodeId, this.container); SwitchHtmlNode.reusePool.set(nodeId, this.container);
} else { } else {
this.r.component.props.properties = this.props.model.getProperties(); this.r.component.props.properties = this.props.model.getProperties();
} }
} }
/** /**
* 获取节点文本内容 * 获取节点文本内容
* 对于元素返回 null因为其内容由特定组件渲染 * 对于元素返回 null因为其内容由特定组件渲染
* @returns {null} * @returns {null}
*/ */
getText() { getText() {
return null; return null;
} }
handleComponentInstance(data) { handleComponentInstance(data) {
// 将组件实例保存到节点模型 // 将组件实例保存到节点模型
this.props.model.setComponentInstance(data) this.props.model.setComponentInstance(data)
} }
handleContentChange() { handleContentChange() {
// 内容变化时强制更新尺寸 // 内容变化时强制更新尺寸
this.updateNodeSize(); this.updateNodeSize();
} }
// 处理添加锚点 // 处理添加锚点
handleAddAnchor(height, anchorId) { handleAddAnchor(height, anchorId) {
const { model } = this.props const { model } = this.props
model.addAnchor(height, anchorId) model.addAnchor(height, anchorId)
} }
// 处理删除锚点 // 处理删除锚点
handleRemoveAnchor(anchorId) { handleRemoveAnchor(anchorId) {
this.props.model.removeAnchor(anchorId); this.props.model.removeAnchor(anchorId);
} }
handleChangeAnchor(height, anchorId) { handleChangeAnchor(height, anchorId) {
const { model } = this.props const { model } = this.props
model.changeAnchorHeight(height, anchorId) model.changeAnchorHeight(height, anchorId)
} }
// 渲染完成后获取实际尺寸 // 渲染完成后获取实际尺寸
updateNodeSize() { updateNodeSize() {
if (this.container) { if (this.container) {
const { SCALE_X, SCALE_Y } = this.props.graphModel.transformModel; const { SCALE_X, SCALE_Y } = this.props.graphModel.transformModel;
const node = this.container.querySelector(".node__container"); const node = this.container.querySelector(".node__container");
const rect = node.getBoundingClientRect(); const rect = node.getBoundingClientRect();
this.props.model.updateSize(rect.width / SCALE_X, rect.height / SCALE_Y); this.props.model.updateSize(rect.width / SCALE_X, rect.height / SCALE_Y);
} }
} }
setupSizeObserver() { setupSizeObserver() {
// 首次渲染立即检测 // 首次渲染立即检测
requestAnimationFrame(() => { requestAnimationFrame(() => {
this.updateNodeSize(); this.updateNodeSize();
// 持续监听变化 // 持续监听变化
this.resizeObserver = new ResizeObserver(() => { this.resizeObserver = new ResizeObserver(() => {
this.updateNodeSize(); this.updateNodeSize();
}); });
this.resizeObserver.observe(this.container); this.resizeObserver.observe(this.container);
}); });
} }
// 组件卸载时移除监听 // 组件卸载时移除监听
onDestroy() { onDestroy() {
this.resizeObserver?.disconnect(); this.resizeObserver?.disconnect();
} }
} }
/** /**
* 定义一个元素的 HTML 模型类继承自 HtmlNodeModel * 定义一个元素的 HTML 模型类继承自 HtmlNodeModel
* 该类主要设置节点的属性和样式 * 该类主要设置节点的属性和样式
*/ */
class SwitchHtmlModel extends HtmlNodeModel { class SwitchHtmlModel extends HtmlNodeModel {
initNodeData(data) { initNodeData(data) {
super.initNodeData(data); super.initNodeData(data);
} }
// 返回动态锚点 // 返回动态锚点
addAnchor(height, anchorId) { addAnchor(height, anchorId) {
const properties = this.getProperties() const properties = this.getProperties()
const anchor = properties?.anchor || [] const anchor = properties?.anchor || []
anchor.push({ anchor.push({
id: anchorId, id: anchorId,
name: 'right', name: 'right',
x: this.x, x: this.x,
y: this.y, y: this.y,
height height
}) })
this.setProperties({ this.setProperties({
...properties, ...properties,
anchor anchor
}) })
this.getDefaultAnchor() this.getDefaultAnchor()
this.initNodeData(this) this.initNodeData(this)
} }
removeAnchor(anchorId) { removeAnchor(anchorId) {
const properties = this.getProperties() const properties = this.getProperties()
const anchor = properties?.anchor || [] const anchor = properties?.anchor || []
let nweAnchor = anchor.filter(item => item.id !== anchorId); let nweAnchor = anchor.filter(item => item.id !== anchorId);
this.setProperties({ this.setProperties({
...properties, ...properties,
anchor: nweAnchor anchor: nweAnchor
}) })
} }
changeAnchorHeight(height, anchorId) { changeAnchorHeight(height, anchorId) {
const properties = this.getProperties() const properties = this.getProperties()
const anchor = properties?.anchor || [] const anchor = properties?.anchor || []
anchor.forEach(item => { anchor.forEach(item => {
if (item.id === anchorId) { if (item.id === anchorId) {
item.height = height item.height = height
} }
}) })
this.setProperties({ this.setProperties({
...properties, ...properties,
anchor anchor
}) })
this.getDefaultAnchor() this.getDefaultAnchor()
this.initNodeData(this) this.initNodeData(this)
} }
// 保存组件实例引用 // 保存组件实例引用
setComponentInstance(instance) { setComponentInstance(instance) {
this.componentInstance = instance; this.componentInstance = instance;
} }
// 验证表单 closePopover() {
async validateForm() { this.componentInstance.closePopover()
if (this.componentInstance && this.componentInstance.validate) { }
try {
const result = await this.componentInstance.validate(); // 验证表单
if (result) { async validateForm() {
return { valid: true, message: "验证通过" }; if (this.componentInstance && this.componentInstance.validate) {
} else { try {
return { valid: false, message: "验证失败" }; const result = await this.componentInstance.validate();
} if (result) {
} catch { return { valid: true, message: "验证通过" };
return { valid: false, message: "验证失败" }; } else {
} return { valid: false, message: "验证失败" };
} }
return { valid: true, message: "无验证方法" }; } catch {
} return { valid: false, message: "验证失败" };
}
/** }
* 设置节点属性 return { valid: true, message: "无验证方法" };
* 包括宽度高度文本编辑属性等 }
*/
setAttributes() { /**
// 初始设置为0后续动态更新 * 设置节点属性
this.width = 0; * 包括宽度高度文本编辑属性等
this.height = 0; */
this.text.editable = false; setAttributes() {
} // 初始设置为0后续动态更新
this.width = 0;
updateSize(width, height) { this.height = 0;
this.width = width + 24; this.text.editable = false;
this.height = height + 50; }
// const properties = lf.getProperties(this.id)
// this.setProperties({ updateSize(width, height) {
// ...properties, this.width = width + 24;
// width: this.width, this.height = height + 50;
// height: this.height // const properties = lf.getProperties(this.id)
// }) // this.setProperties({
this.initNodeData(this); // 触发节点重绘 // ...properties,
} // width: this.width,
// height: this.height
// 定义节点只有左右两个锚点. 锚点位置通过中心点和宽度算出来。 // })
getDefaultAnchor() { this.initNodeData(this); // 触发节点重绘
let _a = this, }
x = _a.x,
y = _a.y, // 定义节点只有左右两个锚点. 锚点位置通过中心点和宽度算出来。
width = _a.width, getDefaultAnchor() {
height = _a.height; let _a = this,
const properties = this.getProperties() x = _a.x,
const anchor = properties?.anchor || [] y = _a.y,
// const { SCALE_Y } = this.graphModel.transformModel; width = _a.width,
const ids = [] height = _a.height;
anchor.forEach(item => { const properties = this.getProperties()
ids.push(item.id) const anchor = properties?.anchor || []
if (item.id !== "".concat(this.id, "_else")) { // const { SCALE_Y } = this.graphModel.transformModel;
item.x = x + width / 2 - 40 const ids = []
// item.y = (y - height / 2 + item.height + 60) / SCALE_Y anchor.forEach(item => {
item.y = y - height / 2 + item.height + 60 ids.push(item.id)
} else { if (item.id !== "".concat(this.id, "_else")) {
item.x = x + width / 2 - 40 item.x = x + width / 2 - 40
item.y = y + height / 2 - 80 // item.y = (y - height / 2 + item.height + 60) / SCALE_Y
} item.y = y - height / 2 + item.height + 60
}) } else {
item.x = x + width / 2 - 40
return [ item.y = y + height / 2 - 80
// { }
// x: x + width / 2 - 40, })
// y: y + height / 2 - 80,
// name: "right", return [
// id: "".concat(this.id, "_else") // {
// }, // x: x + width / 2 - 40,
{ // y: y + height / 2 - 80,
x: x - width / 2, // name: "right",
y: y - 25, // id: "".concat(this.id, "_else")
name: "left", // },
id: "".concat(this.id, "_entry") {
}, x: x - width / 2,
...anchor y: y - 25,
]; name: "left",
} id: "".concat(this.id, "_entry")
},
/** ...anchor
* 获取节点轮廓样式 ];
* 覆盖父类方法设置 stroke 属性为 none以适应特定的视觉效果 }
* @returns {object} 节点轮廓样式
*/ /**
getOutlineStyle() { * 获取节点轮廓样式
const style = super.getOutlineStyle(); * 覆盖父类方法设置 stroke 属性为 none以适应特定的视觉效果
style.stroke = "none"; * @returns {object} 节点轮廓样式
style.hover.stroke = "none"; */
return style; getOutlineStyle() {
} const style = super.getOutlineStyle();
} style.stroke = "none";
style.hover.stroke = "none";
// 导出方法注册 return style;
export function registerSwitch(lf) { }
lf.register({ }
type: "branch",
view: SwitchHtmlNode, // 导出方法注册
model: SwitchHtmlModel, export function registerSwitch(lf) {
}); lf.register({
} type: "branch",
view: SwitchHtmlNode,
model: SwitchHtmlModel,
});
}

View File

@ -1,6 +1,6 @@
<template> <template>
<div class="node__container" ref="switchRef" @mouseleave="setNodeProperties"> <div class="node__container" ref="switchRef" @mouseleave="setNodeProperties">
<NodeState :state="nodeOperatingStatus"> <NodeState :state="nodeOperatingStatus" :runtimes="runtimes" ref="nodeStateRef">
<template #input> <template #input>
<JsonViewer :value="inputJsonData" copyable boxed sort theme="light" /> <JsonViewer :value="inputJsonData" copyable boxed sort theme="light" />
</template> </template>
@ -385,6 +385,7 @@ const visibleChange = (value) => {
}; };
const nodeOperatingStatus = ref("NORMAL"); const nodeOperatingStatus = ref("NORMAL");
const runtimes = ref(0);
const inputJsonData = ref({}); const inputJsonData = ref({});
const outputJsonData = ref({}); const outputJsonData = ref({});
const errorInfoData = ref(''); const errorInfoData = ref('');
@ -406,6 +407,14 @@ watch(
} }
); );
const nodeStateRef = ref(null);
const closePopover = () => {
if (nodeStateRef.value) {
nodeStateRef.value.closePopover();
}
}
onMounted(() => { onMounted(() => {
emits("addAnchor", 280, "".concat(props.model.id, "_else")); emits("addAnchor", 280, "".concat(props.model.id, "_else"));
@ -414,6 +423,9 @@ onMounted(() => {
emitter.on("changeNodeState", (data) => { emitter.on("changeNodeState", (data) => {
if (data.nodeId === props.model.id) { if (data.nodeId === props.model.id) {
nodeOperatingStatus.value = data.status; nodeOperatingStatus.value = data.status;
if (data.endTime && data.startTime) {
runtimes.value = data.endTime - data.startTime;
}
let inputData = {}; let inputData = {};
let output = {}; let output = {};
errorInfoData.value = data?.message || '' errorInfoData.value = data?.message || ''
@ -446,6 +458,8 @@ onUnmounted(() => {
emitter.off("changeNodeState"); emitter.off("changeNodeState");
emitter.off("contentChange"); emitter.off("contentChange");
}); });
defineExpose({ closePopover })
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.node__container { .node__container {

View File

@ -24,8 +24,8 @@ export default defineConfig(({mode, command}) => {
'typescript', 'typescript',
], ],
include: [ include: [
// 确保其他依赖被优化 // 确保其他依赖被优化
'monaco-editor/esm/vs/language/typescript/monaco.contribution', 'monaco-editor/esm/vs/language/typescript/monaco.contribution',
], ],
}, },
resolve: { resolve: {
@ -47,11 +47,11 @@ export default defineConfig(({mode, command}) => {
proxy: { proxy: {
// https://cn.vitejs.dev/config/#server-proxy // https://cn.vitejs.dev/config/#server-proxy
'/dev-api': { '/dev-api': {
//杨 http://192.168.0.10:13080 //服务器 http://192.168.0.100:13080
//赵 http://10.148.108.58:13080 //李小龙 http://192.168.0.5:13080
// dev http://10.148.20.34:13080 // dev http://10.148.20.34:13080
// target: VITE_API_URL, // target: VITE_API_URL,
target: command === 'build' ? VITE_API_URL : 'http://192.168.0.100:13080', target: command === 'build' ? VITE_API_URL : 'http://192.168.0.5:13080',
changeOrigin: true, changeOrigin: true,
rewrite: (p) => p.replace(/^\/dev-api/, '') rewrite: (p) => p.replace(/^\/dev-api/, '')
} }