File size: 2,245 Bytes
2740e39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { Position } from '@xyflow/react';

// Geometry for "floating" edges: instead of fixed top/bottom handles, an edge leaves
// and enters each node on the side that faces the other node. This keeps radial
// ("web") layouts readable.

const rectOf = (node) => ({
  x: node.internals.positionAbsolute.x,
  y: node.internals.positionAbsolute.y,
  width: node.measured?.width ?? node.width ?? 0,
  height: node.measured?.height ?? node.height ?? 0,
});

// Point where the line between the two node centres crosses the border of `node`
const intersection = (node, other) => {
  const a = rectOf(node);
  const b = rectOf(other);
  const w = a.width / 2;
  const h = a.height / 2;
  const cx = a.x + w;
  const cy = a.y + h;
  const ox = b.x + b.width / 2;
  const oy = b.y + b.height / 2;
  if (!w || !h) return { x: cx, y: cy };
  const xx1 = (ox - cx) / (2 * w) - (oy - cy) / (2 * h);
  const yy1 = (ox - cx) / (2 * w) + (oy - cy) / (2 * h);
  const k = 1 / (Math.abs(xx1) + Math.abs(yy1) || 1);
  return { x: w * (k * xx1 + k * yy1) + cx, y: h * (-k * xx1 + k * yy1) + cy };
};

const sideOf = (node, point) => {
  const r = rectOf(node);
  if (point.x <= r.x + 1) return Position.Left;
  if (point.x >= r.x + r.width - 1) return Position.Right;
  if (point.y <= r.y + 1) return Position.Top;
  return Position.Bottom;
};

/**
 * Returns { sx, sy, tx, ty, sourcePos, targetPos } for an edge between two internal nodes.
 * `keepSource` / `keepTarget` keep the real handle position (e.g. a condition's branch).
 */
export const floatingPoints = (sourceNode, targetNode, fixed) => {
  const s = intersection(sourceNode, targetNode);
  const t = intersection(targetNode, sourceNode);
  return {
    sx: fixed.keepSource ? fixed.sourceX : s.x,
    sy: fixed.keepSource ? fixed.sourceY : s.y,
    tx: fixed.keepTarget ? fixed.targetX : t.x,
    ty: fixed.keepTarget ? fixed.targetY : t.y,
    sourcePos: fixed.keepSource ? fixed.sourcePosition : sideOf(sourceNode, s),
    targetPos: fixed.keepTarget ? fixed.targetPosition : sideOf(targetNode, t),
  };
};

// Handles whose position carries meaning and must not float
export const isMeaningfulHandle = (node, handleId) =>
  node?.type === 'condition' && handleId && handleId.startsWith('opt-');