UPDATE: VERSION-20260315

This commit is contained in:
libertyspy
2026-03-15 19:32:20 +08:00
parent 83a38c6db8
commit f2e81c6e5c
16 changed files with 197 additions and 178 deletions

View File

@@ -0,0 +1,184 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2025 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
import { Edge, Graph, Path, Selection } from '@antv/x6';
import { createLineOptions, type ModelElement } from '../graph';
import type { Connecting } from '@antv/x6/lib/graph/options';
Graph.registerConnector(
'sequenceFlowConnector',
(s, e) => {
const offset = 4;
const deltaY = Math.abs(e.y - s.y);
const control = Math.floor((deltaY / 3) * 2);
const v1 = { x: s.x, y: s.y + offset + control };
const v2 = { x: e.x, y: e.y - offset - control };
return Path.parse(
`
M ${s.x} ${s.y}
L ${s.x} ${s.y + offset}
C ${v1.x} ${v1.y} ${v2.x} ${v2.y} ${e.x} ${e.y - offset}
L ${e.x} ${e.y}
`,
).serialize();
},
true,
);
export const createGraphConnectingAttributes = (): Partial<Connecting> => {
const lineOptions = createLineOptions();
return {
snap: true, // 当 snap 设置为 true 时连线的过程中距离节点或者连接桩 50px 时会触发自动吸附
allowBlank: false, // 是否允许连接到画布空白位置的点,默认为 true
allowLoop: false, // 是否允许创建循环连线,即边的起始节点和终止节点为同一节点,默认为 true
highlight: true, // 当连接到节点时,通过 sourceAnchor 来指定源节点的锚点。
connector: 'smooth',
connectionPoint: 'anchor', // 指定连接点,默认值为 boundary。
anchor: 'center',
// validateMagnet({ magnet }) {
// return magnet.getAttribute('port-group') !== 'top'
// },
// 验证连接
createEdge(this: Graph) {
const edge: Edge = this.createEdge({
shape: 'edge',
...lineOptions, // 应用动画配置
attrs: {
...lineOptions.attrs,
// 在创建边时覆盖箭头配置,确保移除箭头
line: {
...lineOptions.attrs?.line,
targetMarker: null,
sourceMarker: null,
}
},
animation: lineOptions.animation,
markup: lineOptions.markup,
});
return edge;
},
validateConnection(this: Graph, { sourceCell, targetCell }) {
console.error('validateConnection');
if (!sourceCell || !targetCell) return false;
// 核心逻辑:禁止节点连接自己(自环)
if (sourceCell === targetCell) {
return false;
}
// const sourceData = sourceCell.getData() as GraphElement;
const targetData = targetCell.getData() as ModelElement;
// 根节点不能作为子节点
if (targetData.category === 'root') {
return false;
}
// 4. 新增核心逻辑:检查源节点是否已有出边(已连接其他节点)
// const hasOutgoingEdge = this.getOutgoingEdges(sourceCell);
// if (hasOutgoingEdge && hasOutgoingEdge.length > 1) {
// return false;
// }
// 检查是否已存在相同连接
// const edges: Edge[] = this.getEdges();
// const existingConnection = edges.find(edge =>
// edge.getSourceCell() === sourceCell &&
// edge.getTargetCell() === targetCell,
// );
//
// return !existingConnection;
return true;
},
};
};
export const createGraphCanvas = (container: HTMLDivElement, readonly: boolean = false): Graph => {
const graph = new Graph({
container: container,
grid: {
size: 20,
visible: true,
type: 'dot',
// color: '#e5e7eb'
},
// 确保启用了异步渲染
async: true,
panning: {
enabled: true,
eventTypes: ['leftMouseDown', 'mouseWheel'],
},
mousewheel: {
enabled: true,
modifiers: 'ctrl',
factor: 1.1,
maxScale: 1.5,
minScale: 0.5,
},
highlighting: {
magnetAdsorbed: {
name: 'stroke',
args: {
attrs: {
fill: '#fff',
stroke: '#31d0c6',
strokeWidth: 4,
},
},
},
},
connecting: createGraphConnectingAttributes(),
scaling: {
min: 0.5,
max: 2,
},
// 背景配置
background: {},
// 交互配置
interacting: (cellView) => {
if (readonly) {
return false; // 只读模式下禁用所有交互
}
// 确保边(edge)的顶点交互权限开启
if (cellView.cell.isEdge()) {
return {
vertexAddable: true, // 允许添加顶点
vertexMovable: true, // 允许移动顶点
vertexDeletable: true, // 允许删除顶点
edgeMovable: true, // 允许整体拖动连线
arrowheadMovable: true, // 允许拖动箭头调整端点
};
}
// 节点的交互配置(保持不变)
return {
nodeMovable: true,
};
},
});
graph.use(
new Selection({
multiple: true,
rubberEdge: true,
rubberNode: true,
modifiers: 'shift',
rubberband: true,
}),
);
return graph;
};

View File

@@ -0,0 +1,105 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2026 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
import type { NullableString } from '@/types';
export interface GraphPosition {
x: number;
y: number;
}
export interface GraphRect {
width?: number;
height?: number;
x?: number;
y?: number;
}
export interface GraphDraggableElement {
id: number | null,
key?: NullableString,
name: NullableString,
description: NullableString,
category: NullableString,
draggable: boolean,
parent?: GraphDraggableElement,
children: GraphDraggableElement[]
[key: string]: unknown;
}
export interface GraphBaseElement {
id: number;
key: NullableString;
name: NullableString;
description: NullableString;
type: NullableString;
width: number;
height: number;
position: GraphPosition;
category: NullableString;
element?: GraphDraggableElement;
[key: string]: unknown;
}
export interface ElementParameter {
id: number,
templateId: number,
paramKey: NullableString,
dataType: NullableString,
defaultValue: NullableString,
description: NullableString,
templateType: NullableString,
}
export interface ElementVariable {
key: NullableString;
name: NullableString;
value: NullableString;
defaults: NullableString;
unit: NullableString;
}
export interface GraphTaskElement extends GraphBaseElement {
template: number;
templateType: NullableString,
inputs: any;
outputs: any;
order: number;
variables: ElementVariable[];
parameters: ElementParameter[];
children?: GraphTaskElement[],
[key: string]: unknown;
}
export interface ModelElement extends GraphBaseElement {
edges: GraphEdgeElement[];
}
export interface GraphEdgeElement {
id: number;
key: NullableString;
source: NullableString;
target: NullableString;
attrs: Record<any, any>;
router: Record<any, any>;
connector: any;
[key: string]: unknown;
}
export interface GraphContainer {
edges: GraphEdgeElement[];
nodes: GraphTaskElement[];
}

View File

@@ -0,0 +1,254 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2025 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
import { computed, type ComputedRef, ref, type Ref } from 'vue';
import { type Dom, Graph, Node } from '@antv/x6';
import type { NodeViewPositionEventArgs } from '@antv/x6/es/view/node/type';
import { createGraphCanvas } from './canvas';
import { EventListener } from '@/utils/event';
import type { ModelElement } from './element';
// import {createLineOptions} from './line'
export interface UseGraphCanvas {
container: Ref<HTMLDivElement | null>;
readonly: boolean;
eventListener: EventListener;
currentZoom: Ref<number>;
graph: ComputedRef<Graph>;
zoomIn: () => void;
zoomOut: () => void;
fitToScreen: () => void;
centerContent: () => void;
resizeCanvas: () => void;
handleGraphEvent: (name: string, fn: Function) => void;
emitGraphEvent: (name: string, options?: any) => void;
createCanvas: (c: HTMLDivElement) => Graph;
}
export const useGraphCanvas = (readonly: boolean = false): UseGraphCanvas => {
const graph = ref<Graph | null>(null);
const container = ref<HTMLDivElement | null>(null);
const eventListener = new EventListener();
const currentZoom = ref<number>(0);
const handleGraphEvent = (name: string, fn: Function) => {
eventListener.on(name, fn);
};
const emitGraphEvent = (name: string, options?: any): void => {
eventListener.emit(name, options);
};
const zoomIn = (): void => {
if (graph.value) {
const zoom = graph.value.zoom();
graph.value.zoom(zoom + 0.1);
}
};
const zoomOut = (): void => {
if (graph.value) {
const zoom = graph.value.zoom();
graph.value.zoom(Math.max(0.1, zoom - 0.1));
}
};
const fitToScreen = () => {
if (graph.value) {
graph.value.zoomToFit({ padding: 20 });
}
};
const centerContent = () => {
if (graph.value) {
graph.value.centerContent();
}
};
const resizeCanvas = () => {
if (graph.value) {
graph.value?.resize();
}
};
const initEvents = () => {
if (!graph.value) {
return;
}
graph.value.on('keydown', ({ e }: any) => {
if (e.key === 'Delete' || e.key === 'Backspace') {
const cells = graph.value?.getSelectedCells();
if (cells && cells.length) {
graph.value?.removeCells(cells);
// 通知父组件更新状态
emitGraphEvent('cells:removed', cells);
}
}
});
graph.value.on('scale', (ctx) => {
currentZoom.value = ctx.sx;
emitGraphEvent('scale', ctx);
});
// 监听画布空白点击
graph.value.on('blank:click', () => {
graph.value?.cleanSelection();
emitGraphEvent('blank:click');
});
// 监听连线删除
graph.value.on('edge:removed', ({ edge }) => {
emitGraphEvent('edge:removed', edge); // 添加此行
});
graph.value.on('edge:added', ({ edge }) => {
// const lineOptions = createLineOptions();
// edge.setAttrs(lineOptions.attrs);
// edge.set(lineOptions.animation);
// edge.setMarkup(lineOptions.markup);
emitGraphEvent('edge:added', edge); // 添加此行
});
graph.value.on('edge:contextmenu', (ctx) => {
emitGraphEvent('edge:contextmenu', ctx);
});
graph.value.on('edge:connect:abort', () => {
// 当连线被拖拽到空白区域后释放,自动移除这条无效连线
const edges = graph.value?.getEdges();
const invalidEdges = (edges ?? []).filter(edge =>
!edge.getSourceCell() || !edge.getTargetCell(),
);
if (invalidEdges.length) {
graph.value?.removeCells(invalidEdges);
}
});
// 监听连接失败
graph.value.on('edge:connect:invalid', () => {
emitGraphEvent('edge:connect:invalid');
});
graph.value.on('edge:click', (edge) => {
emitGraphEvent('edge:connect:invalid', edge);
});
graph.value.on('edge:connected', ({ edge }) => {
const sourceNode = edge.getSourceCell() as Node;
const targetNode = edge.getTargetCell() as Node;
if (sourceNode && targetNode) {
const sourceData = sourceNode.getData() as ModelElement;
const targetData = targetNode.getData() as ModelElement;
// 将连线存储到节点数据中
const sourceEdges = sourceData.edges || [];
const existingEdge = sourceEdges.find(e => e.target === targetNode.id);
if (!existingEdge) {
sourceEdges.push({
id: sourceData.id,
key: edge.id,
source: sourceNode.id,
sourceName: sourceData.name,
connector: {},
router: {},
attrs: {},
target: targetNode.id,
targetName: targetData.name,
});
sourceNode.replaceData({ ...sourceData, edges: sourceEdges });
}
}
edge.attr('line/stroke', '#3b82f6'); // 显式设置颜色
edge.attr('line/strokeWidth', 2); // 显式设置宽度
// edge.refresh() // 刷新连线
// graph.paint() // 重绘画布
emitGraphEvent('edge:connected', edge);
});
graph.value.on('node:click', (ctx: NodeViewPositionEventArgs<Dom.ClickEvent>) => {
console.info('node click', ctx);
emitGraphEvent('node:click', ctx);
});
// 监听节点选中事件
graph.value.on('node:selected', ({ node }) => {
console.info('node select', node);
emitGraphEvent('node:selected', node);
});
// 监听节点取消选中
graph.value.on('node:unselected', () => {
emitGraphEvent('node:unselected');
});
// 监听节点鼠标移入,显示连接点
graph.value.on('node:mouseenter', (ctx) => {
emitGraphEvent('node:mouseenter', ctx);
});
// 监听节点鼠标移出,隐藏连接点
graph.value.on('node:mouseleave', (ctx) => {
emitGraphEvent('node:mouseleave', ctx);
});
// 监听节点状态变化
graph.value.on('node:change:data', (ctx) => {
const edges = graph.value?.getIncomingEdges(ctx.node);
const { status } = ctx.node.getData();
edges?.forEach((edge) => {
if (status === 'running') {
edge.attr('line/strokeDasharray', 5);
edge.attr('line/style/animation', 'running-line 30s infinite linear');
} else {
edge.attr('line/strokeDasharray', '');
edge.attr('line/style/animation', '');
}
});
emitGraphEvent('node:change:data', ctx);
});
};
const createCanvas = (c: HTMLDivElement): Graph => {
container.value = c;
graph.value = createGraphCanvas(c, readonly);
initEvents();
emitGraphEvent('created', graph.value);
return graph.value as Graph;
};
const graphInstance = computed(() => graph.value);
return {
container,
readonly,
graph: graphInstance,
eventListener,
currentZoom,
emitGraphEvent,
handleGraphEvent,
zoomIn,
zoomOut,
fitToScreen,
centerContent,
resizeCanvas,
createCanvas,
} as UseGraphCanvas;
};

View File

@@ -0,0 +1,16 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2026 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
export * from './line'
export * from './ports'
export * from './element'
export * from './canvas'
export * from './hooks'
export * from './props'
export * from './utils'

View File

@@ -0,0 +1,51 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2026 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
import { Shape } from '@antv/x6';
export const createLineOptions = (): any => {
return {
markup: [
{
tagName: 'circle',
selector: 'marker',
attrs: {
stroke: 'none',
r: 3,
},
},
...Shape.Edge.getMarkup() as any,
],
attrs: {
line: {
stroke: '#5da0df',
strokeWidth: 2,
strokeDasharray: ' ',
strokeDashoffset: 0,
// 去掉箭头
targetMarker: null,
sourceMarker: null,
},
marker: {
fill: '#5da0df',
atConnectionRatio: 0,
},
},
animation: [
[
{ 'attrs/marker/atConnectionRatio': 1 },
{
duration: 2000,
iterations: Infinity,
},
],
],
};
};

View File

@@ -0,0 +1,51 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2025 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
export const createPort = (name: string = 'top', args: Record<any, any> = { dx: 0 }) => {
return {
position: { name: name, args: args },
attrs: {
circle: {
r: 4, // 大小
magnet: true,
stroke: '#1b5e9f', // 边框颜色
strokeWidth: 1, // 边框大小
fill: '#3578bf', // 填充颜色
style: {
visibility: 'visible', // 是否可见
},
},
},
};
};
export const createPorts = (top: boolean = true, right: boolean = true, bottom: boolean = true, left: boolean = true) => {
const groups: any = {};
const items: any = [];
if (top) {
groups['top'] = createPort('top');
items.push({ group: 'top', id: 'top' });
}
if (right) {
groups['right'] = createPort('right');
items.push({ group: 'right', id: 'right' });
}
if (bottom) {
groups['bottom'] = createPort('bottom');
items.push({ group: 'bottom', id: 'bottom' });
}
if (left) {
groups['left'] = createPort('left');
items.push({ group: 'left', id: 'left' });
}
return {
groups: groups,
items: items,
};
};

View File

@@ -0,0 +1,29 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2025 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
import { Graph, Node } from '@antv/x6';
import { type ExtractPropTypes, type PropType } from 'vue';
import type { ModelElement } from './element';
export const elementProps = {
node: {
type: Object as PropType<Node>,
required: true,
},
graph: {
type: Object as PropType<Graph>,
required: true,
},
element: {
type: Object as PropType<ModelElement>,
required: false,
},
};
export type ElementPropsType = ExtractPropTypes<typeof elementProps>

View File

@@ -0,0 +1,112 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2026 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
import type { GraphContainer, GraphEdgeElement, GraphTaskElement } from '../graph';
import { Edge, Graph, Node } from '@antv/x6';
export const defaultHeight: Record<string, number> = {
component: 110,
};
export const createGraphTaskElement = (element: GraphTaskElement, width: number = 250, height: number = 120, shape: string = 'task'): any => {
let realHeight = defaultHeight[element.category as string];
if (!realHeight) {
realHeight = 120;
}
if(element.group === 'condition' || element.group === 'control') {
realHeight = 60;
}
return {
shape: shape ?? 'task',
id: element.key,
position: {
x: element.position?.x || 0,
y: element.position?.y || 0,
},
size: {
width: width,
height: realHeight,
},
attrs: {
label: {
text: element.name,
},
},
data: element,
};
};
export const resolveGraphTaskElements = (graph: Graph): GraphTaskElement[] => {
const taskElements: GraphTaskElement[] = [];
if (graph) {
const nodes = graph?.getNodes() as Node[];
if (nodes) {
nodes.forEach(node => {
const nodeData = node.getData() as GraphTaskElement;
const newElement = {
...nodeData,
key: node.id,
position: node.getPosition(),
width: node.getSize().width,
height: node.getSize().height,
};
taskElements.push(newElement);
});
}
}
return taskElements;
};
export const resolveGraphEdgeElements = (graph: Graph): GraphEdgeElement[] => {
const edgeElements: GraphEdgeElement[] = [];
if (graph) {
const graphEdges = graph?.getEdges() ?? [] as Edge[];
if (graphEdges) {
graphEdges.forEach(edge => {
const nodeData = edge.getData() as GraphTaskElement;
edgeElements.push({
id: nodeData?.id ?? 0,
key: edge.id,
type: 'edge',
status: nodeData?.status,
source: edge.getSource() ? edge.getSource() as unknown as string : null,
target: edge.getSource() ? edge.getTarget() as unknown as string : null,
attrs: edge.getAttrs() ?? {},
router: edge.getRouter() ?? {},
connector: edge.getConnector() ?? null,
});
});
}
}
return edgeElements;
};
export const resolveGraph = (graph: Graph): GraphContainer => {
const nodes: GraphTaskElement[] = resolveGraphTaskElements(graph);
const edges: GraphEdgeElement[] = resolveGraphEdgeElements(graph);
return {
nodes,
edges,
};
};
export const hasElements = (graph: Graph): boolean => {
if (graph) {
const taskElements: GraphTaskElement[] = resolveGraphTaskElements(graph);
return taskElements.length > 0;
}
return false;
};
export const hasRootElementNode = (graph: Graph): boolean => {
if (graph) {
const taskElements: GraphTaskElement[] = resolveGraphTaskElements(graph);
return taskElements.filter(e => e.type === 'root').length === 1;
}
return false;
};