@octanejs/xyflow 0.1.0

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 (135) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -0
  3. package/package.json +69 -0
  4. package/src/additional-components/Background/Background.tsrx +144 -0
  5. package/src/additional-components/Background/Patterns.tsrx +32 -0
  6. package/src/additional-components/Background/index.tsrx +2 -0
  7. package/src/additional-components/Background/types.ts +60 -0
  8. package/src/additional-components/Controls/ControlButton.tsrx +34 -0
  9. package/src/additional-components/Controls/Controls.tsrx +148 -0
  10. package/src/additional-components/Controls/Icons/FitView.tsrx +7 -0
  11. package/src/additional-components/Controls/Icons/Lock.tsrx +7 -0
  12. package/src/additional-components/Controls/Icons/Minus.tsrx +5 -0
  13. package/src/additional-components/Controls/Icons/Plus.tsrx +5 -0
  14. package/src/additional-components/Controls/Icons/Unlock.tsrx +7 -0
  15. package/src/additional-components/Controls/index.tsrx +3 -0
  16. package/src/additional-components/Controls/types.ts +68 -0
  17. package/src/additional-components/EdgeToolbar/EdgeToolbar.tsrx +79 -0
  18. package/src/additional-components/EdgeToolbar/index.tsrx +2 -0
  19. package/src/additional-components/EdgeToolbar/types.ts +14 -0
  20. package/src/additional-components/MiniMap/MiniMap.tsrx +249 -0
  21. package/src/additional-components/MiniMap/MiniMapNode.tsrx +43 -0
  22. package/src/additional-components/MiniMap/MiniMapNodes.tsrx +136 -0
  23. package/src/additional-components/MiniMap/index.ts +3 -0
  24. package/src/additional-components/MiniMap/types.ts +139 -0
  25. package/src/additional-components/NodeResizer/NodeResizeControl.tsrx +250 -0
  26. package/src/additional-components/NodeResizer/NodeResizer.tsrx +102 -0
  27. package/src/additional-components/NodeResizer/index.ts +4 -0
  28. package/src/additional-components/NodeResizer/types.ts +122 -0
  29. package/src/additional-components/NodeToolbar/NodeToolbar.tsrx +141 -0
  30. package/src/additional-components/NodeToolbar/NodeToolbarPortal.tsrx +17 -0
  31. package/src/additional-components/NodeToolbar/index.tsrx +2 -0
  32. package/src/additional-components/NodeToolbar/types.ts +32 -0
  33. package/src/additional-components/index.ts +6 -0
  34. package/src/components/A11yDescriptions/index.tsrx +58 -0
  35. package/src/components/Attribution/index.tsrx +31 -0
  36. package/src/components/BatchProvider/index.tsrx +122 -0
  37. package/src/components/BatchProvider/types.ts +7 -0
  38. package/src/components/BatchProvider/useQueue.ts +62 -0
  39. package/src/components/ConnectionLine/index.tsrx +140 -0
  40. package/src/components/EdgeLabelRenderer/index.tsrx +62 -0
  41. package/src/components/EdgeWrapper/EdgeUpdateAnchors.tsrx +151 -0
  42. package/src/components/EdgeWrapper/index.tsrx +274 -0
  43. package/src/components/EdgeWrapper/utils.ts +26 -0
  44. package/src/components/Edges/BaseEdge.tsrx +76 -0
  45. package/src/components/Edges/BezierEdge.tsrx +94 -0
  46. package/src/components/Edges/EdgeAnchor.tsrx +54 -0
  47. package/src/components/Edges/EdgeText.tsrx +97 -0
  48. package/src/components/Edges/SimpleBezierEdge.tsrx +150 -0
  49. package/src/components/Edges/SmoothStepEdge.tsrx +96 -0
  50. package/src/components/Edges/StepEdge.tsrx +55 -0
  51. package/src/components/Edges/StraightEdge.tsrx +81 -0
  52. package/src/components/Edges/index.ts +11 -0
  53. package/src/components/Handle/index.tsrx +314 -0
  54. package/src/components/NodeWrapper/index.tsrx +259 -0
  55. package/src/components/NodeWrapper/useNodeObserver.ts +79 -0
  56. package/src/components/NodeWrapper/utils.tsrx +40 -0
  57. package/src/components/Nodes/DefaultNode.tsrx +17 -0
  58. package/src/components/Nodes/GroupNode.tsrx +3 -0
  59. package/src/components/Nodes/InputNode.tsrx +13 -0
  60. package/src/components/Nodes/OutputNode.tsrx +13 -0
  61. package/src/components/Nodes/utils.ts +45 -0
  62. package/src/components/NodesSelection/index.tsrx +103 -0
  63. package/src/components/Panel/index.tsrx +34 -0
  64. package/src/components/ReactFlowProvider/index.tsrx +128 -0
  65. package/src/components/SelectionListener/index.tsrx +73 -0
  66. package/src/components/StoreUpdater/index.tsrx +173 -0
  67. package/src/components/UserSelection/index.tsrx +27 -0
  68. package/src/components/ViewportPortal/index.tsrx +42 -0
  69. package/src/container/EdgeRenderer/MarkerDefinitions.tsrx +87 -0
  70. package/src/container/EdgeRenderer/MarkerSymbols.tsrx +60 -0
  71. package/src/container/EdgeRenderer/index.tsrx +98 -0
  72. package/src/container/FlowRenderer/index.tsrx +146 -0
  73. package/src/container/GraphView/index.tsrx +212 -0
  74. package/src/container/GraphView/useNodeOrEdgeTypesWarning.ts +39 -0
  75. package/src/container/GraphView/useStylesLoadedWarning.ts +26 -0
  76. package/src/container/NodeRenderer/index.tsrx +103 -0
  77. package/src/container/NodeRenderer/useResizeObserver.ts +38 -0
  78. package/src/container/Pane/index.tsrx +397 -0
  79. package/src/container/ReactFlow/Wrapper.tsrx +66 -0
  80. package/src/container/ReactFlow/index.tsrx +352 -0
  81. package/src/container/ReactFlow/init-values.ts +4 -0
  82. package/src/container/Viewport/index.tsrx +52 -0
  83. package/src/container/ZoomPane/index.tsrx +159 -0
  84. package/src/contexts/HandleConfigContext.tsrx +38 -0
  85. package/src/contexts/NodeIdContext.ts +39 -0
  86. package/src/contexts/StoreContext.ts +8 -0
  87. package/src/custom.d.ts +13 -0
  88. package/src/hooks/slot.ts +22 -0
  89. package/src/hooks/useColorModeClass.ts +50 -0
  90. package/src/hooks/useConnection.ts +69 -0
  91. package/src/hooks/useDrag.ts +95 -0
  92. package/src/hooks/useEdges.ts +32 -0
  93. package/src/hooks/useGlobalKeyHandler.ts +55 -0
  94. package/src/hooks/useHandleConnections.ts +77 -0
  95. package/src/hooks/useInternalNode.ts +47 -0
  96. package/src/hooks/useIsomorphicLayoutEffect.ts +5 -0
  97. package/src/hooks/useKeyPress.ts +217 -0
  98. package/src/hooks/useMoveSelectedNodes.ts +82 -0
  99. package/src/hooks/useNodeConnections.ts +86 -0
  100. package/src/hooks/useNodes.ts +33 -0
  101. package/src/hooks/useNodesData.ts +66 -0
  102. package/src/hooks/useNodesEdgesState.ts +138 -0
  103. package/src/hooks/useNodesInitialized.ts +74 -0
  104. package/src/hooks/useOnEdgesChangeMiddleware.ts +46 -0
  105. package/src/hooks/useOnInitHandler.ts +27 -0
  106. package/src/hooks/useOnNodesChangeMiddleware.ts +46 -0
  107. package/src/hooks/useOnSelectionChange.ts +78 -0
  108. package/src/hooks/useOnViewportChange.ts +68 -0
  109. package/src/hooks/useReactFlow.ts +347 -0
  110. package/src/hooks/useResizeHandler.ts +54 -0
  111. package/src/hooks/useStore.ts +58 -0
  112. package/src/hooks/useUpdateNodeInternals.ts +73 -0
  113. package/src/hooks/useViewport.ts +48 -0
  114. package/src/hooks/useViewportHelper.ts +103 -0
  115. package/src/hooks/useViewportSync.ts +33 -0
  116. package/src/hooks/useVisibleEdgeIds.ts +52 -0
  117. package/src/hooks/useVisibleNodeIds.ts +36 -0
  118. package/src/index.ts +151 -0
  119. package/src/react-shim.ts +93 -0
  120. package/src/store/index.ts +516 -0
  121. package/src/store/initialState.ts +162 -0
  122. package/src/styles/base.css +516 -0
  123. package/src/styles/style.css +648 -0
  124. package/src/styles/utils.ts +9 -0
  125. package/src/types/component-props.ts +716 -0
  126. package/src/types/edges.ts +312 -0
  127. package/src/types/general.ts +239 -0
  128. package/src/types/index.ts +6 -0
  129. package/src/types/instance.ts +265 -0
  130. package/src/types/nodes.ts +144 -0
  131. package/src/types/store.ts +198 -0
  132. package/src/utils/changes.ts +329 -0
  133. package/src/utils/edges.ts +34 -0
  134. package/src/utils/general.ts +72 -0
  135. package/src/utils/index.ts +3 -0
@@ -0,0 +1,150 @@
1
+ import { memo } from 'octane';
2
+ import { Position, getBezierEdgeCenter } from '@xyflow/system';
3
+
4
+ import { BaseEdge } from './BaseEdge.tsrx';
5
+ import type { SimpleBezierEdgeProps } from '../../types';
6
+
7
+ export interface GetSimpleBezierPathParams {
8
+ sourceX: number;
9
+ sourceY: number;
10
+ /** @default Position.Bottom */
11
+ sourcePosition?: Position;
12
+ targetX: number;
13
+ targetY: number;
14
+ /** @default Position.Top */
15
+ targetPosition?: Position;
16
+ }
17
+
18
+ interface GetControlParams {
19
+ pos: Position;
20
+ x1: number;
21
+ y1: number;
22
+ x2: number;
23
+ y2: number;
24
+ }
25
+
26
+ function getControl({ pos, x1, y1, x2, y2 }: GetControlParams): [number, number] {
27
+ if (pos === Position.Left || pos === Position.Right) {
28
+ return [0.5 * (x1 + x2), y1];
29
+ }
30
+
31
+ return [x1, 0.5 * (y1 + y2)];
32
+ }
33
+
34
+ /**
35
+ * The `getSimpleBezierPath` util returns everything you need to render a simple
36
+ * bezier edge between two nodes.
37
+ * @public
38
+ * @returns
39
+ * - `path`: the path to use in an SVG `<path>` element.
40
+ * - `labelX`: the `x` position you can use to render a label for this edge.
41
+ * - `labelY`: the `y` position you can use to render a label for this edge.
42
+ * - `offsetX`: the absolute difference between the source `x` position and the `x` position of the
43
+ * middle of this path.
44
+ * - `offsetY`: the absolute difference between the source `y` position and the `y` position of the
45
+ * middle of this path.
46
+ */
47
+ export function getSimpleBezierPath({
48
+ sourceX,
49
+ sourceY,
50
+ sourcePosition = Position.Bottom,
51
+ targetX,
52
+ targetY,
53
+ targetPosition = Position.Top,
54
+ }: GetSimpleBezierPathParams): [path: string, labelX: number, labelY: number, offsetX: number, offsetY: number] {
55
+ const [sourceControlX, sourceControlY] = getControl({
56
+ pos: sourcePosition,
57
+ x1: sourceX,
58
+ y1: sourceY,
59
+ x2: targetX,
60
+ y2: targetY,
61
+ });
62
+ const [targetControlX, targetControlY] = getControl({
63
+ pos: targetPosition,
64
+ x1: targetX,
65
+ y1: targetY,
66
+ x2: sourceX,
67
+ y2: sourceY,
68
+ });
69
+ const [labelX, labelY, offsetX, offsetY] = getBezierEdgeCenter({
70
+ sourceX,
71
+ sourceY,
72
+ targetX,
73
+ targetY,
74
+ sourceControlX,
75
+ sourceControlY,
76
+ targetControlX,
77
+ targetControlY,
78
+ });
79
+
80
+ return [
81
+ `M${sourceX},${sourceY} C${sourceControlX},${sourceControlY} ${targetControlX},${targetControlY} ${targetX},${targetY}`,
82
+ labelX,
83
+ labelY,
84
+ offsetX,
85
+ offsetY,
86
+ ];
87
+ }
88
+
89
+ function createSimpleBezierEdge(params: { isInternal: boolean }) {
90
+ // eslint-disable-next-line react/display-name
91
+ return memo(({
92
+ id,
93
+ sourceX,
94
+ sourceY,
95
+ targetX,
96
+ targetY,
97
+ sourcePosition,
98
+ targetPosition,
99
+ label,
100
+ labelStyle,
101
+ labelShowBg,
102
+ labelBgStyle,
103
+ labelBgPadding,
104
+ labelBgBorderRadius,
105
+ style,
106
+ markerEnd,
107
+ markerStart,
108
+ interactionWidth,
109
+ }: SimpleBezierEdgeProps) => {
110
+ const [path, labelX, labelY] = getSimpleBezierPath({
111
+ sourceX,
112
+ sourceY,
113
+ sourcePosition,
114
+ targetX,
115
+ targetY,
116
+ targetPosition,
117
+ });
118
+
119
+ const _id = params.isInternal ? undefined : id;
120
+
121
+ return <BaseEdge
122
+ id={_id}
123
+ path={path}
124
+ labelX={labelX}
125
+ labelY={labelY}
126
+ label={label}
127
+ labelStyle={labelStyle}
128
+ labelShowBg={labelShowBg}
129
+ labelBgStyle={labelBgStyle}
130
+ labelBgPadding={labelBgPadding}
131
+ labelBgBorderRadius={labelBgBorderRadius}
132
+ style={style}
133
+ markerEnd={markerEnd}
134
+ markerStart={markerStart}
135
+ interactionWidth={interactionWidth}
136
+ />;
137
+ });
138
+ }
139
+
140
+ const SimpleBezierEdge = createSimpleBezierEdge({ isInternal: false });
141
+ const SimpleBezierEdgeInternal = createSimpleBezierEdge({ isInternal: true });
142
+
143
+ (SimpleBezierEdge as typeof SimpleBezierEdge & { displayName?: string }).displayName =
144
+ 'SimpleBezierEdge';
145
+ (SimpleBezierEdgeInternal as
146
+ typeof SimpleBezierEdgeInternal & {
147
+ displayName?: string;
148
+ }).displayName = 'SimpleBezierEdgeInternal';
149
+
150
+ export { SimpleBezierEdge, SimpleBezierEdgeInternal };
@@ -0,0 +1,96 @@
1
+ import { memo } from 'octane';
2
+ import { Position, getSmoothStepPath } from '@xyflow/system';
3
+
4
+ import { BaseEdge } from './BaseEdge.tsrx';
5
+ import type { SmoothStepEdgeProps } from '../../types';
6
+
7
+ function createSmoothStepEdge(params: { isInternal: boolean }) {
8
+ // eslint-disable-next-line react/display-name
9
+ return memo(({
10
+ id,
11
+ sourceX,
12
+ sourceY,
13
+ targetX,
14
+ targetY,
15
+ label,
16
+ labelStyle,
17
+ labelShowBg,
18
+ labelBgStyle,
19
+ labelBgPadding,
20
+ labelBgBorderRadius,
21
+ style,
22
+ sourcePosition = Position.Bottom,
23
+ targetPosition = Position.Top,
24
+ markerEnd,
25
+ markerStart,
26
+ pathOptions,
27
+ interactionWidth,
28
+ }: SmoothStepEdgeProps) => {
29
+ const [path, labelX, labelY] = getSmoothStepPath({
30
+ sourceX,
31
+ sourceY,
32
+ sourcePosition,
33
+ targetX,
34
+ targetY,
35
+ targetPosition,
36
+ borderRadius: pathOptions?.borderRadius,
37
+ offset: pathOptions?.offset,
38
+ stepPosition: pathOptions?.stepPosition,
39
+ });
40
+
41
+ const _id = params.isInternal ? undefined : id;
42
+
43
+ return <BaseEdge
44
+ id={_id}
45
+ path={path}
46
+ labelX={labelX}
47
+ labelY={labelY}
48
+ label={label}
49
+ labelStyle={labelStyle}
50
+ labelShowBg={labelShowBg}
51
+ labelBgStyle={labelBgStyle}
52
+ labelBgPadding={labelBgPadding}
53
+ labelBgBorderRadius={labelBgBorderRadius}
54
+ style={style}
55
+ markerEnd={markerEnd}
56
+ markerStart={markerStart}
57
+ interactionWidth={interactionWidth}
58
+ />;
59
+ });
60
+ }
61
+
62
+ /**
63
+ * Component that can be used inside a custom edge to render a smooth step edge.
64
+ *
65
+ * @public
66
+ * @example
67
+ *
68
+ * ```tsx
69
+ * import { SmoothStepEdge } from '@xyflow/react';
70
+ *
71
+ * function CustomEdge({ sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition }) {
72
+ * return (
73
+ * <SmoothStepEdge
74
+ * sourceX={sourceX}
75
+ * sourceY={sourceY}
76
+ * targetX={targetX}
77
+ * targetY={targetY}
78
+ * sourcePosition={sourcePosition}
79
+ * targetPosition={targetPosition}
80
+ * />
81
+ * );
82
+ * }
83
+ * ```
84
+ */
85
+ const SmoothStepEdge = createSmoothStepEdge({ isInternal: false });
86
+
87
+ /**
88
+ * @internal
89
+ */
90
+ const SmoothStepEdgeInternal = createSmoothStepEdge({ isInternal: true });
91
+
92
+ (SmoothStepEdge as typeof SmoothStepEdge & { displayName?: string }).displayName = 'SmoothStepEdge';
93
+ (SmoothStepEdgeInternal as typeof SmoothStepEdgeInternal & { displayName?: string }).displayName =
94
+ 'SmoothStepEdgeInternal';
95
+
96
+ export { SmoothStepEdge, SmoothStepEdgeInternal };
@@ -0,0 +1,55 @@
1
+ import { memo, useMemo } from 'octane';
2
+
3
+ import { SmoothStepEdge } from './SmoothStepEdge.tsrx';
4
+ import type { StepEdgeProps } from '../../types';
5
+
6
+ function createStepEdge(params: { isInternal: boolean }) {
7
+ // eslint-disable-next-line react/display-name
8
+ return memo(({ id, ...props }: StepEdgeProps) => {
9
+ const _id = params.isInternal ? undefined : id;
10
+
11
+ return <SmoothStepEdge
12
+ {...props}
13
+ id={_id}
14
+ pathOptions={useMemo(() => ({ borderRadius: 0, offset: props.pathOptions?.offset }), [
15
+ props.pathOptions?.offset,
16
+ ])}
17
+ />;
18
+ });
19
+ }
20
+
21
+ /**
22
+ * Component that can be used inside a custom edge to render a step edge.
23
+ *
24
+ * @public
25
+ * @example
26
+ *
27
+ * ```tsx
28
+ * import { StepEdge } from '@xyflow/react';
29
+ *
30
+ * function CustomEdge({ sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition }) {
31
+ * return (
32
+ * <StepEdge
33
+ * sourceX={sourceX}
34
+ * sourceY={sourceY}
35
+ * targetX={targetX}
36
+ * targetY={targetY}
37
+ * sourcePosition={sourcePosition}
38
+ * targetPosition={targetPosition}
39
+ * />
40
+ * );
41
+ * }
42
+ * ```
43
+ */
44
+ const StepEdge = createStepEdge({ isInternal: false });
45
+
46
+ /**
47
+ * @internal
48
+ */
49
+ const StepEdgeInternal = createStepEdge({ isInternal: true });
50
+
51
+ (StepEdge as typeof StepEdge & { displayName?: string }).displayName = 'StepEdge';
52
+ (StepEdgeInternal as typeof StepEdgeInternal & { displayName?: string }).displayName =
53
+ 'StepEdgeInternal';
54
+
55
+ export { StepEdge, StepEdgeInternal };
@@ -0,0 +1,81 @@
1
+ import { memo } from 'octane';
2
+ import { getStraightPath } from '@xyflow/system';
3
+
4
+ import { BaseEdge } from './BaseEdge.tsrx';
5
+ import type { StraightEdgeProps } from '../../types';
6
+
7
+ function createStraightEdge(params: { isInternal: boolean }) {
8
+ // eslint-disable-next-line react/display-name
9
+ return memo(({
10
+ id,
11
+ sourceX,
12
+ sourceY,
13
+ targetX,
14
+ targetY,
15
+ label,
16
+ labelStyle,
17
+ labelShowBg,
18
+ labelBgStyle,
19
+ labelBgPadding,
20
+ labelBgBorderRadius,
21
+ style,
22
+ markerEnd,
23
+ markerStart,
24
+ interactionWidth,
25
+ }: StraightEdgeProps) => {
26
+ const [path, labelX, labelY] = getStraightPath({ sourceX, sourceY, targetX, targetY });
27
+
28
+ const _id = params.isInternal ? undefined : id;
29
+
30
+ return <BaseEdge
31
+ id={_id}
32
+ path={path}
33
+ labelX={labelX}
34
+ labelY={labelY}
35
+ label={label}
36
+ labelStyle={labelStyle}
37
+ labelShowBg={labelShowBg}
38
+ labelBgStyle={labelBgStyle}
39
+ labelBgPadding={labelBgPadding}
40
+ labelBgBorderRadius={labelBgBorderRadius}
41
+ style={style}
42
+ markerEnd={markerEnd}
43
+ markerStart={markerStart}
44
+ interactionWidth={interactionWidth}
45
+ />;
46
+ });
47
+ }
48
+
49
+ /**
50
+ * Component that can be used inside a custom edge to render a straight line.
51
+ *
52
+ * @public
53
+ * @example
54
+ *
55
+ * ```tsx
56
+ * import { StraightEdge } from '@xyflow/react';
57
+ *
58
+ * function CustomEdge({ sourceX, sourceY, targetX, targetY }) {
59
+ * return (
60
+ * <StraightEdge
61
+ * sourceX={sourceX}
62
+ * sourceY={sourceY}
63
+ * targetX={targetX}
64
+ * targetY={targetY}
65
+ * />
66
+ * );
67
+ * }
68
+ * ```
69
+ */
70
+ const StraightEdge = createStraightEdge({ isInternal: false });
71
+
72
+ /**
73
+ * @internal
74
+ */
75
+ const StraightEdgeInternal = createStraightEdge({ isInternal: true });
76
+
77
+ (StraightEdge as typeof StraightEdge & { displayName?: string }).displayName = 'StraightEdge';
78
+ (StraightEdgeInternal as typeof StraightEdgeInternal & { displayName?: string }).displayName =
79
+ 'StraightEdgeInternal';
80
+
81
+ export { StraightEdge, StraightEdgeInternal };
@@ -0,0 +1,11 @@
1
+ /*
2
+ * We distinguish between internal and exported edges
3
+ * The internal edges are used directly like custom edges and always get an id, source and target props
4
+ * If you import an edge from the library, the id is optional and source and target are not used at all
5
+ */
6
+
7
+ export { SimpleBezierEdge, SimpleBezierEdgeInternal } from './SimpleBezierEdge.tsrx';
8
+ export { SmoothStepEdge, SmoothStepEdgeInternal } from './SmoothStepEdge.tsrx';
9
+ export { StepEdge, StepEdgeInternal } from './StepEdge.tsrx';
10
+ export { StraightEdge, StraightEdgeInternal } from './StraightEdge.tsrx';
11
+ export { BezierEdge, BezierEdgeInternal } from './BezierEdge.tsrx';
@@ -0,0 +1,314 @@
1
+ import { memo } from 'octane';
2
+ import type {
3
+ HTMLAttributes,
4
+ MouseEvent as ReactMouseEvent,
5
+ TouchEvent as ReactTouchEvent,
6
+ ForwardedRef,
7
+ } from '../../react-shim.js';
8
+ import cc from 'classcat';
9
+ import { shallow } from '@octanejs/zustand/shallow';
10
+ import {
11
+ errorMessages,
12
+ Position,
13
+ XYHandle,
14
+ getHostForElement,
15
+ isMouseEvent,
16
+ type HandleProps as HandlePropsSystem,
17
+ type Connection,
18
+ type HandleType,
19
+ ConnectionMode,
20
+ OnConnect,
21
+ ConnectionState,
22
+ FinalConnectionState,
23
+ Optional,
24
+ } from '@xyflow/system';
25
+
26
+ import { useStore, useStoreApi } from '../../hooks/useStore';
27
+ import { useNodeId } from '../../contexts/NodeIdContext';
28
+ import { useHandleConfig } from '../../contexts/HandleConfigContext.tsrx';
29
+ import { type ReactFlowState } from '../../types';
30
+ import { fixedForwardRef } from '../../utils';
31
+ import { addEdge } from '../../utils/edges';
32
+
33
+ /**
34
+ * @expand
35
+ */
36
+ export type HandleProps =
37
+ HandlePropsSystem & Omit<HTMLAttributes<HTMLDivElement>, 'id'> & {
38
+ /** Callback called when connection is made */
39
+ onConnect?: OnConnect;
40
+ };
41
+
42
+ const selector = (s: ReactFlowState) => ({
43
+ connectOnClick: s.connectOnClick,
44
+ noPanClassName: s.noPanClassName,
45
+ rfId: s.rfId,
46
+ });
47
+
48
+ /*
49
+ * While no connection is in progress every handle has this same state, so we return a
50
+ * shared reference rather than allocating + shallow-comparing one per handle on every
51
+ * store update. `isPossibleEndHandle` matches what the selector computes when idle.
52
+ */
53
+ const idleConnectingState = {
54
+ connectingFrom: false,
55
+ connectingTo: false,
56
+ clickConnecting: false,
57
+ isPossibleEndHandle: true,
58
+ connectionInProcess: false,
59
+ clickConnectionInProcess: false,
60
+ valid: false,
61
+ };
62
+
63
+ const connectingSelector = (nodeId: string | null, handleId: string | null, type: HandleType) => (
64
+ state: ReactFlowState,
65
+ ) => {
66
+ const { connectionClickStartHandle: clickHandle, connectionMode, connection } = state;
67
+ const { fromHandle, toHandle, isValid } = connection;
68
+
69
+ if (!fromHandle && !clickHandle) {
70
+ return idleConnectingState;
71
+ }
72
+
73
+ const connectingTo =
74
+ toHandle?.nodeId === nodeId && toHandle?.id === handleId && toHandle?.type === type;
75
+
76
+ return {
77
+ connectingFrom: fromHandle?.nodeId === nodeId && fromHandle?.id === handleId &&
78
+ fromHandle?.type === type,
79
+ connectingTo,
80
+ clickConnecting: clickHandle?.nodeId === nodeId && clickHandle?.id === handleId &&
81
+ clickHandle?.type === type,
82
+ isPossibleEndHandle: connectionMode === ConnectionMode.Strict
83
+ ? fromHandle?.type !== type
84
+ : nodeId !== fromHandle?.nodeId || handleId !== fromHandle?.id,
85
+ connectionInProcess: !!fromHandle,
86
+ clickConnectionInProcess: !!clickHandle,
87
+ valid: connectingTo && isValid,
88
+ };
89
+ };
90
+
91
+ function HandleComponent(
92
+ {
93
+ type = 'source',
94
+ position = Position.Top,
95
+ isValidConnection,
96
+ isConnectable = true,
97
+ isConnectableStart = true,
98
+ isConnectableEnd = true,
99
+ id,
100
+ onConnect,
101
+ children,
102
+ className,
103
+ onMouseDown,
104
+ onTouchStart,
105
+ ...rest
106
+ }: HandleProps,
107
+ ref: ForwardedRef<HTMLDivElement>,
108
+ ) {
109
+ const handleId = id || null;
110
+ const isTarget = type === 'target';
111
+ const store = useStoreApi();
112
+ const nodeId = useNodeId();
113
+ const { connectOnClick, noPanClassName, rfId } = useHandleConfig();
114
+ const {
115
+ connectingFrom,
116
+ connectingTo,
117
+ clickConnecting,
118
+ isPossibleEndHandle,
119
+ connectionInProcess,
120
+ clickConnectionInProcess,
121
+ valid,
122
+ } = useStore(connectingSelector(nodeId, handleId, type), shallow);
123
+ if (!nodeId) {
124
+ store.getState().onError?.('010', errorMessages['error010']());
125
+ }
126
+
127
+ const onConnectExtended = (params: Connection) => {
128
+ const { defaultEdgeOptions, onConnect: onConnectAction, hasDefaultEdges } = store.getState();
129
+
130
+ const edgeParams = {
131
+ ...defaultEdgeOptions,
132
+ ...params,
133
+ };
134
+ if (hasDefaultEdges) {
135
+ const { edges, setEdges, onError } = store.getState();
136
+ setEdges(addEdge(edgeParams, edges, { onError }));
137
+ }
138
+
139
+ onConnectAction?.(edgeParams);
140
+ onConnect?.(edgeParams);
141
+ };
142
+ const onPointerDown = (
143
+ event: ReactMouseEvent<HTMLDivElement> | ReactTouchEvent<HTMLDivElement>,
144
+ ) => {
145
+ if (!nodeId) {
146
+ return;
147
+ }
148
+
149
+ const isMouseTriggered = isMouseEvent(event);
150
+
151
+ if (
152
+ isConnectableStart &&
153
+ (isMouseTriggered && (event as ReactMouseEvent<HTMLDivElement>).button === 0 ||
154
+ !isMouseTriggered)
155
+ ) {
156
+ const currentStore = store.getState();
157
+ const fallbackIsValidConnection: NonNullable<HandleProps['isValidConnection']> = (...args) =>
158
+ store.getState().isValidConnection?.(...args) ?? true;
159
+
160
+ XYHandle.onPointerDown(event, {
161
+ handleDomNode: event.currentTarget,
162
+ autoPanOnConnect: currentStore.autoPanOnConnect,
163
+ connectionMode: currentStore.connectionMode,
164
+ connectionRadius: currentStore.connectionRadius,
165
+ domNode: currentStore.domNode,
166
+ nodeLookup: currentStore.nodeLookup,
167
+ lib: currentStore.lib,
168
+ isTarget,
169
+ handleId,
170
+ nodeId,
171
+ flowId: currentStore.rfId,
172
+ panBy: currentStore.panBy,
173
+ cancelConnection: currentStore.cancelConnection,
174
+ onConnectStart: currentStore.onConnectStart,
175
+ onConnectEnd: (...args) => store.getState().onConnectEnd?.(...args),
176
+ updateConnection: currentStore.updateConnection,
177
+ onConnect: onConnectExtended,
178
+ isValidConnection: isValidConnection || fallbackIsValidConnection,
179
+ getTransform: () => store.getState().transform,
180
+ getFromHandle: () => store.getState().connection.fromHandle,
181
+ autoPanSpeed: currentStore.autoPanSpeed,
182
+ dragThreshold: currentStore.connectionDragThreshold,
183
+ });
184
+ }
185
+
186
+ if (isMouseTriggered) {
187
+ onMouseDown?.(event as ReactMouseEvent<HTMLDivElement>);
188
+ } else {
189
+ onTouchStart?.(event as ReactTouchEvent<HTMLDivElement>);
190
+ }
191
+ };
192
+
193
+ const onClick = (event: ReactMouseEvent) => {
194
+ const {
195
+ onClickConnectStart,
196
+ onClickConnectEnd,
197
+ connectionClickStartHandle,
198
+ connectionMode,
199
+ isValidConnection: isValidConnectionStore,
200
+ lib,
201
+ rfId: flowId,
202
+ nodeLookup,
203
+ connection: connectionState,
204
+ } = store.getState();
205
+
206
+ if (!nodeId || !connectionClickStartHandle && !isConnectableStart) {
207
+ return;
208
+ }
209
+
210
+ if (!connectionClickStartHandle) {
211
+ onClickConnectStart?.(event, { nodeId, handleId, handleType: type });
212
+ store.setState({ connectionClickStartHandle: { nodeId, type, id: handleId } });
213
+ return;
214
+ }
215
+
216
+ const doc = getHostForElement(event.target as Element);
217
+ const isValidConnectionHandler = isValidConnection || isValidConnectionStore;
218
+ const { connection, isValid } = XYHandle.isValid(event, {
219
+ handle: {
220
+ nodeId,
221
+ id: handleId,
222
+ type,
223
+ },
224
+ connectionMode,
225
+ fromNodeId: connectionClickStartHandle.nodeId,
226
+ fromHandleId: connectionClickStartHandle.id || null,
227
+ fromType: connectionClickStartHandle.type,
228
+ isValidConnection: isValidConnectionHandler,
229
+ flowId,
230
+ doc,
231
+ lib,
232
+ nodeLookup,
233
+ });
234
+
235
+ if (isValid && connection) {
236
+ onConnectExtended(connection);
237
+ }
238
+
239
+ const connectionClone = structuredClone(connectionState) as Optional<
240
+ ConnectionState,
241
+ 'inProgress'
242
+ >;
243
+ delete connectionClone.inProgress;
244
+ connectionClone.toPosition = connectionClone.toHandle
245
+ ? connectionClone.toHandle.position
246
+ : null;
247
+ onClickConnectEnd?.(event as unknown as MouseEvent, connectionClone as FinalConnectionState);
248
+
249
+ store.setState({ connectionClickStartHandle: null });
250
+ };
251
+
252
+ return <div
253
+ data-handleid={handleId}
254
+ data-nodeid={nodeId}
255
+ data-handlepos={position}
256
+ data-id={`${rfId}-${nodeId}-${handleId}-${type}`}
257
+ className={cc([
258
+ 'react-flow__handle',
259
+ `react-flow__handle-${position}`,
260
+ 'nodrag',
261
+ noPanClassName,
262
+ className,
263
+ {
264
+ source: !isTarget,
265
+ target: isTarget,
266
+ connectable: isConnectable,
267
+ connectablestart: isConnectableStart,
268
+ connectableend: isConnectableEnd,
269
+ clickconnecting: clickConnecting,
270
+ connectingfrom: connectingFrom,
271
+ connectingto: connectingTo,
272
+ valid,
273
+ /*
274
+ * shows where you can start a connection from
275
+ * and where you can end it while connecting
276
+ */
277
+ connectionindicator: isConnectable && (!connectionInProcess || isPossibleEndHandle) &&
278
+ (connectionInProcess || clickConnectionInProcess ? isConnectableEnd : isConnectableStart),
279
+ },
280
+ ])}
281
+ onMouseDown={onPointerDown}
282
+ onTouchStart={onPointerDown}
283
+ onClick={connectOnClick ? onClick : undefined}
284
+ ref={ref}
285
+ {...rest}
286
+ >{children}</div>;
287
+ }
288
+
289
+ /**
290
+ * The `<Handle />` component is used in your [custom nodes](/learn/customization/custom-nodes)
291
+ * to define connection points.
292
+ *
293
+ *@public
294
+ *
295
+ *@example
296
+ *
297
+ *```jsx
298
+ *import { Handle, Position } from '@xyflow/react';
299
+ *
300
+ *export function CustomNode({ data }) {
301
+ * return (
302
+ * <>
303
+ * <div style={{ padding: '10px 20px' }}>
304
+ * {data.label}
305
+ * </div>
306
+ *
307
+ * <Handle type="target" position={Position.Left} />
308
+ * <Handle type="source" position={Position.Right} />
309
+ * </>
310
+ * );
311
+ *};
312
+ *```
313
+ */
314
+ export const Handle = memo(fixedForwardRef(HandleComponent));