@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,82 @@
1
+ import { useCallback } from 'octane';
2
+ import { resolveHookSlot } from './slot';
3
+ import { calculateNodePosition, snapPosition, type XYPosition } from '@xyflow/system';
4
+
5
+ import { type Node } from '../types';
6
+ import { useStoreApi } from './useStore';
7
+
8
+ const selectedAndDraggable = (nodesDraggable: boolean) => (n: Node) =>
9
+ n.selected && (n.draggable || (nodesDraggable && typeof n.draggable === 'undefined'));
10
+
11
+ /**
12
+ * Hook for updating node positions by passing a direction and factor
13
+ *
14
+ * @internal
15
+ * @returns function for updating node positions
16
+ */
17
+ export function useMoveSelectedNodes(...rest: [slot?: symbol]) {
18
+ const slot = resolveHookSlot(rest);
19
+ const store = useStoreApi(slot);
20
+
21
+ const moveSelectedNodes = useCallback(
22
+ function moveSelectedNodes(params: { direction: XYPosition; factor: number }) {
23
+ const {
24
+ nodeExtent,
25
+ snapToGrid,
26
+ snapGrid,
27
+ nodesDraggable,
28
+ onError,
29
+ updateNodePositions,
30
+ nodeLookup,
31
+ nodeOrigin,
32
+ } = store.getState();
33
+ const nodeUpdates = new Map();
34
+ const isSelected = selectedAndDraggable(nodesDraggable);
35
+
36
+ /*
37
+ * by default a node moves 5px on each key press
38
+ * if snap grid is enabled, we use that for the velocity
39
+ */
40
+ const xVelo = snapToGrid ? snapGrid[0] : 5;
41
+ const yVelo = snapToGrid ? snapGrid[1] : 5;
42
+
43
+ const xDiff = params.direction.x * xVelo * params.factor;
44
+ const yDiff = params.direction.y * yVelo * params.factor;
45
+
46
+ for (const [, node] of nodeLookup) {
47
+ if (!isSelected(node)) {
48
+ continue;
49
+ }
50
+
51
+ let nextPosition = {
52
+ x: node.internals.positionAbsolute.x + xDiff,
53
+ y: node.internals.positionAbsolute.y + yDiff,
54
+ };
55
+
56
+ if (snapToGrid) {
57
+ nextPosition = snapPosition(nextPosition, snapGrid);
58
+ }
59
+
60
+ const { position, positionAbsolute } = calculateNodePosition({
61
+ nodeId: node.id,
62
+ nextPosition,
63
+ nodeLookup,
64
+ nodeExtent,
65
+ nodeOrigin,
66
+ onError,
67
+ });
68
+
69
+ node.position = position;
70
+ node.internals.positionAbsolute = positionAbsolute;
71
+
72
+ nodeUpdates.set(node.id, node);
73
+ }
74
+
75
+ updateNodePositions(nodeUpdates);
76
+ },
77
+ [],
78
+ slot,
79
+ );
80
+
81
+ return moveSelectedNodes;
82
+ }
@@ -0,0 +1,86 @@
1
+ import { useEffect, useMemo, useRef } from 'octane';
2
+ import { resolveHookSlot, subSlot, withoutSlot } from './slot';
3
+ import {
4
+ areConnectionMapsEqual,
5
+ errorMessages,
6
+ handleConnectionChange,
7
+ type NodeConnection,
8
+ type UseNodeConnectionsParams,
9
+ } from '@xyflow/system';
10
+
11
+ import { useStore } from './useStore';
12
+ import { useNodeId } from '../contexts/NodeIdContext';
13
+
14
+ const error014 = errorMessages['error014']();
15
+
16
+ /**
17
+ * This hook returns an array of connections on a specific node, handle type ('source', 'target') or handle ID.
18
+ *
19
+ * @public
20
+ * @returns An array with connections.
21
+ *
22
+ * @example
23
+ * ```jsx
24
+ *import { useNodeConnections } from '@xyflow/react';
25
+ *
26
+ *export default function () {
27
+ * const connections = useNodeConnections({
28
+ * handleType: 'target',
29
+ * handleId: 'my-handle',
30
+ * });
31
+ *
32
+ * return (
33
+ * <div>There are currently {connections.length} incoming connections!</div>
34
+ * );
35
+ *}
36
+ *```
37
+ */
38
+ export function useNodeConnections(
39
+ params: UseNodeConnectionsParams | symbol = {},
40
+ ...rest: [slot?: symbol]
41
+ ): NodeConnection[] {
42
+ let slot = resolveHookSlot(rest);
43
+ const resolved = withoutSlot(params) ?? {};
44
+ const { id, handleType, handleId, onConnect, onDisconnect } = resolved;
45
+ const nodeId = useNodeId();
46
+ const currentNodeId = id ?? nodeId;
47
+
48
+ if (!currentNodeId) {
49
+ throw new Error(error014);
50
+ }
51
+
52
+ const prevConnections = useRef<Map<string, NodeConnection> | null>(
53
+ null,
54
+ subSlot(slot, 'previous-connections'),
55
+ );
56
+
57
+ const connections = useStore(
58
+ (state) =>
59
+ state.connectionLookup.get(
60
+ `${currentNodeId}${handleType ? (handleId ? `-${handleType}-${handleId}` : `-${handleType}`) : ''}`,
61
+ ),
62
+ areConnectionMapsEqual,
63
+ subSlot(slot, 'connections'),
64
+ );
65
+
66
+ useEffect(
67
+ () => {
68
+ // @todo discuss if onConnect/onDisconnect should be called when the component mounts/unmounts
69
+ if (prevConnections.current && prevConnections.current !== connections) {
70
+ const _connections = connections ?? new Map();
71
+ handleConnectionChange(prevConnections.current, _connections, onDisconnect);
72
+ handleConnectionChange(_connections, prevConnections.current, onConnect);
73
+ }
74
+
75
+ prevConnections.current = connections ?? new Map();
76
+ },
77
+ [connections, onConnect, onDisconnect],
78
+ subSlot(slot, 'connection-change'),
79
+ );
80
+
81
+ return useMemo(
82
+ () => Array.from(connections?.values() ?? []),
83
+ [connections],
84
+ subSlot(slot, 'connection-list'),
85
+ );
86
+ }
@@ -0,0 +1,33 @@
1
+ import { shallow } from '@octanejs/zustand/shallow';
2
+ import { resolveHookSlot } from './slot';
3
+
4
+ import { useStore } from '../hooks/useStore';
5
+ import type { Node, ReactFlowState } from '../types';
6
+
7
+ const nodesSelector = (state: ReactFlowState) => state.nodes;
8
+
9
+ /**
10
+ * This hook returns an array of the current nodes. Components that use this hook
11
+ * will re-render **whenever any node changes**, including when a node is selected
12
+ * or moved.
13
+ *
14
+ * @public
15
+ * @returns An array of all nodes currently in the flow.
16
+ *
17
+ * @example
18
+ * ```jsx
19
+ *import { useNodes } from '@xyflow/react';
20
+ *
21
+ *export default function() {
22
+ * const nodes = useNodes();
23
+ *
24
+ * return <div>There are currently {nodes.length} nodes!</div>;
25
+ *}
26
+ *```
27
+ */
28
+ export function useNodes<NodeType extends Node = Node>(...rest: [slot?: symbol]): NodeType[] {
29
+ const slot = resolveHookSlot(rest);
30
+ const nodes = useStore(nodesSelector, shallow, slot) as NodeType[];
31
+
32
+ return nodes;
33
+ }
@@ -0,0 +1,66 @@
1
+ import { useCallback } from 'octane';
2
+ import { resolveHookSlot } from './slot';
3
+ import { DistributivePick, shallowNodeData } from '@xyflow/system';
4
+
5
+ import { useStore } from '../hooks/useStore';
6
+ import type { Node } from '../types';
7
+
8
+ /**
9
+ * This hook lets you subscribe to changes of a specific nodes `data` object.
10
+ *
11
+ * @public
12
+ * @returns An object (or array of object) with `id`, `type`, `data` representing each node.
13
+ *
14
+ * @example
15
+ *```jsx
16
+ *import { useNodesData } from '@xyflow/react';
17
+ *
18
+ *export default function() {
19
+ * const nodeData = useNodesData('nodeId-1');
20
+ * const nodesData = useNodesData(['nodeId-1', 'nodeId-2']);
21
+ *
22
+ * return null;
23
+ *}
24
+ *```
25
+ */
26
+ export function useNodesData<NodeType extends Node = Node>(
27
+ /** The id of the node to get the data from. */
28
+ nodeId: string,
29
+ ...rest: [slot?: symbol]
30
+ ): DistributivePick<NodeType, 'id' | 'type' | 'data'> | null;
31
+ export function useNodesData<NodeType extends Node = Node>(
32
+ /** The ids of the nodes to get the data from. */
33
+ nodeIds: string[],
34
+ ...rest: [slot?: symbol]
35
+ ): DistributivePick<NodeType, 'id' | 'type' | 'data'>[];
36
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
37
+ export function useNodesData(nodeIds: any, ...rest: [slot?: symbol]): any {
38
+ const slot = resolveHookSlot(rest);
39
+ const nodesData = useStore(
40
+ useCallback(
41
+ function selectNodesData(s) {
42
+ const data = [];
43
+ const isArrayOfIds = Array.isArray(nodeIds);
44
+ const _nodeIds = isArrayOfIds ? nodeIds : [nodeIds];
45
+
46
+ for (const nodeId of _nodeIds) {
47
+ const node = s.nodeLookup.get(nodeId);
48
+ if (node) {
49
+ data.push({
50
+ id: node.id,
51
+ type: node.type,
52
+ data: node.data,
53
+ });
54
+ }
55
+ }
56
+
57
+ return isArrayOfIds ? data : (data[0] ?? null);
58
+ },
59
+ [nodeIds],
60
+ ),
61
+ shallowNodeData,
62
+ slot,
63
+ );
64
+
65
+ return nodesData;
66
+ }
@@ -0,0 +1,138 @@
1
+ import { useState, useCallback } from 'octane';
2
+ import type { Dispatch, SetStateAction } from '../react-shim.js';
3
+
4
+ import { applyNodeChanges, applyEdgeChanges } from '../utils/changes';
5
+ import { resolveHookSlot, subSlot } from './slot';
6
+ import type { Node, Edge, OnNodesChange, OnEdgesChange } from '../types';
7
+
8
+ /**
9
+ * This hook makes it easy to prototype a controlled flow where you manage the
10
+ * state of nodes and edges outside the `ReactFlowInstance`. You can think of it
11
+ * like React's `useState` hook with an additional helper callback.
12
+ *
13
+ * @public
14
+ * @returns
15
+ * - `nodes`: The current array of nodes. You might pass this directly to the `nodes` prop of your
16
+ * `<ReactFlow />` component, or you may want to manipulate it first to perform some layouting,
17
+ * for example.
18
+ * - `setNodes`: A function that you can use to update the nodes. You can pass it a new array of
19
+ * nodes or a callback that receives the current array of nodes and returns a new array of nodes.
20
+ * This is the same as the second element of the tuple returned by React's `useState` hook.
21
+ * - `onNodesChange`: A handy callback that can take an array of `NodeChanges` and update the nodes
22
+ * state accordingly. You'll typically pass this directly to the `onNodesChange` prop of your
23
+ * `<ReactFlow />` component.
24
+ * @example
25
+ *
26
+ *```tsx
27
+ *import { ReactFlow, useNodesState, useEdgesState } from '@xyflow/react';
28
+ *
29
+ *const initialNodes = [];
30
+ *const initialEdges = [];
31
+ *
32
+ *export default function () {
33
+ * const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
34
+ * const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
35
+ *
36
+ * return (
37
+ * <ReactFlow
38
+ * nodes={nodes}
39
+ * edges={edges}
40
+ * onNodesChange={onNodesChange}
41
+ * onEdgesChange={onEdgesChange}
42
+ * />
43
+ * );
44
+ *}
45
+ *```
46
+ *
47
+ * @remarks This hook was created to make prototyping easier and our documentation
48
+ * examples clearer. Although it is OK to use this hook in production, in
49
+ * practice you may want to use a more sophisticated state management solution
50
+ * like Zustand {@link https://reactflow.dev/docs/guides/state-management/} instead.
51
+ *
52
+ */
53
+ export function useNodesState<NodeType extends Node>(
54
+ initialNodes: NodeType[],
55
+ ...rest: [slot?: symbol]
56
+ ): [
57
+ //
58
+ nodes: NodeType[],
59
+ setNodes: Dispatch<SetStateAction<NodeType[]>>,
60
+ onNodesChange: OnNodesChange<NodeType>,
61
+ ] {
62
+ const slot = resolveHookSlot(rest);
63
+ const [nodes, setNodes] = useState(initialNodes, subSlot(slot, 'state'));
64
+ const onNodesChange: OnNodesChange<NodeType> = useCallback(
65
+ (changes) => setNodes((nds) => applyNodeChanges(changes, nds)),
66
+ [],
67
+ subSlot(slot, 'changes'),
68
+ );
69
+
70
+ return [nodes, setNodes, onNodesChange];
71
+ }
72
+
73
+ /**
74
+ * This hook makes it easy to prototype a controlled flow where you manage the
75
+ * state of nodes and edges outside the `ReactFlowInstance`. You can think of it
76
+ * like React's `useState` hook with an additional helper callback.
77
+ *
78
+ * @public
79
+ * @returns
80
+ * - `edges`: The current array of edges. You might pass this directly to the `edges` prop of your
81
+ * `<ReactFlow />` component, or you may want to manipulate it first to perform some layouting,
82
+ * for example.
83
+ *
84
+ * - `setEdges`: A function that you can use to update the edges. You can pass it a new array of
85
+ * edges or a callback that receives the current array of edges and returns a new array of edges.
86
+ * This is the same as the second element of the tuple returned by React's `useState` hook.
87
+ *
88
+ * - `onEdgesChange`: A handy callback that can take an array of `EdgeChanges` and update the edges
89
+ * state accordingly. You'll typically pass this directly to the `onEdgesChange` prop of your
90
+ * `<ReactFlow />` component.
91
+ * @example
92
+ *
93
+ *```tsx
94
+ *import { ReactFlow, useNodesState, useEdgesState } from '@xyflow/react';
95
+ *
96
+ *const initialNodes = [];
97
+ *const initialEdges = [];
98
+ *
99
+ *export default function () {
100
+ * const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
101
+ * const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
102
+ *
103
+ * return (
104
+ * <ReactFlow
105
+ * nodes={nodes}
106
+ * edges={edges}
107
+ * onNodesChange={onNodesChange}
108
+ * onEdgesChange={onEdgesChange}
109
+ * />
110
+ * );
111
+ *}
112
+ *```
113
+ *
114
+ * @remarks This hook was created to make prototyping easier and our documentation
115
+ * examples clearer. Although it is OK to use this hook in production, in
116
+ * practice you may want to use a more sophisticated state management solution
117
+ * like Zustand {@link https://reactflow.dev/docs/guides/state-management/} instead.
118
+ *
119
+ */
120
+ export function useEdgesState<EdgeType extends Edge = Edge>(
121
+ initialEdges: EdgeType[],
122
+ ...rest: [slot?: symbol]
123
+ ): [
124
+ //
125
+ edges: EdgeType[],
126
+ setEdges: Dispatch<SetStateAction<EdgeType[]>>,
127
+ onEdgesChange: OnEdgesChange<EdgeType>,
128
+ ] {
129
+ const slot = resolveHookSlot(rest);
130
+ const [edges, setEdges] = useState(initialEdges, subSlot(slot, 'state'));
131
+ const onEdgesChange: OnEdgesChange<EdgeType> = useCallback(
132
+ (changes) => setEdges((eds) => applyEdgeChanges(changes, eds)),
133
+ [],
134
+ subSlot(slot, 'changes'),
135
+ );
136
+
137
+ return [edges, setEdges, onEdgesChange];
138
+ }
@@ -0,0 +1,74 @@
1
+ import { nodeHasDimensions } from '@xyflow/system';
2
+ import { resolveHookSlot, withoutSlot } from './slot';
3
+
4
+ import { useStore } from './useStore';
5
+ import type { ReactFlowState } from '../types';
6
+
7
+ export type UseNodesInitializedOptions = {
8
+ /** @default false */
9
+ includeHiddenNodes?: boolean;
10
+ };
11
+
12
+ const selector = (options: UseNodesInitializedOptions) => (s: ReactFlowState) => {
13
+ if (!options.includeHiddenNodes) {
14
+ return s.nodesInitialized;
15
+ }
16
+
17
+ if (s.nodeLookup.size === 0) {
18
+ return false;
19
+ }
20
+
21
+ for (const [, { internals }] of s.nodeLookup) {
22
+ if (internals.handleBounds === undefined || !nodeHasDimensions(internals.userNode)) {
23
+ return false;
24
+ }
25
+ }
26
+
27
+ return true;
28
+ };
29
+
30
+ /**
31
+ * This hook tells you whether all the nodes in a flow have been measured and given
32
+ *a width and height. When you add a node to the flow, this hook will return
33
+ *`false` and then `true` again once the node has been measured.
34
+ *
35
+ * @public
36
+ * @returns Whether or not the nodes have been initialized by the `<ReactFlow />` component and
37
+ * given a width and height.
38
+ *
39
+ * @example
40
+ * ```jsx
41
+ *import { useReactFlow, useNodesInitialized } from '@xyflow/react';
42
+ *import { useEffect, useState } from 'octane';
43
+ *
44
+ *const options = {
45
+ * includeHiddenNodes: false,
46
+ *};
47
+ *
48
+ *export default function useLayout() {
49
+ * const { getNodes } = useReactFlow(slot);
50
+ * const nodesInitialized = useNodesInitialized(options);
51
+ * const [layoutedNodes, setLayoutedNodes] = useState(getNodes());
52
+ *
53
+ * useEffect(() => {
54
+ * if (nodesInitialized) {
55
+ * setLayoutedNodes(yourLayoutingFunction(getNodes()));
56
+ * }
57
+ * }, [nodesInitialized]);
58
+ *
59
+ * return layoutedNodes;
60
+ *}
61
+ *```
62
+ */
63
+ export function useNodesInitialized(
64
+ options: UseNodesInitializedOptions | symbol = {
65
+ includeHiddenNodes: false,
66
+ },
67
+ ...rest: [slot?: symbol]
68
+ ): boolean {
69
+ let slot = resolveHookSlot(rest);
70
+ const resolved = withoutSlot(options) ?? { includeHiddenNodes: false };
71
+ const initialized = useStore(selector(resolved), undefined, slot);
72
+
73
+ return initialized;
74
+ }
@@ -0,0 +1,46 @@
1
+ import { useEffect, useState } from 'octane';
2
+ import { resolveHookSlot, subSlot } from './slot';
3
+ import type { EdgeChange } from '@xyflow/system';
4
+
5
+ import { useStoreApi } from './useStore';
6
+ import type { Edge, Node } from '../types';
7
+
8
+ /**
9
+ * Registers a middleware function to transform edge changes.
10
+ *
11
+ * @public
12
+ * @param fn - Middleware function. Should be memoized with useCallback to avoid re-registration.
13
+ */
14
+ export function experimental_useOnEdgesChangeMiddleware<EdgeType extends Edge = Edge>(
15
+ fn: (changes: EdgeChange<EdgeType>[]) => EdgeChange<EdgeType>[],
16
+ ...rest: [slot?: symbol]
17
+ ) {
18
+ const slot = resolveHookSlot(rest);
19
+ const store = useStoreApi<Node, EdgeType>(subSlot(slot, 'store'));
20
+ const [symbol] = useState(
21
+ function createSymbol() {
22
+ return Symbol();
23
+ },
24
+ subSlot(slot, 'symbol'),
25
+ );
26
+
27
+ useEffect(
28
+ function registerMiddleware() {
29
+ const { onEdgesChangeMiddlewareMap } = store.getState();
30
+ onEdgesChangeMiddlewareMap.set(symbol, fn);
31
+ },
32
+ [fn],
33
+ subSlot(slot, 'register'),
34
+ );
35
+
36
+ useEffect(
37
+ function unregisterMiddleware() {
38
+ const { onEdgesChangeMiddlewareMap } = store.getState();
39
+ return function cleanup() {
40
+ onEdgesChangeMiddlewareMap.delete(symbol);
41
+ };
42
+ },
43
+ [],
44
+ subSlot(slot, 'unregister'),
45
+ );
46
+ }
@@ -0,0 +1,27 @@
1
+ import { useEffect, useRef } from 'octane';
2
+
3
+ import { useReactFlow } from './useReactFlow';
4
+ import { resolveHookSlot } from './slot';
5
+ import type { OnInit, Node, Edge } from '../types';
6
+
7
+ export function useOnInitHandler<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
8
+ onInit: OnInit<NodeType, EdgeType> | undefined,
9
+ ...rest: [slot?: symbol]
10
+ ) {
11
+ const slot = resolveHookSlot(rest);
12
+ const rfInstance = useReactFlow<NodeType, EdgeType>(slot);
13
+ const isInitialized = useRef<boolean>(false, slot);
14
+
15
+ useEffect(
16
+ function onInitEffect() {
17
+ if (!isInitialized.current && rfInstance.viewportInitialized && onInit) {
18
+ setTimeout(function invokeOnInit() {
19
+ onInit(rfInstance);
20
+ }, 1);
21
+ isInitialized.current = true;
22
+ }
23
+ },
24
+ [onInit, rfInstance.viewportInitialized],
25
+ slot,
26
+ );
27
+ }
@@ -0,0 +1,46 @@
1
+ import { useEffect, useState } from 'octane';
2
+ import { resolveHookSlot, subSlot } from './slot';
3
+ import type { NodeChange } from '@xyflow/system';
4
+
5
+ import { useStoreApi } from './useStore';
6
+ import type { Edge, Node } from '../types';
7
+
8
+ /**
9
+ * Registers a middleware function to transform node changes.
10
+ *
11
+ * @public
12
+ * @param fn - Middleware function. Should be memoized with useCallback to avoid re-registration.
13
+ */
14
+ export function experimental_useOnNodesChangeMiddleware<NodeType extends Node = Node>(
15
+ fn: (changes: NodeChange<NodeType>[]) => NodeChange<NodeType>[],
16
+ ...rest: [slot?: symbol]
17
+ ) {
18
+ const slot = resolveHookSlot(rest);
19
+ const store = useStoreApi<NodeType, Edge>(subSlot(slot, 'store'));
20
+ const [symbol] = useState(
21
+ function createSymbol() {
22
+ return Symbol();
23
+ },
24
+ subSlot(slot, 'symbol'),
25
+ );
26
+
27
+ useEffect(
28
+ function registerMiddleware() {
29
+ const { onNodesChangeMiddlewareMap } = store.getState();
30
+ onNodesChangeMiddlewareMap.set(symbol, fn);
31
+ },
32
+ [fn],
33
+ subSlot(slot, 'register'),
34
+ );
35
+
36
+ useEffect(
37
+ function unregisterMiddleware() {
38
+ const { onNodesChangeMiddlewareMap } = store.getState();
39
+ return function cleanup() {
40
+ onNodesChangeMiddlewareMap.delete(symbol);
41
+ };
42
+ },
43
+ [],
44
+ subSlot(slot, 'unregister'),
45
+ );
46
+ }
@@ -0,0 +1,78 @@
1
+ import { useEffect } from 'octane';
2
+ import { resolveHookSlot } from './slot';
3
+
4
+ import { useStoreApi } from './useStore';
5
+ import type { OnSelectionChangeFunc, Node, Edge } from '../types';
6
+
7
+ export type UseOnSelectionChangeOptions<
8
+ NodeType extends Node = Node,
9
+ EdgeType extends Edge = Edge,
10
+ > = {
11
+ /** The handler to register. */
12
+ onChange: OnSelectionChangeFunc<NodeType, EdgeType>;
13
+ };
14
+
15
+ /**
16
+ * This hook lets you listen for changes to both node and edge selection. As the
17
+ *name implies, the callback you provide will be called whenever the selection of
18
+ *_either_ nodes or edges changes.
19
+ *
20
+ * @public
21
+ * @example
22
+ * ```jsx
23
+ *import { useState } from 'octane';
24
+ *import { ReactFlow, useOnSelectionChange } from '@xyflow/react';
25
+ *
26
+ *function SelectionDisplay() {
27
+ * const [selectedNodes, setSelectedNodes] = useState([]);
28
+ * const [selectedEdges, setSelectedEdges] = useState([]);
29
+ *
30
+ * // the passed handler has to be memoized, otherwise the hook will not work correctly
31
+ * const onChange = useCallback(({ nodes, edges }) => {
32
+ * setSelectedNodes(nodes.map((node) => node.id));
33
+ * setSelectedEdges(edges.map((edge) => edge.id));
34
+ * }, []);
35
+ *
36
+ * useOnSelectionChange({
37
+ * onChange,
38
+ * });
39
+ *
40
+ * return (
41
+ * <div>
42
+ * <p>Selected nodes: {selectedNodes.join(', ')}</p>
43
+ * <p>Selected edges: {selectedEdges.join(', ')}</p>
44
+ * </div>
45
+ * );
46
+ *}
47
+ *```
48
+ *
49
+ * @remarks You need to memoize the passed `onChange` handler, otherwise the hook will not work correctly.
50
+ */
51
+ export function useOnSelectionChange<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
52
+ { onChange }: UseOnSelectionChangeOptions<NodeType, EdgeType>,
53
+ ...rest: [slot?: symbol]
54
+ ) {
55
+ const slot = resolveHookSlot(rest);
56
+ const store = useStoreApi<NodeType, EdgeType>(slot);
57
+
58
+ useEffect(
59
+ function registerSelectionChange() {
60
+ const nextOnSelectionChangeHandlers = [
61
+ ...store.getState().onSelectionChangeHandlers,
62
+ onChange,
63
+ ];
64
+ store.setState({ onSelectionChangeHandlers: nextOnSelectionChangeHandlers });
65
+
66
+ return function unregisterSelectionChange() {
67
+ const nextHandlers = store
68
+ .getState()
69
+ .onSelectionChangeHandlers.filter(function isNotChange(fn) {
70
+ return fn !== onChange;
71
+ });
72
+ store.setState({ onSelectionChangeHandlers: nextHandlers });
73
+ };
74
+ },
75
+ [onChange],
76
+ slot,
77
+ );
78
+ }