pin.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { Point } from '@antv/x6-geometry';
  2. function toPercentage(value, max) {
  3. if (max === 0) {
  4. return '0%';
  5. }
  6. return `${Math.round((value / max) * 100)}%`;
  7. }
  8. function pin(relative) {
  9. const strategy = (terminal, view, magnet, coords) => {
  10. return view.isEdgeElement(magnet)
  11. ? pinEdgeTerminal(relative, terminal, view, magnet, coords)
  12. : pinNodeTerminal(relative, terminal, view, magnet, coords);
  13. };
  14. return strategy;
  15. }
  16. function pinNodeTerminal(relative, data, view, magnet, coords) {
  17. const node = view.cell;
  18. const angle = node.getAngle();
  19. const bbox = view.getUnrotatedBBoxOfElement(magnet);
  20. const center = node.getBBox().getCenter();
  21. const pos = Point.create(coords).rotate(angle, center);
  22. let dx = pos.x - bbox.x;
  23. let dy = pos.y - bbox.y;
  24. if (relative) {
  25. dx = toPercentage(dx, bbox.width);
  26. dy = toPercentage(dy, bbox.height);
  27. }
  28. data.anchor = {
  29. name: 'topLeft',
  30. args: {
  31. dx,
  32. dy,
  33. rotate: true,
  34. },
  35. };
  36. return data;
  37. }
  38. function pinEdgeTerminal(relative, end, view, magnet, coords) {
  39. const connection = view.getConnection();
  40. if (!connection) {
  41. return end;
  42. }
  43. const length = connection.closestPointLength(coords);
  44. if (relative) {
  45. const totalLength = connection.length();
  46. end.anchor = {
  47. name: 'ratio',
  48. args: {
  49. ratio: length / totalLength,
  50. },
  51. };
  52. }
  53. else {
  54. end.anchor = {
  55. name: 'length',
  56. args: {
  57. length,
  58. },
  59. };
  60. }
  61. return end;
  62. }
  63. export const pinRelative = pin(true);
  64. export const pinAbsolute = pin(false);
  65. //# sourceMappingURL=pin.js.map