@antv/g6 5.1.0-beta.1 → 5.1.1

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 (91) hide show
  1. package/dist/g6.min.js +8 -10
  2. package/dist/lib/plugins/contextmenu/index.d.ts +1 -0
  3. package/dist/lib/plugins/contextmenu/util.d.ts +1 -1
  4. package/dist/lib/transforms/process-parallel-edges.d.ts +18 -0
  5. package/dist/lib/types/edge.d.ts +11 -0
  6. package/dist/lib/utils/edge.d.ts +16 -1
  7. package/dist/lib/utils/shortcut.d.ts +7 -0
  8. package/dist/lib/version.d.ts +1 -1
  9. package/esm/behaviors/create-edge.js +3 -2
  10. package/esm/behaviors/create-edge.js.map +1 -1
  11. package/esm/elements/combos/base-combo.js.map +1 -1
  12. package/esm/elements/edges/base-edge.js +10 -4
  13. package/esm/elements/edges/base-edge.js.map +1 -1
  14. package/esm/elements/nodes/base-node.js.map +1 -1
  15. package/esm/elements/nodes/image.js +2 -2
  16. package/esm/elements/nodes/image.js.map +1 -1
  17. package/esm/plugins/contextmenu/index.d.ts +1 -0
  18. package/esm/plugins/contextmenu/index.js +20 -3
  19. package/esm/plugins/contextmenu/index.js.map +1 -1
  20. package/esm/plugins/contextmenu/util.d.ts +1 -1
  21. package/esm/plugins/contextmenu/util.js +16 -1
  22. package/esm/plugins/contextmenu/util.js.map +1 -1
  23. package/esm/plugins/tooltip.js.map +1 -1
  24. package/esm/runtime/canvas.js.map +1 -1
  25. package/esm/runtime/element.js +3 -0
  26. package/esm/runtime/element.js.map +1 -1
  27. package/esm/transforms/process-parallel-edges.d.ts +18 -0
  28. package/esm/transforms/process-parallel-edges.js +29 -5
  29. package/esm/transforms/process-parallel-edges.js.map +1 -1
  30. package/esm/types/edge.d.ts +11 -0
  31. package/esm/utils/edge.d.ts +16 -1
  32. package/esm/utils/edge.js +110 -4
  33. package/esm/utils/edge.js.map +1 -1
  34. package/esm/utils/shortcut.d.ts +7 -0
  35. package/esm/utils/shortcut.js +29 -0
  36. package/esm/utils/shortcut.js.map +1 -1
  37. package/esm/utils/vector.js +36 -3
  38. package/esm/utils/vector.js.map +1 -1
  39. package/esm/version.d.ts +1 -1
  40. package/esm/version.js +1 -1
  41. package/esm/version.js.map +1 -1
  42. package/lib/behaviors/create-edge.js +3 -2
  43. package/lib/behaviors/create-edge.js.map +1 -1
  44. package/lib/elements/combos/base-combo.js.map +1 -1
  45. package/lib/elements/edges/base-edge.js +9 -3
  46. package/lib/elements/edges/base-edge.js.map +1 -1
  47. package/lib/elements/nodes/base-node.js.map +1 -1
  48. package/lib/elements/nodes/image.js +1 -1
  49. package/lib/elements/nodes/image.js.map +1 -1
  50. package/lib/plugins/contextmenu/index.d.ts +1 -0
  51. package/lib/plugins/contextmenu/index.js +20 -3
  52. package/lib/plugins/contextmenu/index.js.map +1 -1
  53. package/lib/plugins/contextmenu/util.d.ts +1 -1
  54. package/lib/plugins/contextmenu/util.js +16 -1
  55. package/lib/plugins/contextmenu/util.js.map +1 -1
  56. package/lib/plugins/tooltip.js.map +1 -1
  57. package/lib/runtime/canvas.js.map +1 -1
  58. package/lib/runtime/element.js +3 -0
  59. package/lib/runtime/element.js.map +1 -1
  60. package/lib/transforms/process-parallel-edges.d.ts +18 -0
  61. package/lib/transforms/process-parallel-edges.js +29 -5
  62. package/lib/transforms/process-parallel-edges.js.map +1 -1
  63. package/lib/types/edge.d.ts +11 -0
  64. package/lib/utils/edge.d.ts +16 -1
  65. package/lib/utils/edge.js +111 -4
  66. package/lib/utils/edge.js.map +1 -1
  67. package/lib/utils/shortcut.d.ts +7 -0
  68. package/lib/utils/shortcut.js +29 -0
  69. package/lib/utils/shortcut.js.map +1 -1
  70. package/lib/utils/vector.js +35 -2
  71. package/lib/utils/vector.js.map +1 -1
  72. package/lib/version.d.ts +1 -1
  73. package/lib/version.js +1 -1
  74. package/lib/version.js.map +1 -1
  75. package/package.json +2 -2
  76. package/src/behaviors/create-edge.ts +3 -2
  77. package/src/elements/combos/base-combo.ts +1 -2
  78. package/src/elements/edges/base-edge.ts +24 -4
  79. package/src/elements/nodes/base-node.ts +1 -2
  80. package/src/elements/nodes/image.ts +2 -2
  81. package/src/plugins/contextmenu/index.ts +26 -3
  82. package/src/plugins/contextmenu/util.ts +16 -1
  83. package/src/plugins/tooltip.ts +1 -2
  84. package/src/runtime/canvas.ts +2 -4
  85. package/src/runtime/element.ts +4 -0
  86. package/src/transforms/process-parallel-edges.ts +47 -3
  87. package/src/types/edge.ts +14 -1
  88. package/src/utils/edge.ts +131 -3
  89. package/src/utils/shortcut.ts +30 -0
  90. package/src/utils/vector.ts +38 -5
  91. package/src/version.ts +1 -1
@@ -14,6 +14,9 @@ import { isStyleEqual, reassignTo } from './utils';
14
14
 
15
15
  const CUBIC_EDGE_TYPE = 'quadratic';
16
16
 
17
+ const INITIAL_NESTED_LOOP_DIST = 35;
18
+ const INITIAL_SPREAD_LOOP_DIST = 50;
19
+
17
20
  const CUBIC_LOOP_PLACEMENTS: LoopPlacement[] = [
18
21
  'top',
19
22
  'top-right',
@@ -55,6 +58,24 @@ export interface ProcessParallelEdgesOptions extends BaseTransformOptions {
55
58
  * <en/> The style of the merged edge, only valid for merging mode
56
59
  */
57
60
  style?: PathStyleProps | ((prev: EdgeData[]) => PathStyleProps);
61
+ /**
62
+ * <zh/> 自环边的处理模式
63
+ * - `'spread'`: 将多个自环边分散到节点的不同位置(上、右、下、左等8个方向)
64
+ * - `'nested'`: 将同一位置的多个自环边按不同距离嵌套排列
65
+ *
66
+ * <en/> The processing mode for self-loop edges
67
+ * - `'spread'`: Distribute multiple self-loop edges to different positions around the node (top, right, bottom, left, etc. - 8 directions)
68
+ * - `'nested'`: Arrange multiple self-loop edges at the same position with different distances (nested/concentric loops)
69
+ * @defaultValue 'spread'
70
+ */
71
+ loopMode?: 'spread' | 'nested';
72
+ /**
73
+ * <zh/> 嵌套自环边之间的距离,仅在 loopMode 为 'nested' 时有效
74
+ *
75
+ * <en/> The distance between nested self-loop edges, only valid when loopMode is 'nested'
76
+ * @defaultValue 15
77
+ */
78
+ loopDistance?: number;
58
79
  }
59
80
 
60
81
  /**
@@ -70,6 +91,8 @@ export class ProcessParallelEdges extends BaseTransform<ProcessParallelEdgesOpti
70
91
  static defaultOptions: Partial<ProcessParallelEdgesOptions> = {
71
92
  mode: 'bundle',
72
93
  distance: 15, // only valid for bundling mode
94
+ loopMode: 'spread',
95
+ loopDistance: 15,
73
96
  };
74
97
 
75
98
  private cacheMergeStyle: Map<ID, PathStyleProps> = new Map();
@@ -168,15 +191,36 @@ export class ProcessParallelEdges extends BaseTransform<ProcessParallelEdgesOpti
168
191
 
169
192
  protected applyBundlingStyle = (input: DrawData, edges: Map<ID, EdgeData>, distance: number) => {
170
193
  const { edgeMap, reverses } = groupByEndpoints(edges);
194
+ const loopMode = this.options.loopMode ?? 'spread';
195
+ const loopDistance = this.options.loopDistance ?? distance;
196
+
197
+ // 嵌套模式下的位置计数:key = `${nodeId}-${placement}` | Placement counts for nested mode
198
+ const placementCounts = new Map<string, number>();
171
199
 
172
200
  edgeMap.forEach((arcEdges) => {
173
201
  arcEdges.forEach((edge, i, edgeArr) => {
174
202
  const length = edgeArr.length;
175
203
  const style: EdgeStyle = edge.style || {};
176
204
  if (edge.source === edge.target) {
177
- const len = CUBIC_LOOP_PLACEMENTS.length;
178
- style.loopPlacement = CUBIC_LOOP_PLACEMENTS[i % len];
179
- style.loopDist = Math.floor(i / len) * distance + 50;
205
+ if (loopMode === 'nested') {
206
+ // 嵌套模式:按位置分组,在每组内自动递增距离 | Nested mode: group by placement, auto-increment distance within each group
207
+ const placement = style.loopPlacement || 'top';
208
+ const key = `${edge.source}-${placement}`;
209
+
210
+ style.loopPlacement = placement;
211
+
212
+ // 仅在用户未手动设置 loopDist 时自动分配 | Only auto-assign loopDist when not already set by user
213
+ if (style.loopDist === undefined) {
214
+ const count = placementCounts.get(key) ?? 0;
215
+ style.loopDist = INITIAL_NESTED_LOOP_DIST + count * loopDistance;
216
+ placementCounts.set(key, count + 1);
217
+ }
218
+ } else {
219
+ // 分散模式(默认):将自环边分散到 8 个位置 | Spread mode (default): distribute loops across 8 positions
220
+ const len = CUBIC_LOOP_PLACEMENTS.length;
221
+ style.loopPlacement = CUBIC_LOOP_PLACEMENTS[i % len];
222
+ style.loopDist = Math.floor(i / len) * distance + INITIAL_SPREAD_LOOP_DIST;
223
+ }
180
224
  } else if (length === 1) {
181
225
  style.curveOffset = 0;
182
226
  } else {
package/src/types/edge.ts CHANGED
@@ -102,7 +102,9 @@ export interface EdgeBadgeStyleProps extends BadgeStyleProps {
102
102
  * <en/> Edge arrow style properties
103
103
  */
104
104
  export interface EdgeArrowStyleProps
105
- extends PathStyleProps, Omit<ImageStyleProps, 'width' | 'height'>, Record<string, unknown> {
105
+ extends PathStyleProps,
106
+ Omit<ImageStyleProps, 'width' | 'height'>,
107
+ Record<string, unknown> {
106
108
  /**
107
109
  * <zh/> 箭头大小
108
110
  *
@@ -135,6 +137,17 @@ export type LoopPlacement = CardinalPlacement | CornerPlacement;
135
137
  * <en/> Loop style properties
136
138
  */
137
139
  export interface LoopStyleProps {
140
+ /**
141
+ * <zh/> 自环边的绘制类型
142
+ * - `'default'`: 使用三次贝塞尔曲线(默认,与 G6 原始行为一致)
143
+ * - `'arc'`: 使用 SVG 圆弧命令绘制近似圆形的自环
144
+ *
145
+ * <en/> Drawing type for self-loop edges
146
+ * - `'default'`: Use cubic Bezier curve (default, consistent with original G6 behavior)
147
+ * - `'arc'`: Use SVG arc command to draw a near-circular self-loop
148
+ * @defaultValue 'default'
149
+ */
150
+ type?: 'default' | 'arc';
138
151
  /**
139
152
  * <zh/> 边的位置
140
153
  *
package/src/utils/edge.ts CHANGED
@@ -23,6 +23,26 @@ import { isCollinear, isHorizontal, moveTo, parsePoint } from './point';
23
23
  import { freeJoin } from './router/orth';
24
24
  import { add, distance, manhattanDistance, multiply, normalize, perpendicular, subtract } from './vector';
25
25
 
26
+ /**
27
+ * <zh/> 自环边弧顶处的切线角度,每个方向的切线与凸起方向垂直
28
+ *
29
+ * <en/> Tangent angles at the apex of loop edges, perpendicular to bulge direction for each placement
30
+ */
31
+ const LOOP_TANGENT_ANGLES: Record<string, number> = {
32
+ top: 0,
33
+ bottom: 0,
34
+ left: Math.PI / 2,
35
+ right: Math.PI / 2,
36
+ 'top-right': Math.PI / 4,
37
+ 'right-top': Math.PI / 4,
38
+ 'bottom-left': Math.PI / 4,
39
+ 'left-bottom': Math.PI / 4,
40
+ 'right-bottom': -Math.PI / 4,
41
+ 'bottom-right': -Math.PI / 4,
42
+ 'left-top': -Math.PI / 4,
43
+ 'top-left': -Math.PI / 4,
44
+ };
45
+
26
46
  /**
27
47
  * <zh/> 获取标签的位置样式
28
48
  *
@@ -32,6 +52,8 @@ import { add, distance, manhattanDistance, multiply, normalize, perpendicular, s
32
52
  * @param autoRotate - <zh/> 是否自动旋转 | <en/> Whether to auto-rotate
33
53
  * @param offsetX - <zh/> 标签相对于边的水平偏移量 | <en/> Horizontal offset of the label relative to the edge
34
54
  * @param offsetY - <zh/> 标签相对于边的垂直偏移量 | <en/> Vertical offset of the label relative to the edge
55
+ * @param isLoop - <zh/> 是否是自环边 | <en/> Whether it is a loop edge
56
+ * @param loopPlacement - <zh/> 自环边的位置 | <en/> The loop placement
35
57
  * @returns <zh/> 标签的位置样式 | <en/> Returns the style of the label's position
36
58
  */
37
59
  export function getLabelPositionStyle(
@@ -40,6 +62,8 @@ export function getLabelPositionStyle(
40
62
  autoRotate: boolean,
41
63
  offsetX: number,
42
64
  offsetY: number,
65
+ isLoop?: boolean,
66
+ loopPlacement?: LoopPlacement,
43
67
  ): Partial<EdgeLabelStyleProps> {
44
68
  const START_RATIO = 0;
45
69
  const MIDDLE_RATIO = 0.5;
@@ -49,6 +73,29 @@ export function getLabelPositionStyle(
49
73
  if (placement === 'start') ratio = START_RATIO;
50
74
  if (placement === 'end') ratio = END_RATIO;
51
75
 
76
+ // 自环边:label 放在弧顶点(ratio=0.5),角度由 loopPlacement 精确计算
77
+ // Loop edge: place label at apex (ratio=0.5), compute exact angle from loopPlacement
78
+ // 自环边:label 居中在弧顶(ratio=0.5),旋转角度由 loopPlacement 决定
79
+ // Loop edge: center label at apex (ratio=0.5), rotation angle determined by loopPlacement
80
+ if (isLoop && loopPlacement) {
81
+ ratio = 0.5;
82
+ // 自环边默认居中在弧顶,清除默认偏移量
83
+ // Loop edges default to centering at the apex, clear default offsets
84
+ offsetX = 0;
85
+ offsetY = 0;
86
+
87
+ let angle = LOOP_TANGENT_ANGLES[loopPlacement] ?? 0;
88
+ // 确保文本从左到右可读 | Ensure text reads left-to-right
89
+ if (Math.cos(angle) < -1e-6) angle += Math.PI;
90
+
91
+ const shouldRotate = autoRotate && angle !== 0;
92
+ const [x, y] = getXYByPlacement(key, ratio, offsetX, offsetY, shouldRotate ? angle : undefined);
93
+ const transform: TransformArray = [['translate', x, y]];
94
+ if (shouldRotate) transform.push(['rotate', (angle / Math.PI) * 180]);
95
+
96
+ return { textAlign: 'center' as const, transform };
97
+ }
98
+
52
99
  const point = parsePoint(key.getPoint(ratio));
53
100
  const pointOffset = parsePoint(key.getPoint(ratio + 0.01));
54
101
 
@@ -383,19 +430,100 @@ export function getCubicLoopPath(
383
430
  const sourcePort = node.getPorts()[(sourcePortKey || targetPortKey)!];
384
431
  const targetPort = node.getPorts()[(targetPortKey || sourcePortKey)!];
385
432
 
386
- // 1. 获取起点和终点 | Get the start and end points
387
433
  let [sourcePoint, targetPoint] = getLoopEndpoints(node, placement, clockwise, sourcePort, targetPort);
388
434
 
389
- // 2. 获取控制点 | Get the control points
390
435
  const controlPoints = getCubicLoopControlPoints(node, sourcePoint, targetPoint, dist);
391
436
 
392
- // 3. 如果定义了连接桩,调整端点以与连接桩边界相交 | If the port is defined, adjust the endpoint to intersect with the port boundary
393
437
  if (sourcePort) sourcePoint = getPortConnectionPoint(sourcePort, controlPoints[0]);
394
438
  if (targetPort) targetPoint = getPortConnectionPoint(targetPort, controlPoints.at(-1) as Point);
395
439
 
396
440
  return getCubicPath(sourcePoint, targetPoint, controlPoints);
397
441
  }
398
442
 
443
+ /**
444
+ * <zh/> 获取圆弧自环边的绘制路径(使用 SVG Arc 命令绘制近似圆形)
445
+ *
446
+ * <en/> Get the arc loop edge path (using SVG Arc command for near-circular loops)
447
+ * @param node - <zh/> 节点实例 | <en/> Node instance
448
+ * @param placement - <zh/> 环形边相对于节点位置 | <en/> Loop position relative to the node
449
+ * @param clockwise - <zh/> 是否顺时针 | <en/> Whether to draw the loop clockwise
450
+ * @param dist - <zh/> 从节点 keyShape 边缘到自环顶部的距离 | <en/> The distance from the edge of the node keyShape to the top of the self-loop
451
+ * @param sourcePortKey - <zh/> 起点连接桩 key | <en/> Source port key
452
+ * @param targetPortKey - <zh/> 终点连接桩 key | <en/> Target port key
453
+ * @returns <zh/> 返回绘制圆弧环形边的路径 | <en/> Returns the arc loop edge path
454
+ */
455
+ export function getArcLoopPath(
456
+ node: Node,
457
+ placement: LoopPlacement,
458
+ clockwise: boolean,
459
+ dist: number,
460
+ sourcePortKey?: string,
461
+ targetPortKey?: string,
462
+ ): PathArray {
463
+ const sourcePort = node.getPorts()[(sourcePortKey || targetPortKey)!];
464
+ const targetPort = node.getPorts()[(targetPortKey || sourcePortKey)!];
465
+
466
+ let [sourcePoint, targetPoint] = getLoopEndpoints(node, placement, clockwise, sourcePort, targetPort);
467
+
468
+ // 退化情况:起点和终点相同(同一端口)| Degenerate case: same start and end point (same port)
469
+ if (isEqual(sourcePoint, targetPoint)) {
470
+ const controlPoints = getCubicLoopControlPoints(node, sourcePoint, targetPoint, dist);
471
+ if (sourcePort) sourcePoint = getPortConnectionPoint(sourcePort, controlPoints[0]);
472
+ if (targetPort) targetPoint = getPortConnectionPoint(targetPort, controlPoints.at(-1) as Point);
473
+ return getCubicPath(sourcePoint, targetPoint, controlPoints);
474
+ }
475
+
476
+ const center = node.getCenter();
477
+
478
+ // 弦中点和凸起方向 | Chord midpoint and bulge direction
479
+ const chordMid: Point = [(sourcePoint[0] + targetPoint[0]) / 2, (sourcePoint[1] + targetPoint[1]) / 2, 0];
480
+ const bulgeDirLen = distance(center, chordMid);
481
+ const bulgeDir: Point = bulgeDirLen > 1e-6 ? (normalize(subtract(chordMid, center)) as Point) : [0, -1, 0];
482
+
483
+ // 圆弧参数:R = (c² + 4h²) / (8h) | Circular arc parameters
484
+ const chordLen = distance(sourcePoint, targetPoint);
485
+ const h = Math.max(Math.abs(dist), 0.01);
486
+ const R = (chordLen * chordLen + 4 * h * h) / (8 * h);
487
+
488
+ // 弧顶点 | Apex point
489
+ const apex: Point = [chordMid[0] + bulgeDir[0] * h, chordMid[1] + bulgeDir[1] * h, 0];
490
+
491
+ // 圆弧中心(弧顶点沿凸起方向内缩 R)| Arc center (apex retreated by R along bulge direction)
492
+ const arcCenter: Point = [chordMid[0] + bulgeDir[0] * (h - R), chordMid[1] + bulgeDir[1] * (h - R), 0];
493
+
494
+ // 用 atan2 计算各点相对于圆弧中心的角度 | Compute angles from arc center
495
+ const twoPI = 2 * Math.PI;
496
+ const θs = Math.atan2(sourcePoint[1] - arcCenter[1], sourcePoint[0] - arcCenter[0]);
497
+ const θt = Math.atan2(targetPoint[1] - arcCenter[1], targetPoint[0] - arcCenter[0]);
498
+ const θa = Math.atan2(apex[1] - arcCenter[1], apex[0] - arcCenter[0]);
499
+
500
+ // 判断顺时针方向是否经过弧顶点 | Check if CW direction passes through apex
501
+ const cwAngleToTarget = (((θt - θs) % twoPI) + twoPI) % twoPI;
502
+ const cwAngleToApex = (((θa - θs) % twoPI) + twoPI) % twoPI;
503
+ const cwPassesThroughApex = cwAngleToApex <= cwAngleToTarget + 1e-6;
504
+
505
+ const sweepFlag = cwPassesThroughApex ? 1 : 0;
506
+ const arcAngle = cwPassesThroughApex ? cwAngleToTarget : twoPI - cwAngleToTarget;
507
+ const largeArcFlag = arcAngle > Math.PI ? 1 : 0;
508
+
509
+ // 端口调整:用切线方向作为虚拟控制点 | Port adjustment using tangent direction
510
+ if (sourcePort) {
511
+ const srcR: Point = [sourcePoint[0] - arcCenter[0], sourcePoint[1] - arcCenter[1], 0];
512
+ const tangent: Point = sweepFlag === 1 ? [-srcR[1], srcR[0], 0] : [srcR[1], -srcR[0], 0];
513
+ sourcePoint = getPortConnectionPoint(sourcePort, add(sourcePoint, tangent));
514
+ }
515
+ if (targetPort) {
516
+ const tgtR: Point = [targetPoint[0] - arcCenter[0], targetPoint[1] - arcCenter[1], 0];
517
+ const tangent: Point = sweepFlag === 1 ? [tgtR[1], -tgtR[0], 0] : [-tgtR[1], tgtR[0], 0];
518
+ targetPoint = getPortConnectionPoint(targetPort, add(targetPoint, tangent));
519
+ }
520
+
521
+ return [
522
+ ['M', sourcePoint[0], sourcePoint[1]],
523
+ ['A', R, R, 0, largeArcFlag, sweepFlag, targetPoint[0], targetPoint[1]],
524
+ ] as unknown as PathArray;
525
+ }
526
+
399
527
  /**
400
528
  * <zh/> 获取环形边的控制点
401
529
  *
@@ -11,6 +11,11 @@ export type ShortcutKey = string[];
11
11
 
12
12
  type Handler = (event: any) => void;
13
13
 
14
+ const MODIFIER_KEYS = new Set(['Control', 'Alt', 'Meta', 'Shift']);
15
+ function isModifierKey(key: string) {
16
+ return MODIFIER_KEYS.has(key);
17
+ }
18
+
14
19
  const lowerCaseKeys = (keys: ShortcutKey) => keys.map((key) => (isString(key) ? key.toLocaleLowerCase() : key));
15
20
 
16
21
  export class Shortcut {
@@ -48,6 +53,11 @@ export class Shortcut {
48
53
  this.map.clear();
49
54
  }
50
55
 
56
+ /**
57
+ * Check whether the given keys are being held down currently.
58
+ * @param key - array of keys to check
59
+ * @returns true if the given keys are being held down, false otherwise.
60
+ */
51
61
  public match(key: ShortcutKey) {
52
62
  // 排序
53
63
  const recordKeyList = lowerCaseKeys(Array.from(this.recordKey)).sort();
@@ -58,6 +68,14 @@ export class Shortcut {
58
68
  private bindEvents() {
59
69
  const { emitter } = this;
60
70
 
71
+ // These window listeners are added purely to listen to modifier keys at the window level,
72
+ // and the key presses are only recorded into this.recordKey for the purpose of matching
73
+ // in the match() function. This allows just these keypresses alone to be registered
74
+ // before the canvas is focused, which prevents a problem where when shortcuts involving
75
+ // a modifier and clicking on the canvas are bound, match() will return false for that
76
+ // modifier key because the canvas has not been clicked (and therefore focused) yet.
77
+ window.addEventListener(CommonEvent.KEY_DOWN, this.onKeyDownWindow);
78
+ window.addEventListener(CommonEvent.KEY_UP, this.onKeyUpWindow);
61
79
  emitter.on(CommonEvent.KEY_DOWN, this.onKeyDown);
62
80
  emitter.on(CommonEvent.KEY_UP, this.onKeyUp);
63
81
  emitter.on(CommonEvent.WHEEL, this.onWheel);
@@ -79,6 +97,16 @@ export class Shortcut {
79
97
  this.recordKey.delete(event.key);
80
98
  };
81
99
 
100
+ private onKeyDownWindow = (event: KeyboardEvent) => {
101
+ if (!isModifierKey(event.key)) return;
102
+ this.recordKey.add(event.key);
103
+ };
104
+
105
+ private onKeyUpWindow = (event: KeyboardEvent) => {
106
+ if (!isModifierKey(event.key)) return;
107
+ this.recordKey.delete(event.key);
108
+ };
109
+
82
110
  private trigger(event: KeyboardEvent) {
83
111
  this.map.forEach((handler, key) => {
84
112
  if (this.match(key)) handler(event);
@@ -127,6 +155,8 @@ export class Shortcut {
127
155
  this.unbindAll();
128
156
  this.emitter.off(CommonEvent.KEY_DOWN, this.onKeyDown);
129
157
  this.emitter.off(CommonEvent.KEY_UP, this.onKeyUp);
158
+ window.removeEventListener(CommonEvent.KEY_DOWN, this.onKeyDownWindow);
159
+ window.removeEventListener(CommonEvent.KEY_UP, this.onKeyUpWindow);
130
160
  this.emitter.off(CommonEvent.WHEEL, this.onWheel);
131
161
  this.emitter.off(CommonEvent.DRAG, this.onDrag);
132
162
  this.pinchHandler?.off('pinchmove', this.boundHandlePinch);
@@ -1,8 +1,28 @@
1
1
  import type { Vector2, Vector3 } from '../types';
2
- import { isVector2 } from './is';
2
+ import { isVector2, isVector3 } from './is';
3
+ import { format } from './print';
3
4
 
4
5
  const VECTOR_ZERO: Vector3 = [0, 0, 0];
5
6
 
7
+ /**
8
+ * <zh/> 填充两个向量至相同维度
9
+ *
10
+ * <en/> Pads two vectors to the same dimension
11
+ * @param a - <zh/> 第一个向量 | <en/> The first vector
12
+ * @param b - <zh/> 第二个向量 | <en/> The second vector
13
+ * @returns <zh/> 两个向量填充后的结果 | <en/> The result of padded vectors
14
+ */
15
+ function padVectors(a: Vector2 | Vector3, b: Vector2 | Vector3): [Vector2 | Vector3, Vector2 | Vector3] {
16
+ if (a.length == b.length) {
17
+ return [a, b];
18
+ } else {
19
+ if ((isVector3(a) && a[2] !== 0) || (isVector3(b) && b[2] !== 0)) {
20
+ throw new Error(format('Vectors could not operate due to different dimensions.'));
21
+ }
22
+ return [toVector2(a), toVector2(b)];
23
+ }
24
+ }
25
+
6
26
  /**
7
27
  * <zh/> 两个向量求和
8
28
  *
@@ -12,6 +32,7 @@ const VECTOR_ZERO: Vector3 = [0, 0, 0];
12
32
  * @returns <zh/> 两个向量的和 | <en/> The sum of the two vectors
13
33
  */
14
34
  export function add(a: Vector2 | Vector3, b: Vector2 | Vector3): Vector2 | Vector3 {
35
+ [a, b] = padVectors(a, b);
15
36
  return a.map((v, i) => v + b[i]) as Vector2 | Vector3;
16
37
  }
17
38
 
@@ -24,6 +45,7 @@ export function add(a: Vector2 | Vector3, b: Vector2 | Vector3): Vector2 | Vecto
24
45
  * @returns <zh/> 两个向量的差 | <en/> The difference of the two vectors
25
46
  */
26
47
  export function subtract(a: Vector2 | Vector3, b: Vector2 | Vector3): Vector2 | Vector3 {
48
+ [a, b] = padVectors(a, b);
27
49
  return a.map((v, i) => v - b[i]) as Vector2 | Vector3;
28
50
  }
29
51
 
@@ -36,7 +58,8 @@ export function subtract(a: Vector2 | Vector3, b: Vector2 | Vector3): Vector2 |
36
58
  * @returns <zh/> 两个向量的积或者向量和标量的积 | <en/> The product of the two vectors or the product of the vector and scalar
37
59
  */
38
60
  export function multiply(a: Vector2 | Vector3, b: number | Vector2 | Vector3): Vector2 | Vector3 {
39
- if (typeof b === 'number') return a.map((v) => v * b) as Vector2 | Vector3;
61
+ if (typeof b === 'number') return a.map((v) => v * (b as number)) as Vector2 | Vector3;
62
+ [a, b] = padVectors(a, b);
40
63
  return a.map((v, i) => v * b[i]) as Vector2 | Vector3;
41
64
  }
42
65
 
@@ -49,8 +72,14 @@ export function multiply(a: Vector2 | Vector3, b: number | Vector2 | Vector3): V
49
72
  * @returns <zh/> 两个向量的商或者向量和标量的商 | <en/> The quotient of the two vectors or the quotient of the vector and scalar
50
73
  */
51
74
  export function divide(a: Vector2 | Vector3, b: number | Vector2 | Vector3): Vector2 | Vector3 {
52
- if (typeof b === 'number') return a.map((v) => v / b) as Vector2 | Vector3;
53
- return a.map((v, i) => v / b[i]) as Vector2 | Vector3;
75
+ if (typeof b === 'number') return a.map((v) => v / (b as number)) as Vector2 | Vector3;
76
+ [a, b] = padVectors(a, b);
77
+ return a.map((v, i) => {
78
+ if (b[i] == 0) {
79
+ throw new Error(format('Vector could not be divided by zero'));
80
+ }
81
+ return v / b[i];
82
+ }) as Vector2 | Vector3;
54
83
  }
55
84
 
56
85
  /**
@@ -62,6 +91,7 @@ export function divide(a: Vector2 | Vector3, b: number | Vector2 | Vector3): Vec
62
91
  * @returns <zh/> 两个向量的点积 | <en/> The dot product of the two vectors
63
92
  */
64
93
  export function dot(a: Vector2 | Vector3, b: Vector2 | Vector3): number {
94
+ [a, b] = padVectors(a, b);
65
95
  return (a as number[]).reduce((sum, v, i) => sum + v * b[i], 0);
66
96
  }
67
97
 
@@ -100,7 +130,8 @@ export function scale(a: Vector2 | Vector3, s: number): Vector2 | Vector3 {
100
130
  * @returns <zh/> 两个向量间的距离 | <en/> The distance between the two vectors
101
131
  */
102
132
  export function distance(a: Vector2 | Vector3, b: Vector2 | Vector3): number {
103
- return Math.sqrt((a as number[]).reduce((sum, v, i) => sum + (v - b[i] || 0) ** 2, 0));
133
+ [a, b] = padVectors(a, b);
134
+ return Math.sqrt((a as number[]).reduce((sum, v, i) => sum + (v - b[i]) ** 2, 0));
104
135
  }
105
136
 
106
137
  /**
@@ -112,6 +143,7 @@ export function distance(a: Vector2 | Vector3, b: Vector2 | Vector3): number {
112
143
  * @returns <zh/> 两个向量间的距离 | <en/> The distance between the two vectors
113
144
  */
114
145
  export function manhattanDistance(a: Vector2 | Vector3, b: Vector2 | Vector3): number {
146
+ [a, b] = padVectors(a, b);
115
147
  return (a as number[]).reduce((sum, v, i) => sum + Math.abs(v - b[i]), 0);
116
148
  }
117
149
 
@@ -137,6 +169,7 @@ export function normalize(a: Vector2 | Vector3): Vector2 | Vector3 {
137
169
  * @returns <zh/> 弧度值 | <en/> The angle in radians
138
170
  */
139
171
  export function angle(a: Vector2 | Vector3, b: Vector2 | Vector3, clockwise = false): number {
172
+ [a, b] = padVectors(a, b);
140
173
  const determinant = a[0] * b[1] - a[1] * b[0];
141
174
  let angle = Math.acos(
142
175
  (multiply(a, b) as number[]).reduce((sum: number, v: number) => sum + v, 0) /
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const version = '5.1.0-beta.1';
1
+ export const version = '5.1.1';