@antv/g6 5.0.15 → 5.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/dist/g6.min.js +2 -2
  2. package/dist/lib/behaviors/drag-canvas.d.ts +13 -0
  3. package/dist/lib/behaviors/scroll-canvas.d.ts +7 -0
  4. package/dist/lib/behaviors/zoom-canvas.d.ts +7 -0
  5. package/dist/lib/elements/edges/base-edge.d.ts +2 -2
  6. package/dist/lib/elements/edges/polyline.d.ts +3 -20
  7. package/dist/lib/plugins/index.d.ts +2 -0
  8. package/dist/lib/plugins/snapline/index.d.ts +95 -0
  9. package/dist/lib/runtime/element.d.ts +1 -0
  10. package/dist/lib/runtime/viewport.d.ts +8 -0
  11. package/dist/lib/types/index.d.ts +1 -0
  12. package/dist/lib/types/router.d.ts +103 -0
  13. package/dist/lib/utils/bbox.d.ts +8 -0
  14. package/dist/lib/utils/router/orth.d.ts +8 -8
  15. package/dist/lib/utils/router/shortest-path.d.ts +57 -0
  16. package/dist/lib/utils/text.d.ts +1 -1
  17. package/dist/lib/utils/visibility.d.ts +2 -1
  18. package/dist/lib/version.d.ts +1 -1
  19. package/esm/behaviors/brush-select.js +11 -6
  20. package/esm/behaviors/brush-select.js.map +1 -1
  21. package/esm/behaviors/drag-canvas.d.ts +13 -0
  22. package/esm/behaviors/drag-canvas.js +10 -1
  23. package/esm/behaviors/drag-canvas.js.map +1 -1
  24. package/esm/behaviors/optimize-viewport-transform.js +1 -1
  25. package/esm/behaviors/optimize-viewport-transform.js.map +1 -1
  26. package/esm/behaviors/scroll-canvas.d.ts +7 -0
  27. package/esm/behaviors/scroll-canvas.js +3 -1
  28. package/esm/behaviors/scroll-canvas.js.map +1 -1
  29. package/esm/behaviors/zoom-canvas.d.ts +7 -0
  30. package/esm/behaviors/zoom-canvas.js +3 -1
  31. package/esm/behaviors/zoom-canvas.js.map +1 -1
  32. package/esm/elements/edges/base-edge.d.ts +2 -2
  33. package/esm/elements/edges/base-edge.js +10 -4
  34. package/esm/elements/edges/base-edge.js.map +1 -1
  35. package/esm/elements/edges/polyline.d.ts +3 -20
  36. package/esm/elements/edges/polyline.js +29 -34
  37. package/esm/elements/edges/polyline.js.map +1 -1
  38. package/esm/elements/shapes/base-shape.js +1 -1
  39. package/esm/elements/shapes/base-shape.js.map +1 -1
  40. package/esm/plugins/index.d.ts +2 -0
  41. package/esm/plugins/index.js +1 -0
  42. package/esm/plugins/index.js.map +1 -1
  43. package/esm/plugins/snapline/index.d.ts +95 -0
  44. package/esm/plugins/snapline/index.js +268 -0
  45. package/esm/plugins/snapline/index.js.map +1 -0
  46. package/esm/registry/build-in.js +3 -2
  47. package/esm/registry/build-in.js.map +1 -1
  48. package/esm/runtime/element.d.ts +1 -0
  49. package/esm/runtime/element.js +10 -4
  50. package/esm/runtime/element.js.map +1 -1
  51. package/esm/runtime/viewport.d.ts +8 -0
  52. package/esm/runtime/viewport.js +35 -2
  53. package/esm/runtime/viewport.js.map +1 -1
  54. package/esm/types/index.d.ts +1 -0
  55. package/esm/types/router.d.ts +103 -0
  56. package/esm/types/router.js +2 -0
  57. package/esm/types/router.js.map +1 -0
  58. package/esm/utils/bbox.d.ts +8 -0
  59. package/esm/utils/bbox.js +19 -0
  60. package/esm/utils/bbox.js.map +1 -1
  61. package/esm/utils/router/orth.d.ts +8 -8
  62. package/esm/utils/router/orth.js +13 -7
  63. package/esm/utils/router/orth.js.map +1 -1
  64. package/esm/utils/router/shortest-path.d.ts +57 -0
  65. package/esm/utils/router/shortest-path.js +387 -0
  66. package/esm/utils/router/shortest-path.js.map +1 -0
  67. package/esm/utils/text.d.ts +1 -1
  68. package/esm/utils/visibility.d.ts +2 -1
  69. package/esm/utils/visibility.js +3 -2
  70. package/esm/utils/visibility.js.map +1 -1
  71. package/esm/version.d.ts +1 -1
  72. package/esm/version.js +1 -1
  73. package/lib/behaviors/brush-select.js +11 -6
  74. package/lib/behaviors/brush-select.js.map +1 -1
  75. package/lib/behaviors/drag-canvas.d.ts +13 -0
  76. package/lib/behaviors/drag-canvas.js +10 -1
  77. package/lib/behaviors/drag-canvas.js.map +1 -1
  78. package/lib/behaviors/optimize-viewport-transform.js +1 -1
  79. package/lib/behaviors/optimize-viewport-transform.js.map +1 -1
  80. package/lib/behaviors/scroll-canvas.d.ts +7 -0
  81. package/lib/behaviors/scroll-canvas.js +3 -1
  82. package/lib/behaviors/scroll-canvas.js.map +1 -1
  83. package/lib/behaviors/zoom-canvas.d.ts +7 -0
  84. package/lib/behaviors/zoom-canvas.js +3 -1
  85. package/lib/behaviors/zoom-canvas.js.map +1 -1
  86. package/lib/elements/edges/base-edge.d.ts +2 -2
  87. package/lib/elements/edges/base-edge.js +9 -3
  88. package/lib/elements/edges/base-edge.js.map +1 -1
  89. package/lib/elements/edges/polyline.d.ts +3 -20
  90. package/lib/elements/edges/polyline.js +29 -34
  91. package/lib/elements/edges/polyline.js.map +1 -1
  92. package/lib/elements/shapes/base-shape.js +1 -1
  93. package/lib/elements/shapes/base-shape.js.map +1 -1
  94. package/lib/plugins/index.d.ts +2 -0
  95. package/lib/plugins/index.js +3 -1
  96. package/lib/plugins/index.js.map +1 -1
  97. package/lib/plugins/snapline/index.d.ts +95 -0
  98. package/lib/plugins/snapline/index.js +272 -0
  99. package/lib/plugins/snapline/index.js.map +1 -0
  100. package/lib/registry/build-in.js +2 -1
  101. package/lib/registry/build-in.js.map +1 -1
  102. package/lib/runtime/element.d.ts +1 -0
  103. package/lib/runtime/element.js +9 -3
  104. package/lib/runtime/element.js.map +1 -1
  105. package/lib/runtime/viewport.d.ts +8 -0
  106. package/lib/runtime/viewport.js +34 -1
  107. package/lib/runtime/viewport.js.map +1 -1
  108. package/lib/types/index.d.ts +1 -0
  109. package/lib/types/router.d.ts +103 -0
  110. package/lib/types/router.js +3 -0
  111. package/lib/types/router.js.map +1 -0
  112. package/lib/utils/bbox.d.ts +8 -0
  113. package/lib/utils/bbox.js +20 -0
  114. package/lib/utils/bbox.js.map +1 -1
  115. package/lib/utils/router/orth.d.ts +8 -8
  116. package/lib/utils/router/orth.js +13 -7
  117. package/lib/utils/router/orth.js.map +1 -1
  118. package/lib/utils/router/shortest-path.d.ts +57 -0
  119. package/lib/utils/router/shortest-path.js +394 -0
  120. package/lib/utils/router/shortest-path.js.map +1 -0
  121. package/lib/utils/text.d.ts +1 -1
  122. package/lib/utils/visibility.d.ts +2 -1
  123. package/lib/utils/visibility.js +3 -2
  124. package/lib/utils/visibility.js.map +1 -1
  125. package/lib/version.d.ts +1 -1
  126. package/lib/version.js +1 -1
  127. package/package.json +1 -1
  128. package/src/behaviors/brush-select.ts +12 -5
  129. package/src/behaviors/drag-canvas.ts +24 -1
  130. package/src/behaviors/optimize-viewport-transform.ts +1 -0
  131. package/src/behaviors/scroll-canvas.ts +9 -1
  132. package/src/behaviors/zoom-canvas.ts +9 -1
  133. package/src/elements/edges/base-edge.ts +19 -5
  134. package/src/elements/edges/polyline.ts +33 -68
  135. package/src/elements/shapes/base-shape.ts +1 -1
  136. package/src/plugins/grid-line.ts +1 -1
  137. package/src/plugins/index.ts +2 -0
  138. package/src/plugins/snapline/index.ts +383 -0
  139. package/src/registry/build-in.ts +3 -1
  140. package/src/runtime/element.ts +11 -4
  141. package/src/runtime/viewport.ts +42 -3
  142. package/src/types/index.ts +1 -0
  143. package/src/types/router.ts +107 -0
  144. package/src/utils/bbox.ts +24 -0
  145. package/src/utils/router/orth.ts +19 -10
  146. package/src/utils/router/shortest-path.ts +470 -0
  147. package/src/utils/text.ts +1 -1
  148. package/src/utils/visibility.ts +3 -1
  149. package/src/version.ts +1 -1
@@ -18,7 +18,7 @@ import type {
18
18
  } from '../../types';
19
19
  import { getBBoxHeight, getBBoxWidth, getNodeBBox } from '../../utils/bbox';
20
20
  import { getArrowSize, getBadgePositionStyle, getCubicLoopPath, getLabelPositionStyle } from '../../utils/edge';
21
- import { findPorts, getConnectionPoint, isSameNode } from '../../utils/element';
21
+ import { findPorts, getConnectionPoint, getPortPosition, isSameNode } from '../../utils/element';
22
22
  import { omitStyleProps, subStyleProps } from '../../utils/prefix';
23
23
  import { parseSize } from '../../utils/size';
24
24
  import { mergeOptions } from '../../utils/style';
@@ -153,7 +153,7 @@ export interface BaseEdgeStyleProps
153
153
  /**
154
154
  * <zh/> 在路径除了 “起点” 和 “终点” 之外的每一个顶点上放置标记图形。在内部实现中,由于我们会把路径中部分命令转换成 C 命令,因此这些顶点实际是三阶贝塞尔曲线的控制点
155
155
  *
156
- * <en/> Place a marker graphic on each vertex of the path except for the "start point" and "end point". In the internal implementation, because we will convert some commands in the path to C commands, these vertices are actually the control points of the cubic Bezier curve
156
+ * <en/> Place a marker graphic on each vertex of the path except for the "start point" and "end point". In the internal implementation, because we will convert some commands in the path to C commands, these controlPoints are actually the control points of the cubic Bezier curve
157
157
  */
158
158
  markerMid?: DisplayObject | null;
159
159
  /**
@@ -258,14 +258,28 @@ export abstract class BaseEdge extends BaseElement<BaseEdgeStyleProps> implement
258
258
  return getCubicLoopPath(node, placement, clockwise, dist, sourcePort, targetPort);
259
259
  }
260
260
 
261
- protected getEndpoints(attributes: ParsedBaseEdgeStyleProps): [Point, Point] {
261
+ protected getEndpoints(
262
+ attributes: ParsedBaseEdgeStyleProps,
263
+ optimize = true,
264
+ controlPoints: Point[] | (() => Point[]) = [],
265
+ ): [Point, Point] {
262
266
  const { sourcePort: sourcePortKey, targetPort: targetPortKey } = attributes;
263
267
  const { sourceNode, targetNode } = this;
264
268
 
265
269
  const [sourcePort, targetPort] = findPorts(sourceNode, targetNode, sourcePortKey, targetPortKey);
266
270
 
267
- const sourcePoint = getConnectionPoint(sourcePort || sourceNode, targetPort || targetNode);
268
- const targetPoint = getConnectionPoint(targetPort || targetNode, sourcePort || sourceNode);
271
+ if (!optimize) {
272
+ const sourcePoint = sourcePort ? getPortPosition(sourcePort) : sourceNode.getCenter();
273
+ const targetPoint = targetPort ? getPortPosition(targetPort) : targetNode.getCenter();
274
+ return [sourcePoint, targetPoint];
275
+ }
276
+
277
+ const _controlPoints = typeof controlPoints === 'function' ? controlPoints() : controlPoints;
278
+ const sourcePoint = getConnectionPoint(sourcePort || sourceNode, _controlPoints[0] || targetPort || targetNode);
279
+ const targetPoint = getConnectionPoint(
280
+ targetPort || targetNode,
281
+ _controlPoints[_controlPoints.length - 1] || sourcePort || sourceNode,
282
+ );
269
283
 
270
284
  return [sourcePoint, targetPoint];
271
285
  }
@@ -1,11 +1,11 @@
1
1
  import type { DisplayObjectConfig } from '@antv/g';
2
2
  import type { PathArray } from '@antv/util';
3
- import type { LoopStyleProps, Padding, Point, Port } from '../../types';
3
+ import type { LoopStyleProps, Point, PolylineRouter } from '../../types';
4
4
  import { getBBoxHeight, getBBoxWidth, getNodeBBox } from '../../utils/bbox';
5
5
  import { getPolylineLoopPath, getPolylinePath } from '../../utils/edge';
6
- import { findPorts, getConnectionPoint, getPortPosition } from '../../utils/element';
7
6
  import { subStyleProps } from '../../utils/prefix';
8
7
  import { orth } from '../../utils/router/orth';
8
+ import { aStarSearch } from '../../utils/router/shortest-path';
9
9
  import { mergeOptions } from '../../utils/style';
10
10
  import type { BaseEdgeStyleProps } from './base-edge';
11
11
  import { BaseEdge } from './base-edge';
@@ -35,24 +35,9 @@ export interface PolylineStyleProps extends BaseEdgeStyleProps {
35
35
  * <en/> Whether to enable routing, it is enabled by default and controlPoints will be automatically included
36
36
  * @defaultValue false
37
37
  */
38
- router?: boolean;
39
- /**
40
- * <zh/> 路由名称,目前支持 'orth'
41
- *
42
- * <en/> Routing name, currently supports 'orth'
43
- * @defaultValue 'orth'
44
- * @remarks
45
- * <img width="300" src="https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*8Ia2RJFFQSoAAAAAAAAAAAAADmJ7AQ/original" />
46
- */
47
- routerName?: 'orth';
48
- /**
49
- * <zh/> 节点边距
50
- *
51
- * <en/> Padding for routing calculation
52
- * @defaultValue 10
53
- */
54
- routerPadding?: Padding;
38
+ router?: PolylineRouter;
55
39
  }
40
+
56
41
  type ParsedPolylineStyleProps = Required<PolylineStyleProps>;
57
42
 
58
43
  /**
@@ -65,63 +50,42 @@ export class Polyline extends BaseEdge {
65
50
  radius: 0,
66
51
  controlPoints: [],
67
52
  router: false,
68
- routerName: 'orth',
69
- routerPadding: 10,
70
53
  };
71
54
 
72
55
  constructor(options: DisplayObjectConfig<PolylineStyleProps>) {
73
56
  super(mergeOptions({ style: Polyline.defaultStyleProps }, options));
74
57
  }
75
58
 
76
- protected getKeyPath(attributes: ParsedPolylineStyleProps): PathArray {
77
- const { radius } = attributes;
59
+ protected getPoints(attributes: ParsedPolylineStyleProps): Point[] {
60
+ const { router } = attributes;
78
61
  const { sourceNode, targetNode } = this;
79
- // 1. 获取连接点(若有连接桩,取连接桩中心;反之,取节点中心)和连接桩 | Get connection points (if port, take port center; otherwise, take node center) and ports
80
- const { sourcePoint, targetPoint, sourcePort, targetPort } = this.getEndpointsAndPorts(attributes);
81
-
82
- // 2. 计算控制点 | Calculate control points
83
- const controlPoints = this.getControlPoints(attributes, sourcePoint, targetPoint);
84
-
85
- // 3. 计算实际的连接点 | Calculate the actual connection points
86
- const newSourcePoint = getConnectionPoint(sourcePort || sourceNode, controlPoints[0] || targetPort || targetNode);
87
- const newTargetPoint = getConnectionPoint(
88
- targetPort || targetNode,
89
- controlPoints[controlPoints.length - 1] || sourcePort || sourceNode,
90
- );
91
-
92
- // 4. 获取路径 | Get the path
93
- return getPolylinePath([newSourcePoint, ...controlPoints, newTargetPoint], radius);
62
+ const [sourcePoint, targetPoint] = this.getEndpoints(attributes, false);
63
+
64
+ let controlPoints: Point[] = [];
65
+
66
+ if (!router) {
67
+ controlPoints = attributes.controlPoints;
68
+ } else {
69
+ if (router.type === 'shortest-path') {
70
+ const nodes = this.context.element!.getNodes();
71
+ controlPoints = aStarSearch(sourceNode, targetNode, nodes, router);
72
+ if (!controlPoints.length) {
73
+ controlPoints = orth(sourcePoint, targetPoint, sourceNode, targetNode, attributes.controlPoints, {
74
+ padding: router.offset,
75
+ });
76
+ }
77
+ } else if (router.type === 'orth') {
78
+ controlPoints = orth(sourcePoint, targetPoint, sourceNode, targetNode, attributes.controlPoints, router);
79
+ }
80
+ }
81
+
82
+ const [newSourcePoint, newTargetPoint] = this.getEndpoints(attributes, true, controlPoints);
83
+ return [newSourcePoint, ...controlPoints, newTargetPoint];
94
84
  }
95
85
 
96
- private getEndpointsAndPorts(attributes: ParsedPolylineStyleProps): {
97
- sourcePoint: Point;
98
- targetPoint: Point;
99
- sourcePort: Port | undefined;
100
- targetPort: Port | undefined;
101
- } {
102
- const { sourcePort: sourcePortKey, targetPort: targetPortKey } = attributes;
103
- const { sourceNode, targetNode } = this;
104
-
105
- const [sourcePort, targetPort] = findPorts(sourceNode, targetNode, sourcePortKey, targetPortKey);
106
-
107
- return {
108
- sourcePoint: sourcePort ? getPortPosition(sourcePort) : sourceNode.getCenter(),
109
- targetPoint: targetPort ? getPortPosition(targetPort) : targetNode.getCenter(),
110
- sourcePort,
111
- targetPort,
112
- };
113
- }
114
-
115
- protected getControlPoints(attributes: ParsedPolylineStyleProps, sourcePoint: Point, targetPoint: Point): Point[] {
116
- const { controlPoints, router, routerPadding } = attributes;
117
- const { sourceNode, targetNode } = this;
118
-
119
- if (!router) return [...controlPoints];
120
-
121
- const sourceBBox = getNodeBBox(sourceNode, routerPadding);
122
- const targetBBox = getNodeBBox(targetNode, routerPadding);
123
-
124
- return orth(sourcePoint, targetPoint, sourceBBox, targetBBox, controlPoints, routerPadding);
86
+ protected getKeyPath(attributes: ParsedPolylineStyleProps): PathArray {
87
+ const points = this.getPoints(attributes);
88
+ return getPolylinePath(points, attributes.radius);
125
89
  }
126
90
 
127
91
  protected getLoopPath(attributes: ParsedPolylineStyleProps): PathArray {
@@ -129,7 +93,8 @@ export class Polyline extends BaseEdge {
129
93
  const node = this.sourceNode;
130
94
 
131
95
  const bbox = getNodeBBox(node);
132
- // 默认转折点距离为 bbox 的最大宽高的 1/4 | Default distance of the turning point is 1/4 of the maximum width and height of the bbox
96
+ // 默认转折点距离为 bbox 的最大宽高的 1/4
97
+ // Default distance of the turning point is 1/4 of the maximum width and height of the bbox
133
98
  const defaultDist = Math.max(getBBoxWidth(bbox), getBBoxHeight(bbox)) / 4;
134
99
 
135
100
  const {
@@ -222,7 +222,7 @@ export abstract class BaseShape<StyleProps extends BaseShapeStyleProps> extends
222
222
 
223
223
  private setVisibility() {
224
224
  const { visibility } = this.attributes;
225
- setVisibility(this, visibility);
225
+ setVisibility(this, visibility, true);
226
226
  }
227
227
 
228
228
  public destroy(): void {
@@ -1,6 +1,6 @@
1
1
  import { GraphEvent } from '../constants';
2
2
  import type { RuntimeContext } from '../runtime/types';
3
- import { Point } from '../types';
3
+ import type { Point } from '../types';
4
4
  import { createPluginContainer, insertBefore } from '../utils/dom';
5
5
  import { ViewportEvent } from '../utils/event';
6
6
  import { add, mod } from '../utils/vector';
@@ -9,6 +9,7 @@ export { History } from './history';
9
9
  export { Hull } from './hull';
10
10
  export { Legend } from './legend';
11
11
  export { Minimap } from './minimap';
12
+ export { Snapline } from './snapline';
12
13
  export { Timebar } from './timebar';
13
14
  export { Toolbar } from './toolbar';
14
15
  export { Tooltip } from './tooltip';
@@ -25,6 +26,7 @@ export type { HistoryOptions } from './history';
25
26
  export type { HullOptions } from './hull';
26
27
  export type { LegendOptions } from './legend';
27
28
  export type { MinimapOptions } from './minimap';
29
+ export type { SnaplineOptions } from './snapline';
28
30
  export type { TimebarOptions } from './timebar';
29
31
  export type { ToolbarOptions } from './toolbar';
30
32
  export type { TooltipOptions } from './tooltip';
@@ -0,0 +1,383 @@
1
+ import { AABB, BaseStyleProps, DisplayObject, Line, LineStyleProps } from '@antv/g';
2
+ import { isEqual } from '@antv/util';
3
+ import { NodeEvent } from '../../constants';
4
+ import type { RuntimeContext } from '../../runtime/types';
5
+ import type { ID, IDragEvent, Node } from '../../types';
6
+ import { isVisible } from '../../utils/element';
7
+ import { divide } from '../../utils/vector';
8
+ import type { BasePluginOptions } from '../base-plugin';
9
+ import { BasePlugin } from '../base-plugin';
10
+
11
+ export interface SnaplineOptions extends BasePluginOptions {
12
+ /**
13
+ * <zh/> 对齐精度,即移动节点时与目标位置的距离小于 tolerance 时触发显示对齐线
14
+ *
15
+ * <en/> The alignment accuracy, that is, when the distance between the moved node and the target position is less than tolerance, the alignment line is displayed
16
+ * @defaultValue 5
17
+ */
18
+ tolerance?: number;
19
+ /**
20
+ * <zh/> 对齐线头尾的延伸距离。取值范围:[0, Infinity]
21
+ *
22
+ * <en/> The extension distance of the snapline. The value range is [0, Infinity]
23
+ * @defaultValue 20
24
+ */
25
+ offset?: number;
26
+ /**
27
+ * <zh/> 是否启用自动吸附
28
+ *
29
+ * <en/> Whether to enable automatic adsorption
30
+ * @defaultValue true
31
+ */
32
+ autoSnap?: boolean;
33
+ /**
34
+ * <zh/> 指定元素上的哪个图形作为参照图形
35
+ *
36
+ * <en/> Specifies which shape on the element to use as the reference shape
37
+ * @defaultValue `'key'`
38
+ * @remarks
39
+ * <zh/>
40
+ * - 'key' 使用元素的主图形作为参照图形
41
+ * - 也可以传入一个函数,接收元素对象,返回一个图形
42
+ *
43
+ * <en/>
44
+ * - `'key'` uses the key shape of the element as the reference shape
45
+ * - You can also pass in a function that receives the element and returns a shape
46
+ */
47
+ shape?: string | ((node: Node) => DisplayObject);
48
+ /**
49
+ * <zh/> 垂直对齐线样式
50
+ *
51
+ * <en/> Vertical snapline style
52
+ * @defaultValue `{ stroke: '#1783FF' }`
53
+ */
54
+ verticalLineStyle?: BaseStyleProps;
55
+ /**
56
+ * <zh/> 水平对齐线样式
57
+ *
58
+ * <en/> Horizontal snapline style
59
+ * @defaultValue `{ stroke: '#1783FF' }`
60
+ */
61
+ horizontalLineStyle?: BaseStyleProps;
62
+ /**
63
+ * <zh/> 过滤器,用于过滤不需要作为参考的节点
64
+ *
65
+ * <en/> Filter, used to filter nodes that do not need to be used as references
66
+ * @defaultValue `() => true`
67
+ */
68
+ filter?: (node: Node) => boolean;
69
+ }
70
+
71
+ const defaultLineStyle: LineStyleProps = { x1: 0, y1: 0, x2: 0, y2: 0, visibility: 'hidden' };
72
+
73
+ type Metadata = {
74
+ verticalX: number | null;
75
+ verticalMinY: number | null;
76
+ verticalMaxY: number | null;
77
+ horizontalY: number | null;
78
+ horizontalMinX: number | null;
79
+ horizontalMaxX: number | null;
80
+ };
81
+
82
+ export class Snapline extends BasePlugin<SnaplineOptions> {
83
+ static defaultOptions: Partial<SnaplineOptions> = {
84
+ tolerance: 5,
85
+ offset: 20,
86
+ autoSnap: true,
87
+ shape: 'key',
88
+ verticalLineStyle: { stroke: '#1783FF' },
89
+ horizontalLineStyle: { stroke: '#1783FF' },
90
+ filter: () => true,
91
+ };
92
+
93
+ private horizontalLine!: Line;
94
+ private verticalLine!: Line;
95
+
96
+ constructor(context: RuntimeContext, options: SnaplineOptions) {
97
+ super(context, Object.assign({}, Snapline.defaultOptions, options));
98
+ this.bindEvents();
99
+ }
100
+
101
+ private initSnapline = () => {
102
+ const canvas = this.context.canvas.getLayer('transient');
103
+
104
+ if (!this.horizontalLine) {
105
+ this.horizontalLine = canvas.appendChild(
106
+ new Line({ style: { ...defaultLineStyle, ...this.options.horizontalLineStyle } }),
107
+ );
108
+ }
109
+
110
+ if (!this.verticalLine) {
111
+ this.verticalLine = canvas.appendChild(
112
+ new Line({ style: { ...defaultLineStyle, ...this.options.verticalLineStyle } }),
113
+ );
114
+ }
115
+ };
116
+
117
+ private getNodes(): Node[] {
118
+ const { filter } = this.options;
119
+ const allNodes = this.context.element?.getNodes() || [];
120
+
121
+ // 不考虑超出画布视口范围、不可见的节点
122
+ // Nodes that are out of the canvas viewport range, invisible are not considered
123
+ const nodes = allNodes.filter((node) => {
124
+ return isVisible(node) && this.context.viewport?.isInViewport(node.getRenderBounds());
125
+ });
126
+
127
+ if (!filter) return nodes;
128
+
129
+ return nodes.filter((node) => filter(node));
130
+ }
131
+
132
+ private hideSnapline() {
133
+ this.horizontalLine.style.visibility = 'hidden';
134
+ this.verticalLine.style.visibility = 'hidden';
135
+ }
136
+
137
+ private getLineWidth(direction: 'horizontal' | 'vertical') {
138
+ const { lineWidth } = this.options[`${direction}LineStyle`] as LineStyleProps;
139
+ return +(lineWidth || defaultLineStyle.lineWidth || 1) / this.context.graph.getZoom();
140
+ }
141
+
142
+ private updateSnapline(metadata: Metadata) {
143
+ const { verticalX, verticalMinY, verticalMaxY, horizontalY, horizontalMinX, horizontalMaxX } = metadata;
144
+ const [canvasWidth, canvasHeight] = this.context.canvas.getSize();
145
+ const { offset } = this.options;
146
+
147
+ if (horizontalY !== null) {
148
+ Object.assign(this.horizontalLine.style, {
149
+ x1: offset === Infinity ? 0 : horizontalMinX! - offset,
150
+ y1: horizontalY,
151
+ x2: offset === Infinity ? canvasWidth : horizontalMaxX! + offset,
152
+ y2: horizontalY,
153
+ visibility: 'visible',
154
+ lineWidth: this.getLineWidth('horizontal'),
155
+ });
156
+ } else {
157
+ this.horizontalLine.style.visibility = 'hidden';
158
+ }
159
+
160
+ if (verticalX !== null) {
161
+ Object.assign(this.verticalLine.style, {
162
+ x1: verticalX,
163
+ y1: offset === Infinity ? 0 : verticalMinY! - offset,
164
+ x2: verticalX,
165
+ y2: offset === Infinity ? canvasHeight : verticalMaxY! + offset,
166
+ visibility: 'visible',
167
+ lineWidth: this.getLineWidth('vertical'),
168
+ });
169
+ } else {
170
+ this.verticalLine.style.visibility = 'hidden';
171
+ }
172
+ }
173
+
174
+ private isHorizontalSticking = false;
175
+ private isVerticalSticking = false;
176
+ private enableStick = true;
177
+
178
+ private autoSnapToLine = async (nodeId: ID, bbox: AABB, metadata: Metadata) => {
179
+ const { verticalX, horizontalY } = metadata;
180
+ const { tolerance } = this.options;
181
+ const {
182
+ min: [nodeMinX, nodeMinY],
183
+ max: [nodeMaxX, nodeMaxY],
184
+ center: [nodeCenterX, nodeCenterY],
185
+ } = bbox;
186
+
187
+ let dx = 0;
188
+ let dy = 0;
189
+ if (verticalX !== null) {
190
+ if (distance(nodeMaxX, verticalX) < tolerance) dx = verticalX - nodeMaxX;
191
+ if (distance(nodeMinX, verticalX) < tolerance) dx = verticalX - nodeMinX;
192
+ if (distance(nodeCenterX, verticalX) < tolerance) dx = verticalX - nodeCenterX;
193
+
194
+ if (dx !== 0) this.isVerticalSticking = true;
195
+ }
196
+ if (horizontalY !== null) {
197
+ if (distance(nodeMaxY, horizontalY) < tolerance) dy = horizontalY - nodeMaxY;
198
+ if (distance(nodeMinY, horizontalY) < tolerance) dy = horizontalY - nodeMinY;
199
+ if (distance(nodeCenterY, horizontalY) < tolerance) dy = horizontalY - nodeCenterY;
200
+
201
+ if (dy !== 0) this.isHorizontalSticking = true;
202
+ }
203
+ if (dx !== 0 || dy !== 0) {
204
+ // Stick to the line
205
+ await this.context.graph.translateElementBy({ [nodeId]: [dx, dy] }, false);
206
+ }
207
+ };
208
+
209
+ /**
210
+ * Get the delta of the drag
211
+ * @param event - drag event object
212
+ * @returns delta
213
+ * @internal
214
+ */
215
+ protected getDelta(event: IDragEvent<Node>) {
216
+ const zoom = this.context.graph.getZoom();
217
+ return divide([event.dx, event.dy], zoom);
218
+ }
219
+
220
+ private enableSnap = (event: IDragEvent<Node>) => {
221
+ const { target } = event;
222
+
223
+ const threshold = 0.5;
224
+
225
+ if (this.isHorizontalSticking || this.isVerticalSticking) {
226
+ const [dx, dy] = this.getDelta(event);
227
+ if (
228
+ this.isHorizontalSticking &&
229
+ this.isVerticalSticking &&
230
+ Math.abs(dx) <= threshold &&
231
+ Math.abs(dy) <= threshold
232
+ ) {
233
+ this.context.graph.translateElementBy({ [target.id]: [-dx, -dy] }, false);
234
+ return false;
235
+ } else if (this.isHorizontalSticking && Math.abs(dy) <= threshold) {
236
+ this.context.graph.translateElementBy({ [target.id]: [0, -dy] }, false);
237
+ return false;
238
+ } else if (this.isVerticalSticking && Math.abs(dx) <= threshold) {
239
+ this.context.graph.translateElementBy({ [target.id]: [-dx, 0] }, false);
240
+ return false;
241
+ } else {
242
+ this.isHorizontalSticking = false;
243
+ this.isVerticalSticking = false;
244
+ this.enableStick = false;
245
+ setTimeout(() => {
246
+ this.enableStick = true;
247
+ }, 200);
248
+ }
249
+ }
250
+
251
+ return this.enableStick;
252
+ };
253
+
254
+ private calcSnaplineMetadata = (target: Node, nodeBBox: AABB): Metadata => {
255
+ const { tolerance, shape } = this.options;
256
+
257
+ const {
258
+ min: [nodeMinX, nodeMinY],
259
+ max: [nodeMaxX, nodeMaxY],
260
+ center: [nodeCenterX, nodeCenterY],
261
+ } = nodeBBox;
262
+
263
+ let verticalX: number | null = null;
264
+ let verticalMinY: number | null = null;
265
+ let verticalMaxY: number | null = null;
266
+ let horizontalY: number | null = null;
267
+ let horizontalMinX: number | null = null;
268
+ let horizontalMaxX: number | null = null;
269
+
270
+ this.getNodes().some((snapNode: Node) => {
271
+ if (isEqual(target.id, snapNode.id)) return false;
272
+
273
+ const snapBBox = getShape(snapNode, shape).getRenderBounds();
274
+ const {
275
+ min: [snapMinX, snapMinY],
276
+ max: [snapMaxX, snapMaxY],
277
+ center: [snapCenterX, snapCenterY],
278
+ } = snapBBox;
279
+
280
+ if (verticalX === null) {
281
+ if (distance(snapCenterX, nodeCenterX) < tolerance) {
282
+ verticalX = snapCenterX;
283
+ } else if (distance(snapMinX, nodeMinX) < tolerance) {
284
+ verticalX = snapMinX;
285
+ } else if (distance(snapMinX, nodeMaxX) < tolerance) {
286
+ verticalX = snapMinX;
287
+ } else if (distance(snapMaxX, nodeMaxX) < tolerance) {
288
+ verticalX = snapMaxX;
289
+ } else if (distance(snapMaxX, nodeMinX) < tolerance) {
290
+ verticalX = snapMaxX;
291
+ }
292
+
293
+ if (verticalX !== null) {
294
+ verticalMinY = Math.min(snapMinY, nodeMinY);
295
+ verticalMaxY = Math.max(snapMaxY, nodeMaxY);
296
+ }
297
+ }
298
+
299
+ if (horizontalY === null) {
300
+ if (distance(snapCenterY, nodeCenterY) < tolerance) {
301
+ horizontalY = snapCenterY;
302
+ } else if (distance(snapMinY, nodeMinY) < tolerance) {
303
+ horizontalY = snapMinY;
304
+ } else if (distance(snapMinY, nodeMaxY) < tolerance) {
305
+ horizontalY = snapMinY;
306
+ } else if (distance(snapMaxY, nodeMaxY) < tolerance) {
307
+ horizontalY = snapMaxY;
308
+ } else if (distance(snapMaxY, nodeMinY) < tolerance) {
309
+ horizontalY = snapMaxY;
310
+ }
311
+
312
+ if (horizontalY !== null) {
313
+ horizontalMinX = Math.min(snapMinX, nodeMinX);
314
+ horizontalMaxX = Math.max(snapMaxX, nodeMaxX);
315
+ }
316
+ }
317
+
318
+ return verticalX !== null && horizontalY !== null;
319
+ });
320
+ return { verticalX, verticalMinY, verticalMaxY, horizontalY, horizontalMinX, horizontalMaxX };
321
+ };
322
+
323
+ protected onDragStart = () => {
324
+ this.initSnapline();
325
+ };
326
+
327
+ protected onDrag = async (event: IDragEvent<Node>) => {
328
+ const { target } = event;
329
+
330
+ if (this.options.autoSnap) {
331
+ const enable = this.enableSnap(event);
332
+ if (!enable) return;
333
+ }
334
+
335
+ const nodeBBox = getShape(target, this.options.shape).getRenderBounds();
336
+ const metadata = this.calcSnaplineMetadata(target, nodeBBox);
337
+
338
+ this.hideSnapline();
339
+
340
+ if (metadata.verticalX !== null || metadata.horizontalY !== null) {
341
+ this.updateSnapline(metadata);
342
+ }
343
+
344
+ if (this.options.autoSnap) {
345
+ await this.autoSnapToLine(target.id, nodeBBox, metadata);
346
+ }
347
+ };
348
+
349
+ protected onDragEnd = () => {
350
+ this.hideSnapline();
351
+ };
352
+
353
+ private async bindEvents() {
354
+ const { graph } = this.context;
355
+ graph.on(NodeEvent.DRAG_START, this.onDragStart);
356
+ graph.on(NodeEvent.DRAG, this.onDrag);
357
+ graph.on(NodeEvent.DRAG_END, this.onDragEnd);
358
+ }
359
+
360
+ private unbindEvents() {
361
+ const { graph } = this.context;
362
+ graph.off(NodeEvent.DRAG_START, this.onDragStart);
363
+ graph.off(NodeEvent.DRAG, this.onDrag);
364
+ graph.off(NodeEvent.DRAG_END, this.onDragEnd);
365
+ }
366
+
367
+ private destroyElements() {
368
+ this.horizontalLine.destroy();
369
+ this.verticalLine.destroy();
370
+ }
371
+
372
+ public destroy() {
373
+ this.destroyElements();
374
+ this.unbindEvents();
375
+ super.destroy();
376
+ }
377
+ }
378
+
379
+ const distance = (a: number, b: number) => Math.abs(a - b);
380
+
381
+ const getShape = (node: Node, shapeFilter: string | ((node: Node) => DisplayObject)) => {
382
+ return typeof shapeFilter === 'function' ? shapeFilter(node) : node.getShape(shapeFilter);
383
+ };
@@ -65,6 +65,7 @@ import {
65
65
  Hull,
66
66
  Legend,
67
67
  Minimap,
68
+ Snapline,
68
69
  Timebar,
69
70
  Toolbar,
70
71
  Tooltip,
@@ -175,11 +176,12 @@ const BUILT_IN_EXTENSIONS: ExtensionRegistry = {
175
176
  history: History,
176
177
  hull: Hull,
177
178
  legend: Legend,
179
+ minimap: Minimap,
180
+ snapline: Snapline,
178
181
  timebar: Timebar,
179
182
  toolbar: Toolbar,
180
183
  tooltip: Tooltip,
181
184
  watermark: Watermark,
182
- minimap: Minimap,
183
185
  },
184
186
  transform: {
185
187
  'update-related-edges': UpdateRelatedEdge,
@@ -22,7 +22,7 @@ import type {
22
22
  State,
23
23
  StyleIterationContext,
24
24
  } from '../types';
25
- import { cacheStyle, getCachedStyle, hasCachedStyle, setCacheStyle } from '../utils/cache';
25
+ import { cacheStyle, hasCachedStyle } from '../utils/cache';
26
26
  import { reduceDataChanges } from '../utils/change';
27
27
  import { isCollapsed } from '../utils/collapsibility';
28
28
  import { markToBeDestroyed, updateStyle } from '../utils/element';
@@ -34,6 +34,7 @@ import { positionOf } from '../utils/position';
34
34
  import { print } from '../utils/print';
35
35
  import { computeElementCallbackStyle } from '../utils/style';
36
36
  import { themeOf } from '../utils/theme';
37
+ import { setVisibility } from '../utils/visibility';
37
38
  import type { RuntimeContext } from './types';
38
39
 
39
40
  export class ElementController {
@@ -451,6 +452,10 @@ export class ElementController {
451
452
 
452
453
  const exactStage = stage !== 'visibility' ? stage : style.visibility === 'hidden' ? 'hide' : 'show';
453
454
 
455
+ // 避免立即将 visibility 设置为 hidden,导致元素不可见,而是在 after 阶段再设置
456
+ // Avoid setting visibility to hidden immediately, causing the element to be invisible, but set it in the after phase
457
+ if (exactStage === 'hide') delete style['visibility'];
458
+
454
459
  this.context.animation?.add(
455
460
  {
456
461
  element,
@@ -470,14 +475,14 @@ export class ElementController {
470
475
  // 缓存原始透明度 / Cache original opacity
471
476
  // 会在 animation controller 中访问该缓存值 / The cached value will be accessed in the animation controller
472
477
  if (!hasCachedStyle(element, 'opacity')) cacheStyle(element, 'opacity');
473
- setCacheStyle(element, 'visibility', exactStage === 'show' ? 'visible' : 'hidden');
474
- if (exactStage === 'show') updateStyle(element, { visibility: 'visible' });
478
+ this.visibilityCache.set(element, exactStage === 'show' ? 'visible' : 'hidden');
479
+ if (exactStage === 'show') setVisibility(element, 'visible');
475
480
  }
476
481
  },
477
482
  after: () => {
478
483
  const element = this.elementMap[id];
479
484
  if (stage === 'collapse') updateStyle(element, style);
480
- if (exactStage === 'hide') updateStyle(element, { visibility: getCachedStyle(element, 'visibility') });
485
+ if (exactStage === 'hide') setVisibility(element, this.visibilityCache.get(element));
481
486
  this.emit(new ElementLifeCycleEvent(GraphEvent.AFTER_ELEMENT_UPDATE, elementType, datum), context);
482
487
  element.onUpdate?.();
483
488
  },
@@ -498,6 +503,8 @@ export class ElementController {
498
503
  });
499
504
  }
500
505
 
506
+ private visibilityCache = new WeakMap<Element, BaseStyleProps['visibility']>();
507
+
501
508
  /**
502
509
  * <zh/> 标记销毁元素
503
510
  *