Greasy Fork is available in English.

@xyflow᜵react

A UMD build of @xyflow/react

Tento skript by nemal byť nainštalovaný priamo. Je to knižnica pre ďalšie skripty, ktorú by mali používať cez meta príkaz // @require https://update.greasyfork.org/scripts/520295/1500131/%40xyflow%E1%9C%B5react.js

  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react/jsx-runtime'), require('classcat'), require('@xyflow/system'), require('react'), require('zustand/traditional'), require('zustand/shallow'), require('react-dom')) :
  3. typeof define === 'function' && define.amd ? define(['exports', 'react/jsx-runtime', 'classcat', '@xyflow/system', 'react', 'zustand/traditional', 'zustand/shallow', 'react-dom'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.XYFlowReact = {}, global.ReactJSXRuntime, global.classcat, global.XYFlowSystem, global.React, global.ZustandTraditional, global.ZustandShallow, global.ReactDOM));
  5. })(this, (function (exports, jsxRuntime, cc, system, react, traditional, shallow, reactDom) { 'use strict';
  6. var StoreContext = react.createContext(null);
  7. var Provider$1 = StoreContext.Provider;
  8. var zustandErrorMessage = system.errorMessages["error001"]();
  9. function useStore(selector2, equalityFn) {
  10. const store = react.useContext(StoreContext);
  11. if (store === null) {
  12. throw new Error(zustandErrorMessage);
  13. }
  14. return traditional.useStoreWithEqualityFn(store, selector2, equalityFn);
  15. }
  16. function useStoreApi() {
  17. const store = react.useContext(StoreContext);
  18. if (store === null) {
  19. throw new Error(zustandErrorMessage);
  20. }
  21. return react.useMemo(() => ({
  22. getState: store.getState,
  23. setState: store.setState,
  24. subscribe: store.subscribe
  25. }), [store]);
  26. }
  27. var style = { display: "none" };
  28. var ariaLiveStyle = {
  29. position: "absolute",
  30. width: 1,
  31. height: 1,
  32. margin: -1,
  33. border: 0,
  34. padding: 0,
  35. overflow: "hidden",
  36. clip: "rect(0px, 0px, 0px, 0px)",
  37. clipPath: "inset(100%)"
  38. };
  39. var ARIA_NODE_DESC_KEY = "react-flow__node-desc";
  40. var ARIA_EDGE_DESC_KEY = "react-flow__edge-desc";
  41. var ARIA_LIVE_MESSAGE = "react-flow__aria-live";
  42. var selector$o = (s) => s.ariaLiveMessage;
  43. function AriaLiveMessage({ rfId }) {
  44. const ariaLiveMessage = useStore(selector$o);
  45. return jsxRuntime.jsx("div", { id: `${ARIA_LIVE_MESSAGE}-${rfId}`, "aria-live": "assertive", "aria-atomic": "true", style: ariaLiveStyle, children: ariaLiveMessage });
  46. }
  47. function A11yDescriptions({ rfId, disableKeyboardA11y }) {
  48. return jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsxs("div", { id: `${ARIA_NODE_DESC_KEY}-${rfId}`, style, children: ["Press enter or space to select a node.", !disableKeyboardA11y && "You can then use the arrow keys to move the node around.", " Press delete to remove it and escape to cancel.", " "] }), jsxRuntime.jsx("div", { id: `${ARIA_EDGE_DESC_KEY}-${rfId}`, style, children: "Press enter or space to select an edge. You can then press delete to remove it or escape to cancel." }), !disableKeyboardA11y && jsxRuntime.jsx(AriaLiveMessage, { rfId })] });
  49. }
  50. var selector$n = (s) => s.userSelectionActive ? "none" : "all";
  51. var Panel = react.forwardRef(({ position = "top-left", children, className, style: style2, ...rest }, ref) => {
  52. const pointerEvents = useStore(selector$n);
  53. const positionClasses = `${position}`.split("-");
  54. return jsxRuntime.jsx("div", { className: cc(["react-flow__panel", className, ...positionClasses]), style: { ...style2, pointerEvents }, ref, ...rest, children });
  55. });
  56. function Attribution({ proOptions, position = "bottom-right" }) {
  57. if (proOptions?.hideAttribution) {
  58. return null;
  59. }
  60. return jsxRuntime.jsx(Panel, { position, className: "react-flow__attribution", "data-message": "Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev", children: jsxRuntime.jsx("a", { href: "https://reactflow.dev", target: "_blank", rel: "noopener noreferrer", "aria-label": "React Flow attribution", children: "React Flow" }) });
  61. }
  62. var selector$m = (s) => {
  63. const selectedNodes = [];
  64. const selectedEdges = [];
  65. for (const [, node] of s.nodeLookup) {
  66. if (node.selected) {
  67. selectedNodes.push(node.internals.userNode);
  68. }
  69. }
  70. for (const [, edge] of s.edgeLookup) {
  71. if (edge.selected) {
  72. selectedEdges.push(edge);
  73. }
  74. }
  75. return { selectedNodes, selectedEdges };
  76. };
  77. var selectId = (obj) => obj.id;
  78. function areEqual(a, b) {
  79. return shallow.shallow(a.selectedNodes.map(selectId), b.selectedNodes.map(selectId)) && shallow.shallow(a.selectedEdges.map(selectId), b.selectedEdges.map(selectId));
  80. }
  81. function SelectionListenerInner({ onSelectionChange }) {
  82. const store = useStoreApi();
  83. const { selectedNodes, selectedEdges } = useStore(selector$m, areEqual);
  84. react.useEffect(() => {
  85. const params = { nodes: selectedNodes, edges: selectedEdges };
  86. onSelectionChange?.(params);
  87. store.getState().onSelectionChangeHandlers.forEach((fn) => fn(params));
  88. }, [selectedNodes, selectedEdges, onSelectionChange]);
  89. return null;
  90. }
  91. var changeSelector = (s) => !!s.onSelectionChangeHandlers;
  92. function SelectionListener({ onSelectionChange }) {
  93. const storeHasSelectionChangeHandlers = useStore(changeSelector);
  94. if (onSelectionChange || storeHasSelectionChangeHandlers) {
  95. return jsxRuntime.jsx(SelectionListenerInner, { onSelectionChange });
  96. }
  97. return null;
  98. }
  99. var defaultNodeOrigin = [0, 0];
  100. var defaultViewport = { x: 0, y: 0, zoom: 1 };
  101. var reactFlowFieldsToTrack = [
  102. "nodes",
  103. "edges",
  104. "defaultNodes",
  105. "defaultEdges",
  106. "onConnect",
  107. "onConnectStart",
  108. "onConnectEnd",
  109. "onClickConnectStart",
  110. "onClickConnectEnd",
  111. "nodesDraggable",
  112. "nodesConnectable",
  113. "nodesFocusable",
  114. "edgesFocusable",
  115. "edgesReconnectable",
  116. "elevateNodesOnSelect",
  117. "elevateEdgesOnSelect",
  118. "minZoom",
  119. "maxZoom",
  120. "nodeExtent",
  121. "onNodesChange",
  122. "onEdgesChange",
  123. "elementsSelectable",
  124. "connectionMode",
  125. "snapGrid",
  126. "snapToGrid",
  127. "translateExtent",
  128. "connectOnClick",
  129. "defaultEdgeOptions",
  130. "fitView",
  131. "fitViewOptions",
  132. "onNodesDelete",
  133. "onEdgesDelete",
  134. "onDelete",
  135. "onNodeDrag",
  136. "onNodeDragStart",
  137. "onNodeDragStop",
  138. "onSelectionDrag",
  139. "onSelectionDragStart",
  140. "onSelectionDragStop",
  141. "onMoveStart",
  142. "onMove",
  143. "onMoveEnd",
  144. "noPanClassName",
  145. "nodeOrigin",
  146. "autoPanOnConnect",
  147. "autoPanOnNodeDrag",
  148. "onError",
  149. "connectionRadius",
  150. "isValidConnection",
  151. "selectNodesOnDrag",
  152. "nodeDragThreshold",
  153. "onBeforeDelete",
  154. "debug",
  155. "autoPanSpeed",
  156. "paneClickDistance"
  157. ];
  158. var fieldsToTrack = [...reactFlowFieldsToTrack, "rfId"];
  159. var selector$l = (s) => ({
  160. setNodes: s.setNodes,
  161. setEdges: s.setEdges,
  162. setMinZoom: s.setMinZoom,
  163. setMaxZoom: s.setMaxZoom,
  164. setTranslateExtent: s.setTranslateExtent,
  165. setNodeExtent: s.setNodeExtent,
  166. reset: s.reset,
  167. setDefaultNodesAndEdges: s.setDefaultNodesAndEdges,
  168. setPaneClickDistance: s.setPaneClickDistance
  169. });
  170. var initPrevValues = {
  171. translateExtent: system.infiniteExtent,
  172. nodeOrigin: defaultNodeOrigin,
  173. minZoom: 0.5,
  174. maxZoom: 2,
  175. elementsSelectable: true,
  176. noPanClassName: "nopan",
  177. rfId: "1",
  178. paneClickDistance: 0
  179. };
  180. function StoreUpdater(props) {
  181. const { setNodes, setEdges, setMinZoom, setMaxZoom, setTranslateExtent, setNodeExtent, reset, setDefaultNodesAndEdges, setPaneClickDistance } = useStore(selector$l, shallow.shallow);
  182. const store = useStoreApi();
  183. react.useEffect(() => {
  184. setDefaultNodesAndEdges(props.defaultNodes, props.defaultEdges);
  185. return () => {
  186. previousFields.current = initPrevValues;
  187. reset();
  188. };
  189. }, []);
  190. const previousFields = react.useRef(initPrevValues);
  191. react.useEffect(
  192. () => {
  193. for (const fieldName of fieldsToTrack) {
  194. const fieldValue = props[fieldName];
  195. const previousFieldValue = previousFields.current[fieldName];
  196. if (fieldValue === previousFieldValue)
  197. continue;
  198. if (typeof props[fieldName] === "undefined")
  199. continue;
  200. if (fieldName === "nodes")
  201. setNodes(fieldValue);
  202. else if (fieldName === "edges")
  203. setEdges(fieldValue);
  204. else if (fieldName === "minZoom")
  205. setMinZoom(fieldValue);
  206. else if (fieldName === "maxZoom")
  207. setMaxZoom(fieldValue);
  208. else if (fieldName === "translateExtent")
  209. setTranslateExtent(fieldValue);
  210. else if (fieldName === "nodeExtent")
  211. setNodeExtent(fieldValue);
  212. else if (fieldName === "paneClickDistance")
  213. setPaneClickDistance(fieldValue);
  214. else if (fieldName === "fitView")
  215. store.setState({ fitViewOnInit: fieldValue });
  216. else if (fieldName === "fitViewOptions")
  217. store.setState({ fitViewOnInitOptions: fieldValue });
  218. else
  219. store.setState({ [fieldName]: fieldValue });
  220. }
  221. previousFields.current = props;
  222. },
  223. fieldsToTrack.map((fieldName) => props[fieldName])
  224. );
  225. return null;
  226. }
  227. function getMediaQuery() {
  228. if (typeof window === "undefined" || !window.matchMedia) {
  229. return null;
  230. }
  231. return window.matchMedia("(prefers-color-scheme: dark)");
  232. }
  233. function useColorModeClass(colorMode) {
  234. const [colorModeClass, setColorModeClass] = react.useState(colorMode === "system" ? null : colorMode);
  235. react.useEffect(() => {
  236. if (colorMode !== "system") {
  237. setColorModeClass(colorMode);
  238. return;
  239. }
  240. const mediaQuery = getMediaQuery();
  241. const updateColorModeClass = () => setColorModeClass(mediaQuery?.matches ? "dark" : "light");
  242. updateColorModeClass();
  243. mediaQuery?.addEventListener("change", updateColorModeClass);
  244. return () => {
  245. mediaQuery?.removeEventListener("change", updateColorModeClass);
  246. };
  247. }, [colorMode]);
  248. return colorModeClass !== null ? colorModeClass : getMediaQuery()?.matches ? "dark" : "light";
  249. }
  250. var defaultDoc = typeof document !== "undefined" ? document : null;
  251. function useKeyPress(keyCode = null, options = { target: defaultDoc, actInsideInputWithModifier: true }) {
  252. const [keyPressed, setKeyPressed] = react.useState(false);
  253. const modifierPressed = react.useRef(false);
  254. const pressedKeys = react.useRef( new Set([]));
  255. const [keyCodes, keysToWatch] = react.useMemo(() => {
  256. if (keyCode !== null) {
  257. const keyCodeArr = Array.isArray(keyCode) ? keyCode : [keyCode];
  258. const keys = keyCodeArr.filter((kc) => typeof kc === "string").map((kc) => kc.replace("+", "\n").replace("\n\n", "\n+").split("\n"));
  259. const keysFlat = keys.reduce((res, item) => res.concat(...item), []);
  260. return [keys, keysFlat];
  261. }
  262. return [[], []];
  263. }, [keyCode]);
  264. react.useEffect(() => {
  265. const target = options?.target || defaultDoc;
  266. if (keyCode !== null) {
  267. const downHandler = (event) => {
  268. modifierPressed.current = event.ctrlKey || event.metaKey || event.shiftKey;
  269. const preventAction = (!modifierPressed.current || modifierPressed.current && !options.actInsideInputWithModifier) && system.isInputDOMNode(event);
  270. if (preventAction) {
  271. return false;
  272. }
  273. const keyOrCode = useKeyOrCode(event.code, keysToWatch);
  274. pressedKeys.current.add(event[keyOrCode]);
  275. if (isMatchingKey(keyCodes, pressedKeys.current, false)) {
  276. event.preventDefault();
  277. setKeyPressed(true);
  278. }
  279. };
  280. const upHandler = (event) => {
  281. const preventAction = (!modifierPressed.current || modifierPressed.current && !options.actInsideInputWithModifier) && system.isInputDOMNode(event);
  282. if (preventAction) {
  283. return false;
  284. }
  285. const keyOrCode = useKeyOrCode(event.code, keysToWatch);
  286. if (isMatchingKey(keyCodes, pressedKeys.current, true)) {
  287. setKeyPressed(false);
  288. pressedKeys.current.clear();
  289. } else {
  290. pressedKeys.current.delete(event[keyOrCode]);
  291. }
  292. if (event.key === "Meta") {
  293. pressedKeys.current.clear();
  294. }
  295. modifierPressed.current = false;
  296. };
  297. const resetHandler = () => {
  298. pressedKeys.current.clear();
  299. setKeyPressed(false);
  300. };
  301. target?.addEventListener("keydown", downHandler);
  302. target?.addEventListener("keyup", upHandler);
  303. window.addEventListener("blur", resetHandler);
  304. window.addEventListener("contextmenu", resetHandler);
  305. return () => {
  306. target?.removeEventListener("keydown", downHandler);
  307. target?.removeEventListener("keyup", upHandler);
  308. window.removeEventListener("blur", resetHandler);
  309. window.removeEventListener("contextmenu", resetHandler);
  310. };
  311. }
  312. }, [keyCode, setKeyPressed]);
  313. return keyPressed;
  314. }
  315. function isMatchingKey(keyCodes, pressedKeys, isUp) {
  316. return keyCodes.filter((keys) => isUp || keys.length === pressedKeys.size).some((keys) => keys.every((k) => pressedKeys.has(k)));
  317. }
  318. function useKeyOrCode(eventCode, keysToWatch) {
  319. return keysToWatch.includes(eventCode) ? "code" : "key";
  320. }
  321. var useViewportHelper = () => {
  322. const store = useStoreApi();
  323. return react.useMemo(() => {
  324. return {
  325. zoomIn: (options) => {
  326. const { panZoom } = store.getState();
  327. return panZoom ? panZoom.scaleBy(1.2, { duration: options?.duration }) : Promise.resolve(false);
  328. },
  329. zoomOut: (options) => {
  330. const { panZoom } = store.getState();
  331. return panZoom ? panZoom.scaleBy(1 / 1.2, { duration: options?.duration }) : Promise.resolve(false);
  332. },
  333. zoomTo: (zoomLevel, options) => {
  334. const { panZoom } = store.getState();
  335. return panZoom ? panZoom.scaleTo(zoomLevel, { duration: options?.duration }) : Promise.resolve(false);
  336. },
  337. getZoom: () => store.getState().transform[2],
  338. setViewport: async (viewport, options) => {
  339. const { transform: [tX, tY, tZoom], panZoom } = store.getState();
  340. if (!panZoom) {
  341. return Promise.resolve(false);
  342. }
  343. await panZoom.setViewport({
  344. x: viewport.x ?? tX,
  345. y: viewport.y ?? tY,
  346. zoom: viewport.zoom ?? tZoom
  347. }, { duration: options?.duration });
  348. return Promise.resolve(true);
  349. },
  350. getViewport: () => {
  351. const [x, y, zoom] = store.getState().transform;
  352. return { x, y, zoom };
  353. },
  354. fitView: (options) => {
  355. const { nodeLookup, minZoom, maxZoom, panZoom, domNode } = store.getState();
  356. if (!panZoom || !domNode) {
  357. return Promise.resolve(false);
  358. }
  359. const fitViewNodes = system.getFitViewNodes(nodeLookup, options);
  360. const { width, height } = system.getDimensions(domNode);
  361. return system.fitView({
  362. nodes: fitViewNodes,
  363. width,
  364. height,
  365. minZoom,
  366. maxZoom,
  367. panZoom
  368. }, options);
  369. },
  370. setCenter: async (x, y, options) => {
  371. const { width, height, maxZoom, panZoom } = store.getState();
  372. const nextZoom = typeof options?.zoom !== "undefined" ? options.zoom : maxZoom;
  373. const centerX = width / 2 - x * nextZoom;
  374. const centerY = height / 2 - y * nextZoom;
  375. if (!panZoom) {
  376. return Promise.resolve(false);
  377. }
  378. await panZoom.setViewport({
  379. x: centerX,
  380. y: centerY,
  381. zoom: nextZoom
  382. }, { duration: options?.duration });
  383. return Promise.resolve(true);
  384. },
  385. fitBounds: async (bounds, options) => {
  386. const { width, height, minZoom, maxZoom, panZoom } = store.getState();
  387. const viewport = system.getViewportForBounds(bounds, width, height, minZoom, maxZoom, options?.padding ?? 0.1);
  388. if (!panZoom) {
  389. return Promise.resolve(false);
  390. }
  391. await panZoom.setViewport(viewport, { duration: options?.duration });
  392. return Promise.resolve(true);
  393. },
  394. screenToFlowPosition: (clientPosition, options = { snapToGrid: true }) => {
  395. const { transform, snapGrid, domNode } = store.getState();
  396. if (!domNode) {
  397. return clientPosition;
  398. }
  399. const { x: domX, y: domY } = domNode.getBoundingClientRect();
  400. const correctedPosition = {
  401. x: clientPosition.x - domX,
  402. y: clientPosition.y - domY
  403. };
  404. return system.pointToRendererPoint(correctedPosition, transform, options.snapToGrid, snapGrid);
  405. },
  406. flowToScreenPosition: (flowPosition) => {
  407. const { transform, domNode } = store.getState();
  408. if (!domNode) {
  409. return flowPosition;
  410. }
  411. const { x: domX, y: domY } = domNode.getBoundingClientRect();
  412. const rendererPosition = system.rendererPointToPoint(flowPosition, transform);
  413. return {
  414. x: rendererPosition.x + domX,
  415. y: rendererPosition.y + domY
  416. };
  417. }
  418. };
  419. }, []);
  420. };
  421. function applyChanges(changes, elements) {
  422. const updatedElements = [];
  423. const changesMap = new Map();
  424. const addItemChanges = [];
  425. for (const change of changes) {
  426. if (change.type === "add") {
  427. addItemChanges.push(change);
  428. continue;
  429. } else if (change.type === "remove" || change.type === "replace") {
  430. changesMap.set(change.id, [change]);
  431. } else {
  432. const elementChanges = changesMap.get(change.id);
  433. if (elementChanges) {
  434. elementChanges.push(change);
  435. } else {
  436. changesMap.set(change.id, [change]);
  437. }
  438. }
  439. }
  440. for (const element of elements) {
  441. const changes2 = changesMap.get(element.id);
  442. if (!changes2) {
  443. updatedElements.push(element);
  444. continue;
  445. }
  446. if (changes2[0].type === "remove") {
  447. continue;
  448. }
  449. if (changes2[0].type === "replace") {
  450. updatedElements.push({ ...changes2[0].item });
  451. continue;
  452. }
  453. const updatedElement = { ...element };
  454. for (const change of changes2) {
  455. applyChange(change, updatedElement);
  456. }
  457. updatedElements.push(updatedElement);
  458. }
  459. if (addItemChanges.length) {
  460. addItemChanges.forEach((change) => {
  461. if (change.index !== void 0) {
  462. updatedElements.splice(change.index, 0, { ...change.item });
  463. } else {
  464. updatedElements.push({ ...change.item });
  465. }
  466. });
  467. }
  468. return updatedElements;
  469. }
  470. function applyChange(change, element) {
  471. switch (change.type) {
  472. case "select": {
  473. element.selected = change.selected;
  474. break;
  475. }
  476. case "position": {
  477. if (typeof change.position !== "undefined") {
  478. element.position = change.position;
  479. }
  480. if (typeof change.dragging !== "undefined") {
  481. element.dragging = change.dragging;
  482. }
  483. break;
  484. }
  485. case "dimensions": {
  486. if (typeof change.dimensions !== "undefined") {
  487. element.measured ??= {};
  488. element.measured.width = change.dimensions.width;
  489. element.measured.height = change.dimensions.height;
  490. if (change.setAttributes) {
  491. element.width = change.dimensions.width;
  492. element.height = change.dimensions.height;
  493. }
  494. }
  495. if (typeof change.resizing === "boolean") {
  496. element.resizing = change.resizing;
  497. }
  498. break;
  499. }
  500. }
  501. }
  502. function applyNodeChanges(changes, nodes) {
  503. return applyChanges(changes, nodes);
  504. }
  505. function applyEdgeChanges(changes, edges) {
  506. return applyChanges(changes, edges);
  507. }
  508. function createSelectionChange(id, selected2) {
  509. return {
  510. id,
  511. type: "select",
  512. selected: selected2
  513. };
  514. }
  515. function getSelectionChanges(items, selectedIds = new Set(), mutateItem = false) {
  516. const changes = [];
  517. for (const [id, item] of items) {
  518. const willBeSelected = selectedIds.has(id);
  519. if (!(item.selected === void 0 && !willBeSelected) && item.selected !== willBeSelected) {
  520. if (mutateItem) {
  521. item.selected = willBeSelected;
  522. }
  523. changes.push(createSelectionChange(item.id, willBeSelected));
  524. }
  525. }
  526. return changes;
  527. }
  528. function getElementsDiffChanges({ items = [], lookup }) {
  529. const changes = [];
  530. const itemsLookup = new Map(items.map((item) => [item.id, item]));
  531. for (const [index2, item] of items.entries()) {
  532. const lookupItem = lookup.get(item.id);
  533. const storeItem = lookupItem?.internals?.userNode ?? lookupItem;
  534. if (storeItem !== void 0 && storeItem !== item) {
  535. changes.push({ id: item.id, item, type: "replace" });
  536. }
  537. if (storeItem === void 0) {
  538. changes.push({ item, type: "add", index: index2 });
  539. }
  540. }
  541. for (const [id] of lookup) {
  542. const nextNode = itemsLookup.get(id);
  543. if (nextNode === void 0) {
  544. changes.push({ id, type: "remove" });
  545. }
  546. }
  547. return changes;
  548. }
  549. function elementToRemoveChange(item) {
  550. return {
  551. id: item.id,
  552. type: "remove"
  553. };
  554. }
  555. var isNode = (element) => system.isNodeBase(element);
  556. var isEdge = (element) => system.isEdgeBase(element);
  557. function fixedForwardRef(render) {
  558. return react.forwardRef(render);
  559. }
  560. var useIsomorphicLayoutEffect = typeof window !== "undefined" ? react.useLayoutEffect : react.useEffect;
  561. function useQueue(runQueue) {
  562. const [serial, setSerial] = react.useState(BigInt(0));
  563. const [queue] = react.useState(() => createQueue(() => setSerial((n) => n + BigInt(1))));
  564. useIsomorphicLayoutEffect(() => {
  565. const queueItems = queue.get();
  566. if (queueItems.length) {
  567. runQueue(queueItems);
  568. queue.reset();
  569. }
  570. }, [serial]);
  571. return queue;
  572. }
  573. function createQueue(cb) {
  574. let queue = [];
  575. return {
  576. get: () => queue,
  577. reset: () => {
  578. queue = [];
  579. },
  580. push: (item) => {
  581. queue.push(item);
  582. cb();
  583. }
  584. };
  585. }
  586. var BatchContext = react.createContext(null);
  587. function BatchProvider({ children }) {
  588. const store = useStoreApi();
  589. const nodeQueueHandler = react.useCallback((queueItems) => {
  590. const { nodes = [], setNodes, hasDefaultNodes, onNodesChange, nodeLookup } = store.getState();
  591. let next = nodes;
  592. for (const payload of queueItems) {
  593. next = typeof payload === "function" ? payload(next) : payload;
  594. }
  595. if (hasDefaultNodes) {
  596. setNodes(next);
  597. } else if (onNodesChange) {
  598. onNodesChange(getElementsDiffChanges({
  599. items: next,
  600. lookup: nodeLookup
  601. }));
  602. }
  603. }, []);
  604. const nodeQueue = useQueue(nodeQueueHandler);
  605. const edgeQueueHandler = react.useCallback((queueItems) => {
  606. const { edges = [], setEdges, hasDefaultEdges, onEdgesChange, edgeLookup } = store.getState();
  607. let next = edges;
  608. for (const payload of queueItems) {
  609. next = typeof payload === "function" ? payload(next) : payload;
  610. }
  611. if (hasDefaultEdges) {
  612. setEdges(next);
  613. } else if (onEdgesChange) {
  614. onEdgesChange(getElementsDiffChanges({
  615. items: next,
  616. lookup: edgeLookup
  617. }));
  618. }
  619. }, []);
  620. const edgeQueue = useQueue(edgeQueueHandler);
  621. const value = react.useMemo(() => ({ nodeQueue, edgeQueue }), []);
  622. return jsxRuntime.jsx(BatchContext.Provider, { value, children });
  623. }
  624. function useBatchContext() {
  625. const batchContext = react.useContext(BatchContext);
  626. if (!batchContext) {
  627. throw new Error("useBatchContext must be used within a BatchProvider");
  628. }
  629. return batchContext;
  630. }
  631. var selector$k = (s) => !!s.panZoom;
  632. function useReactFlow() {
  633. const viewportHelper = useViewportHelper();
  634. const store = useStoreApi();
  635. const batchContext = useBatchContext();
  636. const viewportInitialized = useStore(selector$k);
  637. const generalHelper = react.useMemo(() => {
  638. const getInternalNode = (id) => store.getState().nodeLookup.get(id);
  639. const setNodes = (payload) => {
  640. batchContext.nodeQueue.push(payload);
  641. };
  642. const setEdges = (payload) => {
  643. batchContext.edgeQueue.push(payload);
  644. };
  645. const getNodeRect = (node) => {
  646. const { nodeLookup, nodeOrigin } = store.getState();
  647. const nodeToUse = isNode(node) ? node : nodeLookup.get(node.id);
  648. const position = nodeToUse.parentId ? system.evaluateAbsolutePosition(nodeToUse.position, nodeToUse.measured, nodeToUse.parentId, nodeLookup, nodeOrigin) : nodeToUse.position;
  649. const nodeWithPosition = {
  650. ...nodeToUse,
  651. position,
  652. width: nodeToUse.measured?.width ?? nodeToUse.width,
  653. height: nodeToUse.measured?.height ?? nodeToUse.height
  654. };
  655. return system.nodeToRect(nodeWithPosition);
  656. };
  657. const updateNode = (id, nodeUpdate, options = { replace: false }) => {
  658. setNodes((prevNodes) => prevNodes.map((node) => {
  659. if (node.id === id) {
  660. const nextNode = typeof nodeUpdate === "function" ? nodeUpdate(node) : nodeUpdate;
  661. return options.replace && isNode(nextNode) ? nextNode : { ...node, ...nextNode };
  662. }
  663. return node;
  664. }));
  665. };
  666. const updateEdge = (id, edgeUpdate, options = { replace: false }) => {
  667. setEdges((prevEdges) => prevEdges.map((edge) => {
  668. if (edge.id === id) {
  669. const nextEdge = typeof edgeUpdate === "function" ? edgeUpdate(edge) : edgeUpdate;
  670. return options.replace && isEdge(nextEdge) ? nextEdge : { ...edge, ...nextEdge };
  671. }
  672. return edge;
  673. }));
  674. };
  675. return {
  676. getNodes: () => store.getState().nodes.map((n) => ({ ...n })),
  677. getNode: (id) => getInternalNode(id)?.internals.userNode,
  678. getInternalNode,
  679. getEdges: () => {
  680. const { edges = [] } = store.getState();
  681. return edges.map((e) => ({ ...e }));
  682. },
  683. getEdge: (id) => store.getState().edgeLookup.get(id),
  684. setNodes,
  685. setEdges,
  686. addNodes: (payload) => {
  687. const newNodes = Array.isArray(payload) ? payload : [payload];
  688. batchContext.nodeQueue.push((nodes) => [...nodes, ...newNodes]);
  689. },
  690. addEdges: (payload) => {
  691. const newEdges = Array.isArray(payload) ? payload : [payload];
  692. batchContext.edgeQueue.push((edges) => [...edges, ...newEdges]);
  693. },
  694. toObject: () => {
  695. const { nodes = [], edges = [], transform } = store.getState();
  696. const [x, y, zoom] = transform;
  697. return {
  698. nodes: nodes.map((n) => ({ ...n })),
  699. edges: edges.map((e) => ({ ...e })),
  700. viewport: {
  701. x,
  702. y,
  703. zoom
  704. }
  705. };
  706. },
  707. deleteElements: async ({ nodes: nodesToRemove = [], edges: edgesToRemove = [] }) => {
  708. const { nodes, edges, onNodesDelete, onEdgesDelete, triggerNodeChanges, triggerEdgeChanges, onDelete, onBeforeDelete } = store.getState();
  709. const { nodes: matchingNodes, edges: matchingEdges } = await system.getElementsToRemove({
  710. nodesToRemove,
  711. edgesToRemove,
  712. nodes,
  713. edges,
  714. onBeforeDelete
  715. });
  716. const hasMatchingEdges = matchingEdges.length > 0;
  717. const hasMatchingNodes = matchingNodes.length > 0;
  718. if (hasMatchingEdges) {
  719. const edgeChanges = matchingEdges.map(elementToRemoveChange);
  720. onEdgesDelete?.(matchingEdges);
  721. triggerEdgeChanges(edgeChanges);
  722. }
  723. if (hasMatchingNodes) {
  724. const nodeChanges = matchingNodes.map(elementToRemoveChange);
  725. onNodesDelete?.(matchingNodes);
  726. triggerNodeChanges(nodeChanges);
  727. }
  728. if (hasMatchingNodes || hasMatchingEdges) {
  729. onDelete?.({ nodes: matchingNodes, edges: matchingEdges });
  730. }
  731. return { deletedNodes: matchingNodes, deletedEdges: matchingEdges };
  732. },
  733. getIntersectingNodes: (nodeOrRect, partially = true, nodes) => {
  734. const isRect = system.isRectObject(nodeOrRect);
  735. const nodeRect = isRect ? nodeOrRect : getNodeRect(nodeOrRect);
  736. const hasNodesOption = nodes !== void 0;
  737. if (!nodeRect) {
  738. return [];
  739. }
  740. return (nodes || store.getState().nodes).filter((n) => {
  741. const internalNode = store.getState().nodeLookup.get(n.id);
  742. if (internalNode && !isRect && (n.id === nodeOrRect.id || !internalNode.internals.positionAbsolute)) {
  743. return false;
  744. }
  745. const currNodeRect = system.nodeToRect(hasNodesOption ? n : internalNode);
  746. const overlappingArea = system.getOverlappingArea(currNodeRect, nodeRect);
  747. const partiallyVisible = partially && overlappingArea > 0;
  748. return partiallyVisible || overlappingArea >= nodeRect.width * nodeRect.height;
  749. });
  750. },
  751. isNodeIntersecting: (nodeOrRect, area, partially = true) => {
  752. const isRect = system.isRectObject(nodeOrRect);
  753. const nodeRect = isRect ? nodeOrRect : getNodeRect(nodeOrRect);
  754. if (!nodeRect) {
  755. return false;
  756. }
  757. const overlappingArea = system.getOverlappingArea(nodeRect, area);
  758. const partiallyVisible = partially && overlappingArea > 0;
  759. return partiallyVisible || overlappingArea >= nodeRect.width * nodeRect.height;
  760. },
  761. updateNode,
  762. updateNodeData: (id, dataUpdate, options = { replace: false }) => {
  763. updateNode(id, (node) => {
  764. const nextData = typeof dataUpdate === "function" ? dataUpdate(node) : dataUpdate;
  765. return options.replace ? { ...node, data: nextData } : { ...node, data: { ...node.data, ...nextData } };
  766. }, options);
  767. },
  768. updateEdge,
  769. updateEdgeData: (id, dataUpdate, options = { replace: false }) => {
  770. updateEdge(id, (edge) => {
  771. const nextData = typeof dataUpdate === "function" ? dataUpdate(edge) : dataUpdate;
  772. return options.replace ? { ...edge, data: nextData } : { ...edge, data: { ...edge.data, ...nextData } };
  773. }, options);
  774. },
  775. getNodesBounds: (nodes) => {
  776. const { nodeLookup, nodeOrigin } = store.getState();
  777. return system.getNodesBounds(nodes, { nodeLookup, nodeOrigin });
  778. },
  779. getHandleConnections: ({ type, id, nodeId }) => Array.from(store.getState().connectionLookup.get(`${nodeId}-${type}-${id ?? null}`)?.values() ?? [])
  780. };
  781. }, []);
  782. return react.useMemo(() => {
  783. return {
  784. ...generalHelper,
  785. ...viewportHelper,
  786. viewportInitialized
  787. };
  788. }, [viewportInitialized]);
  789. }
  790. var selected = (item) => item.selected;
  791. var deleteKeyOptions = { actInsideInputWithModifier: false };
  792. var win$1 = typeof window !== "undefined" ? window : void 0;
  793. function useGlobalKeyHandler({ deleteKeyCode, multiSelectionKeyCode }) {
  794. const store = useStoreApi();
  795. const { deleteElements } = useReactFlow();
  796. const deleteKeyPressed = useKeyPress(deleteKeyCode, deleteKeyOptions);
  797. const multiSelectionKeyPressed = useKeyPress(multiSelectionKeyCode, { target: win$1 });
  798. react.useEffect(() => {
  799. if (deleteKeyPressed) {
  800. const { edges, nodes } = store.getState();
  801. deleteElements({ nodes: nodes.filter(selected), edges: edges.filter(selected) });
  802. store.setState({ nodesSelectionActive: false });
  803. }
  804. }, [deleteKeyPressed]);
  805. react.useEffect(() => {
  806. store.setState({ multiSelectionActive: multiSelectionKeyPressed });
  807. }, [multiSelectionKeyPressed]);
  808. }
  809. function useResizeHandler(domNode) {
  810. const store = useStoreApi();
  811. react.useEffect(() => {
  812. const updateDimensions = () => {
  813. if (!domNode.current) {
  814. return false;
  815. }
  816. const size = system.getDimensions(domNode.current);
  817. if (size.height === 0 || size.width === 0) {
  818. store.getState().onError?.("004", system.errorMessages["error004"]());
  819. }
  820. store.setState({ width: size.width || 500, height: size.height || 500 });
  821. };
  822. if (domNode.current) {
  823. updateDimensions();
  824. window.addEventListener("resize", updateDimensions);
  825. const resizeObserver = new ResizeObserver(() => updateDimensions());
  826. resizeObserver.observe(domNode.current);
  827. return () => {
  828. window.removeEventListener("resize", updateDimensions);
  829. if (resizeObserver && domNode.current) {
  830. resizeObserver.unobserve(domNode.current);
  831. }
  832. };
  833. }
  834. }, []);
  835. }
  836. var containerStyle = {
  837. position: "absolute",
  838. width: "100%",
  839. height: "100%",
  840. top: 0,
  841. left: 0
  842. };
  843. var selector$j = (s) => ({
  844. userSelectionActive: s.userSelectionActive,
  845. lib: s.lib
  846. });
  847. function ZoomPane({ onPaneContextMenu, zoomOnScroll = true, zoomOnPinch = true, panOnScroll = false, panOnScrollSpeed = 0.5, panOnScrollMode = system.PanOnScrollMode.Free, zoomOnDoubleClick = true, panOnDrag = true, defaultViewport: defaultViewport2, translateExtent, minZoom, maxZoom, zoomActivationKeyCode, preventScrolling = true, children, noWheelClassName, noPanClassName, onViewportChange, isControlledViewport, paneClickDistance }) {
  848. const store = useStoreApi();
  849. const zoomPane = react.useRef(null);
  850. const { userSelectionActive, lib } = useStore(selector$j, shallow.shallow);
  851. const zoomActivationKeyPressed = useKeyPress(zoomActivationKeyCode);
  852. const panZoom = react.useRef();
  853. useResizeHandler(zoomPane);
  854. const onTransformChange = react.useCallback((transform) => {
  855. onViewportChange?.({ x: transform[0], y: transform[1], zoom: transform[2] });
  856. if (!isControlledViewport) {
  857. store.setState({ transform });
  858. }
  859. }, [onViewportChange, isControlledViewport]);
  860. react.useEffect(() => {
  861. if (zoomPane.current) {
  862. panZoom.current = system.XYPanZoom({
  863. domNode: zoomPane.current,
  864. minZoom,
  865. maxZoom,
  866. translateExtent,
  867. viewport: defaultViewport2,
  868. paneClickDistance,
  869. onDraggingChange: (paneDragging) => store.setState({ paneDragging }),
  870. onPanZoomStart: (event, vp) => {
  871. const { onViewportChangeStart, onMoveStart } = store.getState();
  872. onMoveStart?.(event, vp);
  873. onViewportChangeStart?.(vp);
  874. },
  875. onPanZoom: (event, vp) => {
  876. const { onViewportChange: onViewportChange2, onMove } = store.getState();
  877. onMove?.(event, vp);
  878. onViewportChange2?.(vp);
  879. },
  880. onPanZoomEnd: (event, vp) => {
  881. const { onViewportChangeEnd, onMoveEnd } = store.getState();
  882. onMoveEnd?.(event, vp);
  883. onViewportChangeEnd?.(vp);
  884. }
  885. });
  886. const { x, y, zoom } = panZoom.current.getViewport();
  887. store.setState({
  888. panZoom: panZoom.current,
  889. transform: [x, y, zoom],
  890. domNode: zoomPane.current.closest(".react-flow")
  891. });
  892. return () => {
  893. panZoom.current?.destroy();
  894. };
  895. }
  896. }, []);
  897. react.useEffect(() => {
  898. panZoom.current?.update({
  899. onPaneContextMenu,
  900. zoomOnScroll,
  901. zoomOnPinch,
  902. panOnScroll,
  903. panOnScrollSpeed,
  904. panOnScrollMode,
  905. zoomOnDoubleClick,
  906. panOnDrag,
  907. zoomActivationKeyPressed,
  908. preventScrolling,
  909. noPanClassName,
  910. userSelectionActive,
  911. noWheelClassName,
  912. lib,
  913. onTransformChange
  914. });
  915. }, [
  916. onPaneContextMenu,
  917. zoomOnScroll,
  918. zoomOnPinch,
  919. panOnScroll,
  920. panOnScrollSpeed,
  921. panOnScrollMode,
  922. zoomOnDoubleClick,
  923. panOnDrag,
  924. zoomActivationKeyPressed,
  925. preventScrolling,
  926. noPanClassName,
  927. userSelectionActive,
  928. noWheelClassName,
  929. lib,
  930. onTransformChange
  931. ]);
  932. return jsxRuntime.jsx("div", { className: "react-flow__renderer", ref: zoomPane, style: containerStyle, children });
  933. }
  934. var selector$i = (s) => ({
  935. userSelectionActive: s.userSelectionActive,
  936. userSelectionRect: s.userSelectionRect
  937. });
  938. function UserSelection() {
  939. const { userSelectionActive, userSelectionRect } = useStore(selector$i, shallow.shallow);
  940. const isActive = userSelectionActive && userSelectionRect;
  941. if (!isActive) {
  942. return null;
  943. }
  944. return jsxRuntime.jsx("div", { className: "react-flow__selection react-flow__container", style: {
  945. width: userSelectionRect.width,
  946. height: userSelectionRect.height,
  947. transform: `translate(${userSelectionRect.x}px, ${userSelectionRect.y}px)`
  948. } });
  949. }
  950. var wrapHandler = (handler, containerRef) => {
  951. return (event) => {
  952. if (event.target !== containerRef.current) {
  953. return;
  954. }
  955. handler?.(event);
  956. };
  957. };
  958. var selector$h = (s) => ({
  959. userSelectionActive: s.userSelectionActive,
  960. elementsSelectable: s.elementsSelectable,
  961. dragging: s.paneDragging
  962. });
  963. function Pane({ isSelecting, selectionKeyPressed, selectionMode = system.SelectionMode.Full, panOnDrag, selectionOnDrag, onSelectionStart, onSelectionEnd, onPaneClick, onPaneContextMenu, onPaneScroll, onPaneMouseEnter, onPaneMouseMove, onPaneMouseLeave, children }) {
  964. const container = react.useRef(null);
  965. const store = useStoreApi();
  966. const prevSelectedNodesCount = react.useRef(0);
  967. const prevSelectedEdgesCount = react.useRef(0);
  968. const containerBounds = react.useRef();
  969. const edgeIdLookup = react.useRef( new Map());
  970. const { userSelectionActive, elementsSelectable, dragging } = useStore(selector$h, shallow.shallow);
  971. const hasActiveSelection = elementsSelectable && (isSelecting || userSelectionActive);
  972. const selectionInProgress = react.useRef(false);
  973. const selectionStarted = react.useRef(false);
  974. const resetUserSelection = () => {
  975. store.setState({ userSelectionActive: false, userSelectionRect: null });
  976. prevSelectedNodesCount.current = 0;
  977. prevSelectedEdgesCount.current = 0;
  978. };
  979. const onClick = (event) => {
  980. if (selectionInProgress.current) {
  981. selectionInProgress.current = false;
  982. return;
  983. }
  984. onPaneClick?.(event);
  985. store.getState().resetSelectedElements();
  986. store.setState({ nodesSelectionActive: false });
  987. };
  988. const onContextMenu = (event) => {
  989. if (Array.isArray(panOnDrag) && panOnDrag?.includes(2)) {
  990. event.preventDefault();
  991. return;
  992. }
  993. onPaneContextMenu?.(event);
  994. };
  995. const onWheel = onPaneScroll ? (event) => onPaneScroll(event) : void 0;
  996. const onPointerDown = (event) => {
  997. const { resetSelectedElements, domNode, edgeLookup } = store.getState();
  998. containerBounds.current = domNode?.getBoundingClientRect();
  999. if (!elementsSelectable || !isSelecting || event.button !== 0 || event.target !== container.current || !containerBounds.current) {
  1000. return;
  1001. }
  1002. event.target?.setPointerCapture?.(event.pointerId);
  1003. selectionStarted.current = true;
  1004. selectionInProgress.current = false;
  1005. edgeIdLookup.current = new Map();
  1006. for (const [id, edge] of edgeLookup) {
  1007. edgeIdLookup.current.set(edge.source, edgeIdLookup.current.get(edge.source)?.add(id) || new Set([id]));
  1008. edgeIdLookup.current.set(edge.target, edgeIdLookup.current.get(edge.target)?.add(id) || new Set([id]));
  1009. }
  1010. const { x, y } = system.getEventPosition(event.nativeEvent, containerBounds.current);
  1011. resetSelectedElements();
  1012. store.setState({
  1013. userSelectionRect: {
  1014. width: 0,
  1015. height: 0,
  1016. startX: x,
  1017. startY: y,
  1018. x,
  1019. y
  1020. }
  1021. });
  1022. onSelectionStart?.(event);
  1023. };
  1024. const onPointerMove = (event) => {
  1025. const { userSelectionRect, edgeLookup, transform, nodeLookup, triggerNodeChanges, triggerEdgeChanges } = store.getState();
  1026. if (!containerBounds.current || !userSelectionRect) {
  1027. return;
  1028. }
  1029. selectionInProgress.current = true;
  1030. const { x: mouseX, y: mouseY } = system.getEventPosition(event.nativeEvent, containerBounds.current);
  1031. const { startX, startY } = userSelectionRect;
  1032. const nextUserSelectRect = {
  1033. startX,
  1034. startY,
  1035. x: mouseX < startX ? mouseX : startX,
  1036. y: mouseY < startY ? mouseY : startY,
  1037. width: Math.abs(mouseX - startX),
  1038. height: Math.abs(mouseY - startY)
  1039. };
  1040. const selectedNodes = system.getNodesInside(nodeLookup, nextUserSelectRect, transform, selectionMode === system.SelectionMode.Partial, true);
  1041. const selectedEdgeIds = new Set();
  1042. const selectedNodeIds = new Set();
  1043. for (const selectedNode of selectedNodes) {
  1044. selectedNodeIds.add(selectedNode.id);
  1045. const edgeIds = edgeIdLookup.current.get(selectedNode.id);
  1046. if (edgeIds) {
  1047. for (const edgeId of edgeIds) {
  1048. selectedEdgeIds.add(edgeId);
  1049. }
  1050. }
  1051. }
  1052. if (prevSelectedNodesCount.current !== selectedNodeIds.size) {
  1053. prevSelectedNodesCount.current = selectedNodeIds.size;
  1054. const changes = getSelectionChanges(nodeLookup, selectedNodeIds, true);
  1055. triggerNodeChanges(changes);
  1056. }
  1057. if (prevSelectedEdgesCount.current !== selectedEdgeIds.size) {
  1058. prevSelectedEdgesCount.current = selectedEdgeIds.size;
  1059. const changes = getSelectionChanges(edgeLookup, selectedEdgeIds);
  1060. triggerEdgeChanges(changes);
  1061. }
  1062. store.setState({
  1063. userSelectionRect: nextUserSelectRect,
  1064. userSelectionActive: true,
  1065. nodesSelectionActive: false
  1066. });
  1067. };
  1068. const onPointerUp = (event) => {
  1069. if (event.button !== 0 || !selectionStarted.current) {
  1070. return;
  1071. }
  1072. event.target?.releasePointerCapture?.(event.pointerId);
  1073. const { userSelectionRect } = store.getState();
  1074. if (!userSelectionActive && userSelectionRect && event.target === container.current) {
  1075. onClick?.(event);
  1076. }
  1077. if (prevSelectedNodesCount.current > 0) {
  1078. store.setState({ nodesSelectionActive: true });
  1079. }
  1080. resetUserSelection();
  1081. onSelectionEnd?.(event);
  1082. if (selectionKeyPressed || selectionOnDrag) {
  1083. selectionInProgress.current = false;
  1084. }
  1085. selectionStarted.current = false;
  1086. };
  1087. const draggable = panOnDrag === true || Array.isArray(panOnDrag) && panOnDrag.includes(0);
  1088. return jsxRuntime.jsxs("div", { className: cc(["react-flow__pane", { draggable, dragging, selection: isSelecting }]), onClick: hasActiveSelection ? void 0 : wrapHandler(onClick, container), onContextMenu: wrapHandler(onContextMenu, container), onWheel: wrapHandler(onWheel, container), onPointerEnter: hasActiveSelection ? void 0 : onPaneMouseEnter, onPointerDown: hasActiveSelection ? onPointerDown : onPaneMouseMove, onPointerMove: hasActiveSelection ? onPointerMove : onPaneMouseMove, onPointerUp: hasActiveSelection ? onPointerUp : void 0, onPointerLeave: onPaneMouseLeave, ref: container, style: containerStyle, children: [children, jsxRuntime.jsx(UserSelection, {})] });
  1089. }
  1090. function handleNodeClick({ id, store, unselect = false, nodeRef }) {
  1091. const { addSelectedNodes, unselectNodesAndEdges, multiSelectionActive, nodeLookup, onError } = store.getState();
  1092. const node = nodeLookup.get(id);
  1093. if (!node) {
  1094. onError?.("012", system.errorMessages["error012"](id));
  1095. return;
  1096. }
  1097. store.setState({ nodesSelectionActive: false });
  1098. if (!node.selected) {
  1099. addSelectedNodes([id]);
  1100. } else if (unselect || node.selected && multiSelectionActive) {
  1101. unselectNodesAndEdges({ nodes: [node], edges: [] });
  1102. requestAnimationFrame(() => nodeRef?.current?.blur());
  1103. }
  1104. }
  1105. function useDrag({ nodeRef, disabled = false, noDragClassName, handleSelector, nodeId, isSelectable, nodeClickDistance }) {
  1106. const store = useStoreApi();
  1107. const [dragging, setDragging] = react.useState(false);
  1108. const xyDrag = react.useRef();
  1109. react.useEffect(() => {
  1110. xyDrag.current = system.XYDrag({
  1111. getStoreItems: () => store.getState(),
  1112. onNodeMouseDown: (id) => {
  1113. handleNodeClick({
  1114. id,
  1115. store,
  1116. nodeRef
  1117. });
  1118. },
  1119. onDragStart: () => {
  1120. setDragging(true);
  1121. },
  1122. onDragStop: () => {
  1123. setDragging(false);
  1124. }
  1125. });
  1126. }, []);
  1127. react.useEffect(() => {
  1128. if (disabled) {
  1129. xyDrag.current?.destroy();
  1130. } else if (nodeRef.current) {
  1131. xyDrag.current?.update({
  1132. noDragClassName,
  1133. handleSelector,
  1134. domNode: nodeRef.current,
  1135. isSelectable,
  1136. nodeId,
  1137. nodeClickDistance
  1138. });
  1139. return () => {
  1140. xyDrag.current?.destroy();
  1141. };
  1142. }
  1143. }, [noDragClassName, handleSelector, disabled, isSelectable, nodeRef, nodeId]);
  1144. return dragging;
  1145. }
  1146. var selectedAndDraggable = (nodesDraggable) => (n) => n.selected && (n.draggable || nodesDraggable && typeof n.draggable === "undefined");
  1147. function useMoveSelectedNodes() {
  1148. const store = useStoreApi();
  1149. const moveSelectedNodes = react.useCallback((params) => {
  1150. const { nodeExtent, snapToGrid, snapGrid, nodesDraggable, onError, updateNodePositions, nodeLookup, nodeOrigin } = store.getState();
  1151. const nodeUpdates = new Map();
  1152. const isSelected = selectedAndDraggable(nodesDraggable);
  1153. const xVelo = snapToGrid ? snapGrid[0] : 5;
  1154. const yVelo = snapToGrid ? snapGrid[1] : 5;
  1155. const xDiff = params.direction.x * xVelo * params.factor;
  1156. const yDiff = params.direction.y * yVelo * params.factor;
  1157. for (const [, node] of nodeLookup) {
  1158. if (!isSelected(node)) {
  1159. continue;
  1160. }
  1161. let nextPosition = {
  1162. x: node.internals.positionAbsolute.x + xDiff,
  1163. y: node.internals.positionAbsolute.y + yDiff
  1164. };
  1165. if (snapToGrid) {
  1166. nextPosition = system.snapPosition(nextPosition, snapGrid);
  1167. }
  1168. const { position, positionAbsolute } = system.calculateNodePosition({
  1169. nodeId: node.id,
  1170. nextPosition,
  1171. nodeLookup,
  1172. nodeExtent,
  1173. nodeOrigin,
  1174. onError
  1175. });
  1176. node.position = position;
  1177. node.internals.positionAbsolute = positionAbsolute;
  1178. nodeUpdates.set(node.id, node);
  1179. }
  1180. updateNodePositions(nodeUpdates);
  1181. }, []);
  1182. return moveSelectedNodes;
  1183. }
  1184. var NodeIdContext = react.createContext(null);
  1185. var Provider = NodeIdContext.Provider;
  1186. NodeIdContext.Consumer;
  1187. var useNodeId = () => {
  1188. const nodeId = react.useContext(NodeIdContext);
  1189. return nodeId;
  1190. };
  1191. var selector$g = (s) => ({
  1192. connectOnClick: s.connectOnClick,
  1193. noPanClassName: s.noPanClassName,
  1194. rfId: s.rfId
  1195. });
  1196. var connectingSelector = (nodeId, handleId, type) => (state) => {
  1197. const { connectionClickStartHandle: clickHandle, connectionMode, connection } = state;
  1198. const { fromHandle, toHandle, isValid } = connection;
  1199. const connectingTo = toHandle?.nodeId === nodeId && toHandle?.id === handleId && toHandle?.type === type;
  1200. return {
  1201. connectingFrom: fromHandle?.nodeId === nodeId && fromHandle?.id === handleId && fromHandle?.type === type,
  1202. connectingTo,
  1203. clickConnecting: clickHandle?.nodeId === nodeId && clickHandle?.id === handleId && clickHandle?.type === type,
  1204. isPossibleEndHandle: connectionMode === system.ConnectionMode.Strict ? fromHandle?.type !== type : nodeId !== fromHandle?.nodeId || handleId !== fromHandle?.id,
  1205. connectionInProcess: !!fromHandle,
  1206. valid: connectingTo && isValid
  1207. };
  1208. };
  1209. function HandleComponent({ type = "source", position = system.Position.Top, isValidConnection, isConnectable = true, isConnectableStart = true, isConnectableEnd = true, id, onConnect, children, className, onMouseDown, onTouchStart, ...rest }, ref) {
  1210. const handleId = id || null;
  1211. const isTarget = type === "target";
  1212. const store = useStoreApi();
  1213. const nodeId = useNodeId();
  1214. const { connectOnClick, noPanClassName, rfId } = useStore(selector$g, shallow.shallow);
  1215. const { connectingFrom, connectingTo, clickConnecting, isPossibleEndHandle, connectionInProcess, valid } = useStore(connectingSelector(nodeId, handleId, type), shallow.shallow);
  1216. if (!nodeId) {
  1217. store.getState().onError?.("010", system.errorMessages["error010"]());
  1218. }
  1219. const onConnectExtended = (params) => {
  1220. const { defaultEdgeOptions, onConnect: onConnectAction, hasDefaultEdges } = store.getState();
  1221. const edgeParams = {
  1222. ...defaultEdgeOptions,
  1223. ...params
  1224. };
  1225. if (hasDefaultEdges) {
  1226. const { edges, setEdges } = store.getState();
  1227. setEdges(system.addEdge(edgeParams, edges));
  1228. }
  1229. onConnectAction?.(edgeParams);
  1230. onConnect?.(edgeParams);
  1231. };
  1232. const onPointerDown = (event) => {
  1233. if (!nodeId) {
  1234. return;
  1235. }
  1236. const isMouseTriggered = system.isMouseEvent(event.nativeEvent);
  1237. if (isConnectableStart && (isMouseTriggered && event.button === 0 || !isMouseTriggered)) {
  1238. const currentStore = store.getState();
  1239. system.XYHandle.onPointerDown(event.nativeEvent, {
  1240. autoPanOnConnect: currentStore.autoPanOnConnect,
  1241. connectionMode: currentStore.connectionMode,
  1242. connectionRadius: currentStore.connectionRadius,
  1243. domNode: currentStore.domNode,
  1244. nodeLookup: currentStore.nodeLookup,
  1245. lib: currentStore.lib,
  1246. isTarget,
  1247. handleId,
  1248. nodeId,
  1249. flowId: currentStore.rfId,
  1250. panBy: currentStore.panBy,
  1251. cancelConnection: currentStore.cancelConnection,
  1252. onConnectStart: currentStore.onConnectStart,
  1253. onConnectEnd: currentStore.onConnectEnd,
  1254. updateConnection: currentStore.updateConnection,
  1255. onConnect: onConnectExtended,
  1256. isValidConnection: isValidConnection || currentStore.isValidConnection,
  1257. getTransform: () => store.getState().transform,
  1258. getFromHandle: () => store.getState().connection.fromHandle,
  1259. autoPanSpeed: currentStore.autoPanSpeed
  1260. });
  1261. }
  1262. if (isMouseTriggered) {
  1263. onMouseDown?.(event);
  1264. } else {
  1265. onTouchStart?.(event);
  1266. }
  1267. };
  1268. const onClick = (event) => {
  1269. const { onClickConnectStart, onClickConnectEnd, connectionClickStartHandle, connectionMode, isValidConnection: isValidConnectionStore, lib, rfId: flowId, nodeLookup, connection: connectionState } = store.getState();
  1270. if (!nodeId || !connectionClickStartHandle && !isConnectableStart) {
  1271. return;
  1272. }
  1273. if (!connectionClickStartHandle) {
  1274. onClickConnectStart?.(event.nativeEvent, { nodeId, handleId, handleType: type });
  1275. store.setState({ connectionClickStartHandle: { nodeId, type, id: handleId } });
  1276. return;
  1277. }
  1278. const doc = system.getHostForElement(event.target);
  1279. const isValidConnectionHandler = isValidConnection || isValidConnectionStore;
  1280. const { connection, isValid } = system.XYHandle.isValid(event.nativeEvent, {
  1281. handle: {
  1282. nodeId,
  1283. id: handleId,
  1284. type
  1285. },
  1286. connectionMode,
  1287. fromNodeId: connectionClickStartHandle.nodeId,
  1288. fromHandleId: connectionClickStartHandle.id || null,
  1289. fromType: connectionClickStartHandle.type,
  1290. isValidConnection: isValidConnectionHandler,
  1291. flowId,
  1292. doc,
  1293. lib,
  1294. nodeLookup
  1295. });
  1296. if (isValid && connection) {
  1297. onConnectExtended(connection);
  1298. }
  1299. const connectionClone = structuredClone(connectionState);
  1300. delete connectionClone.inProgress;
  1301. connectionClone.toPosition = connectionClone.toHandle ? connectionClone.toHandle.position : null;
  1302. onClickConnectEnd?.(event, connectionClone);
  1303. store.setState({ connectionClickStartHandle: null });
  1304. };
  1305. return jsxRuntime.jsx("div", { "data-handleid": handleId, "data-nodeid": nodeId, "data-handlepos": position, "data-id": `${rfId}-${nodeId}-${handleId}-${type}`, className: cc([
  1306. "react-flow__handle",
  1307. `react-flow__handle-${position}`,
  1308. "nodrag",
  1309. noPanClassName,
  1310. className,
  1311. {
  1312. source: !isTarget,
  1313. target: isTarget,
  1314. connectable: isConnectable,
  1315. connectablestart: isConnectableStart,
  1316. connectableend: isConnectableEnd,
  1317. clickconnecting: clickConnecting,
  1318. connectingfrom: connectingFrom,
  1319. connectingto: connectingTo,
  1320. valid,
  1321. connectionindicator: isConnectable && (!connectionInProcess || isPossibleEndHandle) && (connectionInProcess ? isConnectableEnd : isConnectableStart)
  1322. }
  1323. ]), onMouseDown: onPointerDown, onTouchStart: onPointerDown, onClick: connectOnClick ? onClick : void 0, ref, ...rest, children });
  1324. }
  1325. var Handle = react.memo(fixedForwardRef(HandleComponent));
  1326. function InputNode({ data, isConnectable, sourcePosition = system.Position.Bottom }) {
  1327. return jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [data?.label, jsxRuntime.jsx(Handle, { type: "source", position: sourcePosition, isConnectable })] });
  1328. }
  1329. function DefaultNode({ data, isConnectable, targetPosition = system.Position.Top, sourcePosition = system.Position.Bottom }) {
  1330. return jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx(Handle, { type: "target", position: targetPosition, isConnectable }), data?.label, jsxRuntime.jsx(Handle, { type: "source", position: sourcePosition, isConnectable })] });
  1331. }
  1332. function GroupNode() {
  1333. return null;
  1334. }
  1335. function OutputNode({ data, isConnectable, targetPosition = system.Position.Top }) {
  1336. return jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx(Handle, { type: "target", position: targetPosition, isConnectable }), data?.label] });
  1337. }
  1338. var arrowKeyDiffs = {
  1339. ArrowUp: { x: 0, y: -1 },
  1340. ArrowDown: { x: 0, y: 1 },
  1341. ArrowLeft: { x: -1, y: 0 },
  1342. ArrowRight: { x: 1, y: 0 }
  1343. };
  1344. var builtinNodeTypes = {
  1345. input: InputNode,
  1346. default: DefaultNode,
  1347. output: OutputNode,
  1348. group: GroupNode
  1349. };
  1350. function getNodeInlineStyleDimensions(node) {
  1351. if (node.internals.handleBounds === void 0) {
  1352. return {
  1353. width: node.width ?? node.initialWidth ?? node.style?.width,
  1354. height: node.height ?? node.initialHeight ?? node.style?.height
  1355. };
  1356. }
  1357. return {
  1358. width: node.width ?? node.style?.width,
  1359. height: node.height ?? node.style?.height
  1360. };
  1361. }
  1362. var selector$f = (s) => {
  1363. const { width, height, x, y } = system.getInternalNodesBounds(s.nodeLookup, {
  1364. filter: (node) => !!node.selected
  1365. });
  1366. return {
  1367. width: system.isNumeric(width) ? width : null,
  1368. height: system.isNumeric(height) ? height : null,
  1369. userSelectionActive: s.userSelectionActive,
  1370. transformString: `translate(${s.transform[0]}px,${s.transform[1]}px) scale(${s.transform[2]}) translate(${x}px,${y}px)`
  1371. };
  1372. };
  1373. function NodesSelection({ onSelectionContextMenu, noPanClassName, disableKeyboardA11y }) {
  1374. const store = useStoreApi();
  1375. const { width, height, transformString, userSelectionActive } = useStore(selector$f, shallow.shallow);
  1376. const moveSelectedNodes = useMoveSelectedNodes();
  1377. const nodeRef = react.useRef(null);
  1378. react.useEffect(() => {
  1379. if (!disableKeyboardA11y) {
  1380. nodeRef.current?.focus({
  1381. preventScroll: true
  1382. });
  1383. }
  1384. }, [disableKeyboardA11y]);
  1385. useDrag({
  1386. nodeRef
  1387. });
  1388. if (userSelectionActive || !width || !height) {
  1389. return null;
  1390. }
  1391. const onContextMenu = onSelectionContextMenu ? (event) => {
  1392. const selectedNodes = store.getState().nodes.filter((n) => n.selected);
  1393. onSelectionContextMenu(event, selectedNodes);
  1394. } : void 0;
  1395. const onKeyDown = (event) => {
  1396. if (Object.prototype.hasOwnProperty.call(arrowKeyDiffs, event.key)) {
  1397. event.preventDefault();
  1398. moveSelectedNodes({
  1399. direction: arrowKeyDiffs[event.key],
  1400. factor: event.shiftKey ? 4 : 1
  1401. });
  1402. }
  1403. };
  1404. return jsxRuntime.jsx("div", { className: cc(["react-flow__nodesselection", "react-flow__container", noPanClassName]), style: {
  1405. transform: transformString
  1406. }, children: jsxRuntime.jsx("div", { ref: nodeRef, className: "react-flow__nodesselection-rect", onContextMenu, tabIndex: disableKeyboardA11y ? void 0 : -1, onKeyDown: disableKeyboardA11y ? void 0 : onKeyDown, style: {
  1407. width,
  1408. height
  1409. } }) });
  1410. }
  1411. var win = typeof window !== "undefined" ? window : void 0;
  1412. var selector$e = (s) => {
  1413. return { nodesSelectionActive: s.nodesSelectionActive, userSelectionActive: s.userSelectionActive };
  1414. };
  1415. function FlowRendererComponent({ children, onPaneClick, onPaneMouseEnter, onPaneMouseMove, onPaneMouseLeave, onPaneContextMenu, onPaneScroll, paneClickDistance, deleteKeyCode, selectionKeyCode, selectionOnDrag, selectionMode, onSelectionStart, onSelectionEnd, multiSelectionKeyCode, panActivationKeyCode, zoomActivationKeyCode, elementsSelectable, zoomOnScroll, zoomOnPinch, panOnScroll: _panOnScroll, panOnScrollSpeed, panOnScrollMode, zoomOnDoubleClick, panOnDrag: _panOnDrag, defaultViewport: defaultViewport2, translateExtent, minZoom, maxZoom, preventScrolling, onSelectionContextMenu, noWheelClassName, noPanClassName, disableKeyboardA11y, onViewportChange, isControlledViewport }) {
  1416. const { nodesSelectionActive, userSelectionActive } = useStore(selector$e);
  1417. const selectionKeyPressed = useKeyPress(selectionKeyCode, { target: win });
  1418. const panActivationKeyPressed = useKeyPress(panActivationKeyCode, { target: win });
  1419. const panOnDrag = panActivationKeyPressed || _panOnDrag;
  1420. const panOnScroll = panActivationKeyPressed || _panOnScroll;
  1421. const _selectionOnDrag = selectionOnDrag && panOnDrag !== true;
  1422. const isSelecting = selectionKeyPressed || userSelectionActive || _selectionOnDrag;
  1423. useGlobalKeyHandler({ deleteKeyCode, multiSelectionKeyCode });
  1424. return jsxRuntime.jsx(ZoomPane, { onPaneContextMenu, elementsSelectable, zoomOnScroll, zoomOnPinch, panOnScroll, panOnScrollSpeed, panOnScrollMode, zoomOnDoubleClick, panOnDrag: !selectionKeyPressed && panOnDrag, defaultViewport: defaultViewport2, translateExtent, minZoom, maxZoom, zoomActivationKeyCode, preventScrolling, noWheelClassName, noPanClassName, onViewportChange, isControlledViewport, paneClickDistance, children: jsxRuntime.jsxs(Pane, { onSelectionStart, onSelectionEnd, onPaneClick, onPaneMouseEnter, onPaneMouseMove, onPaneMouseLeave, onPaneContextMenu, onPaneScroll, panOnDrag, isSelecting: !!isSelecting, selectionMode, selectionKeyPressed, selectionOnDrag: _selectionOnDrag, children: [children, nodesSelectionActive && jsxRuntime.jsx(NodesSelection, { onSelectionContextMenu, noPanClassName, disableKeyboardA11y })] }) });
  1425. }
  1426. FlowRendererComponent.displayName = "FlowRenderer";
  1427. var FlowRenderer = react.memo(FlowRendererComponent);
  1428. var selector$d = (onlyRenderVisible) => (s) => {
  1429. return onlyRenderVisible ? system.getNodesInside(s.nodeLookup, { x: 0, y: 0, width: s.width, height: s.height }, s.transform, true).map((node) => node.id) : Array.from(s.nodeLookup.keys());
  1430. };
  1431. function useVisibleNodeIds(onlyRenderVisible) {
  1432. const nodeIds = useStore(react.useCallback(selector$d(onlyRenderVisible), [onlyRenderVisible]), shallow.shallow);
  1433. return nodeIds;
  1434. }
  1435. var selector$c = (s) => s.updateNodeInternals;
  1436. function useResizeObserver() {
  1437. const updateNodeInternals2 = useStore(selector$c);
  1438. const [resizeObserver] = react.useState(() => {
  1439. if (typeof ResizeObserver === "undefined") {
  1440. return null;
  1441. }
  1442. return new ResizeObserver((entries) => {
  1443. const updates = new Map();
  1444. entries.forEach((entry) => {
  1445. const id = entry.target.getAttribute("data-id");
  1446. updates.set(id, {
  1447. id,
  1448. nodeElement: entry.target,
  1449. force: true
  1450. });
  1451. });
  1452. updateNodeInternals2(updates);
  1453. });
  1454. });
  1455. react.useEffect(() => {
  1456. return () => {
  1457. resizeObserver?.disconnect();
  1458. };
  1459. }, [resizeObserver]);
  1460. return resizeObserver;
  1461. }
  1462. function useNodeObserver({ node, nodeType, hasDimensions, resizeObserver }) {
  1463. const store = useStoreApi();
  1464. const nodeRef = react.useRef(null);
  1465. const observedNode = react.useRef(null);
  1466. const prevSourcePosition = react.useRef(node.sourcePosition);
  1467. const prevTargetPosition = react.useRef(node.targetPosition);
  1468. const prevType = react.useRef(nodeType);
  1469. const isInitialized = hasDimensions && !!node.internals.handleBounds;
  1470. react.useEffect(() => {
  1471. if (nodeRef.current && !node.hidden && (!isInitialized || observedNode.current !== nodeRef.current)) {
  1472. if (observedNode.current) {
  1473. resizeObserver?.unobserve(observedNode.current);
  1474. }
  1475. resizeObserver?.observe(nodeRef.current);
  1476. observedNode.current = nodeRef.current;
  1477. }
  1478. }, [isInitialized, node.hidden]);
  1479. react.useEffect(() => {
  1480. return () => {
  1481. if (observedNode.current) {
  1482. resizeObserver?.unobserve(observedNode.current);
  1483. observedNode.current = null;
  1484. }
  1485. };
  1486. }, []);
  1487. react.useEffect(() => {
  1488. if (nodeRef.current) {
  1489. const typeChanged = prevType.current !== nodeType;
  1490. const sourcePosChanged = prevSourcePosition.current !== node.sourcePosition;
  1491. const targetPosChanged = prevTargetPosition.current !== node.targetPosition;
  1492. if (typeChanged || sourcePosChanged || targetPosChanged) {
  1493. prevType.current = nodeType;
  1494. prevSourcePosition.current = node.sourcePosition;
  1495. prevTargetPosition.current = node.targetPosition;
  1496. store.getState().updateNodeInternals( new Map([[node.id, { id: node.id, nodeElement: nodeRef.current, force: true }]]));
  1497. }
  1498. }
  1499. }, [node.id, nodeType, node.sourcePosition, node.targetPosition]);
  1500. return nodeRef;
  1501. }
  1502. function NodeWrapper({ id, onClick, onMouseEnter, onMouseMove, onMouseLeave, onContextMenu, onDoubleClick, nodesDraggable, elementsSelectable, nodesConnectable, nodesFocusable, resizeObserver, noDragClassName, noPanClassName, disableKeyboardA11y, rfId, nodeTypes, nodeExtent, nodeClickDistance, onError }) {
  1503. const { node, internals, isParent } = useStore((s) => {
  1504. const node2 = s.nodeLookup.get(id);
  1505. const isParent2 = s.parentLookup.has(id);
  1506. return {
  1507. node: node2,
  1508. internals: node2.internals,
  1509. isParent: isParent2
  1510. };
  1511. }, shallow.shallow);
  1512. let nodeType = node.type || "default";
  1513. let NodeComponent = nodeTypes?.[nodeType] || builtinNodeTypes[nodeType];
  1514. if (NodeComponent === void 0) {
  1515. onError?.("003", system.errorMessages["error003"](nodeType));
  1516. nodeType = "default";
  1517. NodeComponent = builtinNodeTypes.default;
  1518. }
  1519. const isDraggable = !!(node.draggable || nodesDraggable && typeof node.draggable === "undefined");
  1520. const isSelectable = !!(node.selectable || elementsSelectable && typeof node.selectable === "undefined");
  1521. const isConnectable = !!(node.connectable || nodesConnectable && typeof node.connectable === "undefined");
  1522. const isFocusable = !!(node.focusable || nodesFocusable && typeof node.focusable === "undefined");
  1523. const store = useStoreApi();
  1524. const hasDimensions = system.nodeHasDimensions(node);
  1525. const nodeRef = useNodeObserver({ node, nodeType, hasDimensions, resizeObserver });
  1526. const dragging = useDrag({
  1527. nodeRef,
  1528. disabled: node.hidden || !isDraggable,
  1529. noDragClassName,
  1530. handleSelector: node.dragHandle,
  1531. nodeId: id,
  1532. isSelectable,
  1533. nodeClickDistance
  1534. });
  1535. const moveSelectedNodes = useMoveSelectedNodes();
  1536. if (node.hidden) {
  1537. return null;
  1538. }
  1539. const nodeDimensions = system.getNodeDimensions(node);
  1540. const inlineDimensions = getNodeInlineStyleDimensions(node);
  1541. const hasPointerEvents = isSelectable || isDraggable || onClick || onMouseEnter || onMouseMove || onMouseLeave;
  1542. const onMouseEnterHandler = onMouseEnter ? (event) => onMouseEnter(event, { ...internals.userNode }) : void 0;
  1543. const onMouseMoveHandler = onMouseMove ? (event) => onMouseMove(event, { ...internals.userNode }) : void 0;
  1544. const onMouseLeaveHandler = onMouseLeave ? (event) => onMouseLeave(event, { ...internals.userNode }) : void 0;
  1545. const onContextMenuHandler = onContextMenu ? (event) => onContextMenu(event, { ...internals.userNode }) : void 0;
  1546. const onDoubleClickHandler = onDoubleClick ? (event) => onDoubleClick(event, { ...internals.userNode }) : void 0;
  1547. const onSelectNodeHandler = (event) => {
  1548. const { selectNodesOnDrag, nodeDragThreshold } = store.getState();
  1549. if (isSelectable && (!selectNodesOnDrag || !isDraggable || nodeDragThreshold > 0)) {
  1550. handleNodeClick({
  1551. id,
  1552. store,
  1553. nodeRef
  1554. });
  1555. }
  1556. if (onClick) {
  1557. onClick(event, { ...internals.userNode });
  1558. }
  1559. };
  1560. const onKeyDown = (event) => {
  1561. if (system.isInputDOMNode(event.nativeEvent) || disableKeyboardA11y) {
  1562. return;
  1563. }
  1564. if (system.elementSelectionKeys.includes(event.key) && isSelectable) {
  1565. const unselect = event.key === "Escape";
  1566. handleNodeClick({
  1567. id,
  1568. store,
  1569. unselect,
  1570. nodeRef
  1571. });
  1572. } else if (isDraggable && node.selected && Object.prototype.hasOwnProperty.call(arrowKeyDiffs, event.key)) {
  1573. event.preventDefault();
  1574. store.setState({
  1575. ariaLiveMessage: `Moved selected node ${event.key.replace("Arrow", "").toLowerCase()}. New position, x: ${~~internals.positionAbsolute.x}, y: ${~~internals.positionAbsolute.y}`
  1576. });
  1577. moveSelectedNodes({
  1578. direction: arrowKeyDiffs[event.key],
  1579. factor: event.shiftKey ? 4 : 1
  1580. });
  1581. }
  1582. };
  1583. return jsxRuntime.jsx("div", { className: cc([
  1584. "react-flow__node",
  1585. `react-flow__node-${nodeType}`,
  1586. {
  1587. [noPanClassName]: isDraggable
  1588. },
  1589. node.className,
  1590. {
  1591. selected: node.selected,
  1592. selectable: isSelectable,
  1593. parent: isParent,
  1594. draggable: isDraggable,
  1595. dragging
  1596. }
  1597. ]), ref: nodeRef, style: {
  1598. zIndex: internals.z,
  1599. transform: `translate(${internals.positionAbsolute.x}px,${internals.positionAbsolute.y}px)`,
  1600. pointerEvents: hasPointerEvents ? "all" : "none",
  1601. visibility: hasDimensions ? "visible" : "hidden",
  1602. ...node.style,
  1603. ...inlineDimensions
  1604. }, "data-id": id, "data-testid": `rf__node-${id}`, onMouseEnter: onMouseEnterHandler, onMouseMove: onMouseMoveHandler, onMouseLeave: onMouseLeaveHandler, onContextMenu: onContextMenuHandler, onClick: onSelectNodeHandler, onDoubleClick: onDoubleClickHandler, onKeyDown: isFocusable ? onKeyDown : void 0, tabIndex: isFocusable ? 0 : void 0, role: isFocusable ? "button" : void 0, "aria-describedby": disableKeyboardA11y ? void 0 : `${ARIA_NODE_DESC_KEY}-${rfId}`, "aria-label": node.ariaLabel, children: jsxRuntime.jsx(Provider, { value: id, children: jsxRuntime.jsx(NodeComponent, { id, data: node.data, type: nodeType, positionAbsoluteX: internals.positionAbsolute.x, positionAbsoluteY: internals.positionAbsolute.y, selected: node.selected, selectable: isSelectable, draggable: isDraggable, deletable: node.deletable ?? true, isConnectable, sourcePosition: node.sourcePosition, targetPosition: node.targetPosition, dragging, dragHandle: node.dragHandle, zIndex: internals.z, parentId: node.parentId, ...nodeDimensions }) }) });
  1605. }
  1606. var selector$b = (s) => ({
  1607. nodesDraggable: s.nodesDraggable,
  1608. nodesConnectable: s.nodesConnectable,
  1609. nodesFocusable: s.nodesFocusable,
  1610. elementsSelectable: s.elementsSelectable,
  1611. onError: s.onError
  1612. });
  1613. function NodeRendererComponent(props) {
  1614. const { nodesDraggable, nodesConnectable, nodesFocusable, elementsSelectable, onError } = useStore(selector$b, shallow.shallow);
  1615. const nodeIds = useVisibleNodeIds(props.onlyRenderVisibleElements);
  1616. const resizeObserver = useResizeObserver();
  1617. return jsxRuntime.jsx("div", { className: "react-flow__nodes", style: containerStyle, children: nodeIds.map((nodeId) => {
  1618. return (
  1619. jsxRuntime.jsx(NodeWrapper, { id: nodeId, nodeTypes: props.nodeTypes, nodeExtent: props.nodeExtent, onClick: props.onNodeClick, onMouseEnter: props.onNodeMouseEnter, onMouseMove: props.onNodeMouseMove, onMouseLeave: props.onNodeMouseLeave, onContextMenu: props.onNodeContextMenu, onDoubleClick: props.onNodeDoubleClick, noDragClassName: props.noDragClassName, noPanClassName: props.noPanClassName, rfId: props.rfId, disableKeyboardA11y: props.disableKeyboardA11y, resizeObserver, nodesDraggable, nodesConnectable, nodesFocusable, elementsSelectable, nodeClickDistance: props.nodeClickDistance, onError }, nodeId)
  1620. );
  1621. }) });
  1622. }
  1623. NodeRendererComponent.displayName = "NodeRenderer";
  1624. var NodeRenderer = react.memo(NodeRendererComponent);
  1625. function useVisibleEdgeIds(onlyRenderVisible) {
  1626. const edgeIds = useStore(react.useCallback((s) => {
  1627. if (!onlyRenderVisible) {
  1628. return s.edges.map((edge) => edge.id);
  1629. }
  1630. const visibleEdgeIds = [];
  1631. if (s.width && s.height) {
  1632. for (const edge of s.edges) {
  1633. const sourceNode = s.nodeLookup.get(edge.source);
  1634. const targetNode = s.nodeLookup.get(edge.target);
  1635. if (sourceNode && targetNode && system.isEdgeVisible({
  1636. sourceNode,
  1637. targetNode,
  1638. width: s.width,
  1639. height: s.height,
  1640. transform: s.transform
  1641. })) {
  1642. visibleEdgeIds.push(edge.id);
  1643. }
  1644. }
  1645. }
  1646. return visibleEdgeIds;
  1647. }, [onlyRenderVisible]), shallow.shallow);
  1648. return edgeIds;
  1649. }
  1650. var ArrowSymbol = ({ color = "none", strokeWidth = 1 }) => {
  1651. return jsxRuntime.jsx("polyline", { style: {
  1652. stroke: color,
  1653. strokeWidth
  1654. }, strokeLinecap: "round", strokeLinejoin: "round", fill: "none", points: "-5,-4 0,0 -5,4" });
  1655. };
  1656. var ArrowClosedSymbol = ({ color = "none", strokeWidth = 1 }) => {
  1657. return jsxRuntime.jsx("polyline", { style: {
  1658. stroke: color,
  1659. fill: color,
  1660. strokeWidth
  1661. }, strokeLinecap: "round", strokeLinejoin: "round", points: "-5,-4 0,0 -5,4 -5,-4" });
  1662. };
  1663. var MarkerSymbols = {
  1664. [system.MarkerType.Arrow]: ArrowSymbol,
  1665. [system.MarkerType.ArrowClosed]: ArrowClosedSymbol
  1666. };
  1667. function useMarkerSymbol(type) {
  1668. const store = useStoreApi();
  1669. const symbol = react.useMemo(() => {
  1670. const symbolExists = Object.prototype.hasOwnProperty.call(MarkerSymbols, type);
  1671. if (!symbolExists) {
  1672. store.getState().onError?.("009", system.errorMessages["error009"](type));
  1673. return null;
  1674. }
  1675. return MarkerSymbols[type];
  1676. }, [type]);
  1677. return symbol;
  1678. }
  1679. var Marker = ({ id, type, color, width = 12.5, height = 12.5, markerUnits = "strokeWidth", strokeWidth, orient = "auto-start-reverse" }) => {
  1680. const Symbol = useMarkerSymbol(type);
  1681. if (!Symbol) {
  1682. return null;
  1683. }
  1684. return jsxRuntime.jsx("marker", { className: "react-flow__arrowhead", id, markerWidth: `${width}`, markerHeight: `${height}`, viewBox: "-10 -10 20 20", markerUnits, orient, refX: "0", refY: "0", children: jsxRuntime.jsx(Symbol, { color, strokeWidth }) });
  1685. };
  1686. var MarkerDefinitions = ({ defaultColor, rfId }) => {
  1687. const edges = useStore((s) => s.edges);
  1688. const defaultEdgeOptions = useStore((s) => s.defaultEdgeOptions);
  1689. const markers = react.useMemo(() => {
  1690. const markers2 = system.createMarkerIds(edges, {
  1691. id: rfId,
  1692. defaultColor,
  1693. defaultMarkerStart: defaultEdgeOptions?.markerStart,
  1694. defaultMarkerEnd: defaultEdgeOptions?.markerEnd
  1695. });
  1696. return markers2;
  1697. }, [edges, defaultEdgeOptions, rfId, defaultColor]);
  1698. if (!markers.length) {
  1699. return null;
  1700. }
  1701. return jsxRuntime.jsx("svg", { className: "react-flow__marker", children: jsxRuntime.jsx("defs", { children: markers.map((marker) => jsxRuntime.jsx(Marker, { id: marker.id, type: marker.type, color: marker.color, width: marker.width, height: marker.height, markerUnits: marker.markerUnits, strokeWidth: marker.strokeWidth, orient: marker.orient }, marker.id)) }) });
  1702. };
  1703. MarkerDefinitions.displayName = "MarkerDefinitions";
  1704. var MarkerDefinitions$1 = react.memo(MarkerDefinitions);
  1705. function EdgeTextComponent({ x, y, label, labelStyle = {}, labelShowBg = true, labelBgStyle = {}, labelBgPadding = [2, 4], labelBgBorderRadius = 2, children, className, ...rest }) {
  1706. const [edgeTextBbox, setEdgeTextBbox] = react.useState({ x: 1, y: 0, width: 0, height: 0 });
  1707. const edgeTextClasses = cc(["react-flow__edge-textwrapper", className]);
  1708. const edgeTextRef = react.useRef(null);
  1709. react.useEffect(() => {
  1710. if (edgeTextRef.current) {
  1711. const textBbox = edgeTextRef.current.getBBox();
  1712. setEdgeTextBbox({
  1713. x: textBbox.x,
  1714. y: textBbox.y,
  1715. width: textBbox.width,
  1716. height: textBbox.height
  1717. });
  1718. }
  1719. }, [label]);
  1720. if (typeof label === "undefined" || !label) {
  1721. return null;
  1722. }
  1723. return jsxRuntime.jsxs("g", { transform: `translate(${x - edgeTextBbox.width / 2} ${y - edgeTextBbox.height / 2})`, className: edgeTextClasses, visibility: edgeTextBbox.width ? "visible" : "hidden", ...rest, children: [labelShowBg && jsxRuntime.jsx("rect", { width: edgeTextBbox.width + 2 * labelBgPadding[0], x: -labelBgPadding[0], y: -labelBgPadding[1], height: edgeTextBbox.height + 2 * labelBgPadding[1], className: "react-flow__edge-textbg", style: labelBgStyle, rx: labelBgBorderRadius, ry: labelBgBorderRadius }), jsxRuntime.jsx("text", { className: "react-flow__edge-text", y: edgeTextBbox.height / 2, dy: "0.3em", ref: edgeTextRef, style: labelStyle, children: label }), children] });
  1724. }
  1725. EdgeTextComponent.displayName = "EdgeText";
  1726. var EdgeText = react.memo(EdgeTextComponent);
  1727. function BaseEdge({ path, labelX, labelY, label, labelStyle, labelShowBg, labelBgStyle, labelBgPadding, labelBgBorderRadius, interactionWidth = 20, ...props }) {
  1728. return jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("path", { ...props, d: path, fill: "none", className: cc(["react-flow__edge-path", props.className]) }), interactionWidth && jsxRuntime.jsx("path", { d: path, fill: "none", strokeOpacity: 0, strokeWidth: interactionWidth, className: "react-flow__edge-interaction" }), label && system.isNumeric(labelX) && system.isNumeric(labelY) ? jsxRuntime.jsx(EdgeText, { x: labelX, y: labelY, label, labelStyle, labelShowBg, labelBgStyle, labelBgPadding, labelBgBorderRadius }) : null] });
  1729. }
  1730. function getControl({ pos, x1, y1, x2, y2 }) {
  1731. if (pos === system.Position.Left || pos === system.Position.Right) {
  1732. return [0.5 * (x1 + x2), y1];
  1733. }
  1734. return [x1, 0.5 * (y1 + y2)];
  1735. }
  1736. function getSimpleBezierPath({ sourceX, sourceY, sourcePosition = system.Position.Bottom, targetX, targetY, targetPosition = system.Position.Top }) {
  1737. const [sourceControlX, sourceControlY] = getControl({
  1738. pos: sourcePosition,
  1739. x1: sourceX,
  1740. y1: sourceY,
  1741. x2: targetX,
  1742. y2: targetY
  1743. });
  1744. const [targetControlX, targetControlY] = getControl({
  1745. pos: targetPosition,
  1746. x1: targetX,
  1747. y1: targetY,
  1748. x2: sourceX,
  1749. y2: sourceY
  1750. });
  1751. const [labelX, labelY, offsetX, offsetY] = system.getBezierEdgeCenter({
  1752. sourceX,
  1753. sourceY,
  1754. targetX,
  1755. targetY,
  1756. sourceControlX,
  1757. sourceControlY,
  1758. targetControlX,
  1759. targetControlY
  1760. });
  1761. return [
  1762. `M${sourceX},${sourceY} C${sourceControlX},${sourceControlY} ${targetControlX},${targetControlY} ${targetX},${targetY}`,
  1763. labelX,
  1764. labelY,
  1765. offsetX,
  1766. offsetY
  1767. ];
  1768. }
  1769. function createSimpleBezierEdge(params) {
  1770. return react.memo(({ id, sourceX, sourceY, targetX, targetY, sourcePosition = system.Position.Bottom, targetPosition = system.Position.Top, label, labelStyle, labelShowBg, labelBgStyle, labelBgPadding, labelBgBorderRadius, style: style2, markerEnd, markerStart, interactionWidth }) => {
  1771. const [path, labelX, labelY] = getSimpleBezierPath({
  1772. sourceX,
  1773. sourceY,
  1774. sourcePosition,
  1775. targetX,
  1776. targetY,
  1777. targetPosition
  1778. });
  1779. const _id = params.isInternal ? void 0 : id;
  1780. return jsxRuntime.jsx(BaseEdge, { id: _id, path, labelX, labelY, label, labelStyle, labelShowBg, labelBgStyle, labelBgPadding, labelBgBorderRadius, style: style2, markerEnd, markerStart, interactionWidth });
  1781. });
  1782. }
  1783. var SimpleBezierEdge = createSimpleBezierEdge({ isInternal: false });
  1784. var SimpleBezierEdgeInternal = createSimpleBezierEdge({ isInternal: true });
  1785. SimpleBezierEdge.displayName = "SimpleBezierEdge";
  1786. SimpleBezierEdgeInternal.displayName = "SimpleBezierEdgeInternal";
  1787. function createSmoothStepEdge(params) {
  1788. return react.memo(({ id, sourceX, sourceY, targetX, targetY, label, labelStyle, labelShowBg, labelBgStyle, labelBgPadding, labelBgBorderRadius, style: style2, sourcePosition = system.Position.Bottom, targetPosition = system.Position.Top, markerEnd, markerStart, pathOptions, interactionWidth }) => {
  1789. const [path, labelX, labelY] = system.getSmoothStepPath({
  1790. sourceX,
  1791. sourceY,
  1792. sourcePosition,
  1793. targetX,
  1794. targetY,
  1795. targetPosition,
  1796. borderRadius: pathOptions?.borderRadius,
  1797. offset: pathOptions?.offset
  1798. });
  1799. const _id = params.isInternal ? void 0 : id;
  1800. return jsxRuntime.jsx(BaseEdge, { id: _id, path, labelX, labelY, label, labelStyle, labelShowBg, labelBgStyle, labelBgPadding, labelBgBorderRadius, style: style2, markerEnd, markerStart, interactionWidth });
  1801. });
  1802. }
  1803. var SmoothStepEdge = createSmoothStepEdge({ isInternal: false });
  1804. var SmoothStepEdgeInternal = createSmoothStepEdge({ isInternal: true });
  1805. SmoothStepEdge.displayName = "SmoothStepEdge";
  1806. SmoothStepEdgeInternal.displayName = "SmoothStepEdgeInternal";
  1807. function createStepEdge(params) {
  1808. return react.memo(({ id, ...props }) => {
  1809. const _id = params.isInternal ? void 0 : id;
  1810. return jsxRuntime.jsx(SmoothStepEdge, { ...props, id: _id, pathOptions: react.useMemo(() => ({ borderRadius: 0, offset: props.pathOptions?.offset }), [props.pathOptions?.offset]) });
  1811. });
  1812. }
  1813. var StepEdge = createStepEdge({ isInternal: false });
  1814. var StepEdgeInternal = createStepEdge({ isInternal: true });
  1815. StepEdge.displayName = "StepEdge";
  1816. StepEdgeInternal.displayName = "StepEdgeInternal";
  1817. function createStraightEdge(params) {
  1818. return react.memo(({ id, sourceX, sourceY, targetX, targetY, label, labelStyle, labelShowBg, labelBgStyle, labelBgPadding, labelBgBorderRadius, style: style2, markerEnd, markerStart, interactionWidth }) => {
  1819. const [path, labelX, labelY] = system.getStraightPath({ sourceX, sourceY, targetX, targetY });
  1820. const _id = params.isInternal ? void 0 : id;
  1821. return jsxRuntime.jsx(BaseEdge, { id: _id, path, labelX, labelY, label, labelStyle, labelShowBg, labelBgStyle, labelBgPadding, labelBgBorderRadius, style: style2, markerEnd, markerStart, interactionWidth });
  1822. });
  1823. }
  1824. var StraightEdge = createStraightEdge({ isInternal: false });
  1825. var StraightEdgeInternal = createStraightEdge({ isInternal: true });
  1826. StraightEdge.displayName = "StraightEdge";
  1827. StraightEdgeInternal.displayName = "StraightEdgeInternal";
  1828. function createBezierEdge(params) {
  1829. return react.memo(({ id, sourceX, sourceY, targetX, targetY, sourcePosition = system.Position.Bottom, targetPosition = system.Position.Top, label, labelStyle, labelShowBg, labelBgStyle, labelBgPadding, labelBgBorderRadius, style: style2, markerEnd, markerStart, pathOptions, interactionWidth }) => {
  1830. const [path, labelX, labelY] = system.getBezierPath({
  1831. sourceX,
  1832. sourceY,
  1833. sourcePosition,
  1834. targetX,
  1835. targetY,
  1836. targetPosition,
  1837. curvature: pathOptions?.curvature
  1838. });
  1839. const _id = params.isInternal ? void 0 : id;
  1840. return jsxRuntime.jsx(BaseEdge, { id: _id, path, labelX, labelY, label, labelStyle, labelShowBg, labelBgStyle, labelBgPadding, labelBgBorderRadius, style: style2, markerEnd, markerStart, interactionWidth });
  1841. });
  1842. }
  1843. var BezierEdge = createBezierEdge({ isInternal: false });
  1844. var BezierEdgeInternal = createBezierEdge({ isInternal: true });
  1845. BezierEdge.displayName = "BezierEdge";
  1846. BezierEdgeInternal.displayName = "BezierEdgeInternal";
  1847. var builtinEdgeTypes = {
  1848. default: BezierEdgeInternal,
  1849. straight: StraightEdgeInternal,
  1850. step: StepEdgeInternal,
  1851. smoothstep: SmoothStepEdgeInternal,
  1852. simplebezier: SimpleBezierEdgeInternal
  1853. };
  1854. var nullPosition = {
  1855. sourceX: null,
  1856. sourceY: null,
  1857. targetX: null,
  1858. targetY: null,
  1859. sourcePosition: null,
  1860. targetPosition: null
  1861. };
  1862. var shiftX = (x, shift, position) => {
  1863. if (position === system.Position.Left)
  1864. return x - shift;
  1865. if (position === system.Position.Right)
  1866. return x + shift;
  1867. return x;
  1868. };
  1869. var shiftY = (y, shift, position) => {
  1870. if (position === system.Position.Top)
  1871. return y - shift;
  1872. if (position === system.Position.Bottom)
  1873. return y + shift;
  1874. return y;
  1875. };
  1876. var EdgeUpdaterClassName = "react-flow__edgeupdater";
  1877. function EdgeAnchor({ position, centerX, centerY, radius = 10, onMouseDown, onMouseEnter, onMouseOut, type }) {
  1878. return jsxRuntime.jsx("circle", { onMouseDown, onMouseEnter, onMouseOut, className: cc([EdgeUpdaterClassName, `${EdgeUpdaterClassName}-${type}`]), cx: shiftX(centerX, radius, position), cy: shiftY(centerY, radius, position), r: radius, stroke: "transparent", fill: "transparent" });
  1879. }
  1880. function EdgeUpdateAnchors({ isReconnectable, reconnectRadius, edge, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, onReconnect, onReconnectStart, onReconnectEnd, setReconnecting, setUpdateHover }) {
  1881. const store = useStoreApi();
  1882. const handleEdgeUpdater = (event, oppositeHandle) => {
  1883. if (event.button !== 0) {
  1884. return;
  1885. }
  1886. const { autoPanOnConnect, domNode, isValidConnection, connectionMode, connectionRadius, lib, onConnectStart, onConnectEnd, cancelConnection, nodeLookup, rfId: flowId, panBy: panBy2, updateConnection } = store.getState();
  1887. const isTarget = oppositeHandle.type === "target";
  1888. setReconnecting(true);
  1889. onReconnectStart?.(event, edge, oppositeHandle.type);
  1890. const _onReconnectEnd = (evt, connectionState) => {
  1891. setReconnecting(false);
  1892. onReconnectEnd?.(evt, edge, oppositeHandle.type, connectionState);
  1893. };
  1894. const onConnectEdge = (connection) => onReconnect?.(edge, connection);
  1895. system.XYHandle.onPointerDown(event.nativeEvent, {
  1896. autoPanOnConnect,
  1897. connectionMode,
  1898. connectionRadius,
  1899. domNode,
  1900. handleId: oppositeHandle.id,
  1901. nodeId: oppositeHandle.nodeId,
  1902. nodeLookup,
  1903. isTarget,
  1904. edgeUpdaterType: oppositeHandle.type,
  1905. lib,
  1906. flowId,
  1907. cancelConnection,
  1908. panBy: panBy2,
  1909. isValidConnection,
  1910. onConnect: onConnectEdge,
  1911. onConnectStart,
  1912. onConnectEnd,
  1913. onReconnectEnd: _onReconnectEnd,
  1914. updateConnection,
  1915. getTransform: () => store.getState().transform,
  1916. getFromHandle: () => store.getState().connection.fromHandle
  1917. });
  1918. };
  1919. const onReconnectSourceMouseDown = (event) => handleEdgeUpdater(event, { nodeId: edge.target, id: edge.targetHandle ?? null, type: "target" });
  1920. const onReconnectTargetMouseDown = (event) => handleEdgeUpdater(event, { nodeId: edge.source, id: edge.sourceHandle ?? null, type: "source" });
  1921. const onReconnectMouseEnter = () => setUpdateHover(true);
  1922. const onReconnectMouseOut = () => setUpdateHover(false);
  1923. return jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [(isReconnectable === true || isReconnectable === "source") && jsxRuntime.jsx(EdgeAnchor, { position: sourcePosition, centerX: sourceX, centerY: sourceY, radius: reconnectRadius, onMouseDown: onReconnectSourceMouseDown, onMouseEnter: onReconnectMouseEnter, onMouseOut: onReconnectMouseOut, type: "source" }), (isReconnectable === true || isReconnectable === "target") && jsxRuntime.jsx(EdgeAnchor, { position: targetPosition, centerX: targetX, centerY: targetY, radius: reconnectRadius, onMouseDown: onReconnectTargetMouseDown, onMouseEnter: onReconnectMouseEnter, onMouseOut: onReconnectMouseOut, type: "target" })] });
  1924. }
  1925. function EdgeWrapper({ id, edgesFocusable, edgesReconnectable, elementsSelectable, onClick, onDoubleClick, onContextMenu, onMouseEnter, onMouseMove, onMouseLeave, reconnectRadius, onReconnect, onReconnectStart, onReconnectEnd, rfId, edgeTypes, noPanClassName, onError, disableKeyboardA11y }) {
  1926. let edge = useStore((s) => s.edgeLookup.get(id));
  1927. const defaultEdgeOptions = useStore((s) => s.defaultEdgeOptions);
  1928. edge = defaultEdgeOptions ? { ...defaultEdgeOptions, ...edge } : edge;
  1929. let edgeType = edge.type || "default";
  1930. let EdgeComponent = edgeTypes?.[edgeType] || builtinEdgeTypes[edgeType];
  1931. if (EdgeComponent === void 0) {
  1932. onError?.("011", system.errorMessages["error011"](edgeType));
  1933. edgeType = "default";
  1934. EdgeComponent = builtinEdgeTypes.default;
  1935. }
  1936. const isFocusable = !!(edge.focusable || edgesFocusable && typeof edge.focusable === "undefined");
  1937. const isReconnectable = typeof onReconnect !== "undefined" && (edge.reconnectable || edgesReconnectable && typeof edge.reconnectable === "undefined");
  1938. const isSelectable = !!(edge.selectable || elementsSelectable && typeof edge.selectable === "undefined");
  1939. const edgeRef = react.useRef(null);
  1940. const [updateHover, setUpdateHover] = react.useState(false);
  1941. const [reconnecting, setReconnecting] = react.useState(false);
  1942. const store = useStoreApi();
  1943. const { zIndex, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition } = useStore(react.useCallback((store2) => {
  1944. const sourceNode = store2.nodeLookup.get(edge.source);
  1945. const targetNode = store2.nodeLookup.get(edge.target);
  1946. if (!sourceNode || !targetNode) {
  1947. return {
  1948. zIndex: edge.zIndex,
  1949. ...nullPosition
  1950. };
  1951. }
  1952. const edgePosition = system.getEdgePosition({
  1953. id,
  1954. sourceNode,
  1955. targetNode,
  1956. sourceHandle: edge.sourceHandle || null,
  1957. targetHandle: edge.targetHandle || null,
  1958. connectionMode: store2.connectionMode,
  1959. onError
  1960. });
  1961. const zIndex2 = system.getElevatedEdgeZIndex({
  1962. selected: edge.selected,
  1963. zIndex: edge.zIndex,
  1964. sourceNode,
  1965. targetNode,
  1966. elevateOnSelect: store2.elevateEdgesOnSelect
  1967. });
  1968. return {
  1969. zIndex: zIndex2,
  1970. ...edgePosition || nullPosition
  1971. };
  1972. }, [edge.source, edge.target, edge.sourceHandle, edge.targetHandle, edge.selected, edge.zIndex]), shallow.shallow);
  1973. const markerStartUrl = react.useMemo(() => edge.markerStart ? `url('#${system.getMarkerId(edge.markerStart, rfId)}')` : void 0, [edge.markerStart, rfId]);
  1974. const markerEndUrl = react.useMemo(() => edge.markerEnd ? `url('#${system.getMarkerId(edge.markerEnd, rfId)}')` : void 0, [edge.markerEnd, rfId]);
  1975. if (edge.hidden || sourceX === null || sourceY === null || targetX === null || targetY === null) {
  1976. return null;
  1977. }
  1978. const onEdgeClick = (event) => {
  1979. const { addSelectedEdges, unselectNodesAndEdges, multiSelectionActive } = store.getState();
  1980. if (isSelectable) {
  1981. store.setState({ nodesSelectionActive: false });
  1982. if (edge.selected && multiSelectionActive) {
  1983. unselectNodesAndEdges({ nodes: [], edges: [edge] });
  1984. edgeRef.current?.blur();
  1985. } else {
  1986. addSelectedEdges([id]);
  1987. }
  1988. }
  1989. if (onClick) {
  1990. onClick(event, edge);
  1991. }
  1992. };
  1993. const onEdgeDoubleClick = onDoubleClick ? (event) => {
  1994. onDoubleClick(event, { ...edge });
  1995. } : void 0;
  1996. const onEdgeContextMenu = onContextMenu ? (event) => {
  1997. onContextMenu(event, { ...edge });
  1998. } : void 0;
  1999. const onEdgeMouseEnter = onMouseEnter ? (event) => {
  2000. onMouseEnter(event, { ...edge });
  2001. } : void 0;
  2002. const onEdgeMouseMove = onMouseMove ? (event) => {
  2003. onMouseMove(event, { ...edge });
  2004. } : void 0;
  2005. const onEdgeMouseLeave = onMouseLeave ? (event) => {
  2006. onMouseLeave(event, { ...edge });
  2007. } : void 0;
  2008. const onKeyDown = (event) => {
  2009. if (!disableKeyboardA11y && system.elementSelectionKeys.includes(event.key) && isSelectable) {
  2010. const { unselectNodesAndEdges, addSelectedEdges } = store.getState();
  2011. const unselect = event.key === "Escape";
  2012. if (unselect) {
  2013. edgeRef.current?.blur();
  2014. unselectNodesAndEdges({ edges: [edge] });
  2015. } else {
  2016. addSelectedEdges([id]);
  2017. }
  2018. }
  2019. };
  2020. return jsxRuntime.jsx("svg", { style: { zIndex }, children: jsxRuntime.jsxs("g", { className: cc([
  2021. "react-flow__edge",
  2022. `react-flow__edge-${edgeType}`,
  2023. edge.className,
  2024. noPanClassName,
  2025. {
  2026. selected: edge.selected,
  2027. animated: edge.animated,
  2028. inactive: !isSelectable && !onClick,
  2029. updating: updateHover,
  2030. selectable: isSelectable
  2031. }
  2032. ]), onClick: onEdgeClick, onDoubleClick: onEdgeDoubleClick, onContextMenu: onEdgeContextMenu, onMouseEnter: onEdgeMouseEnter, onMouseMove: onEdgeMouseMove, onMouseLeave: onEdgeMouseLeave, onKeyDown: isFocusable ? onKeyDown : void 0, tabIndex: isFocusable ? 0 : void 0, role: isFocusable ? "button" : "img", "data-id": id, "data-testid": `rf__edge-${id}`, "aria-label": edge.ariaLabel === null ? void 0 : edge.ariaLabel || `Edge from ${edge.source} to ${edge.target}`, "aria-describedby": isFocusable ? `${ARIA_EDGE_DESC_KEY}-${rfId}` : void 0, ref: edgeRef, children: [!reconnecting && jsxRuntime.jsx(EdgeComponent, { id, source: edge.source, target: edge.target, type: edge.type, selected: edge.selected, animated: edge.animated, selectable: isSelectable, deletable: edge.deletable ?? true, label: edge.label, labelStyle: edge.labelStyle, labelShowBg: edge.labelShowBg, labelBgStyle: edge.labelBgStyle, labelBgPadding: edge.labelBgPadding, labelBgBorderRadius: edge.labelBgBorderRadius, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, data: edge.data, style: edge.style, sourceHandleId: edge.sourceHandle, targetHandleId: edge.targetHandle, markerStart: markerStartUrl, markerEnd: markerEndUrl, pathOptions: "pathOptions" in edge ? edge.pathOptions : void 0, interactionWidth: edge.interactionWidth }), isReconnectable && jsxRuntime.jsx(EdgeUpdateAnchors, { edge, isReconnectable, reconnectRadius, onReconnect, onReconnectStart, onReconnectEnd, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, setUpdateHover, setReconnecting })] }) });
  2033. }
  2034. var selector$a = (s) => ({
  2035. edgesFocusable: s.edgesFocusable,
  2036. edgesReconnectable: s.edgesReconnectable,
  2037. elementsSelectable: s.elementsSelectable,
  2038. connectionMode: s.connectionMode,
  2039. onError: s.onError
  2040. });
  2041. function EdgeRendererComponent({ defaultMarkerColor, onlyRenderVisibleElements, rfId, edgeTypes, noPanClassName, onReconnect, onEdgeContextMenu, onEdgeMouseEnter, onEdgeMouseMove, onEdgeMouseLeave, onEdgeClick, reconnectRadius, onEdgeDoubleClick, onReconnectStart, onReconnectEnd, disableKeyboardA11y }) {
  2042. const { edgesFocusable, edgesReconnectable, elementsSelectable, onError } = useStore(selector$a, shallow.shallow);
  2043. const edgeIds = useVisibleEdgeIds(onlyRenderVisibleElements);
  2044. return jsxRuntime.jsxs("div", { className: "react-flow__edges", children: [jsxRuntime.jsx(MarkerDefinitions$1, { defaultColor: defaultMarkerColor, rfId }), edgeIds.map((id) => {
  2045. return jsxRuntime.jsx(EdgeWrapper, { id, edgesFocusable, edgesReconnectable, elementsSelectable, noPanClassName, onReconnect, onContextMenu: onEdgeContextMenu, onMouseEnter: onEdgeMouseEnter, onMouseMove: onEdgeMouseMove, onMouseLeave: onEdgeMouseLeave, onClick: onEdgeClick, reconnectRadius, onDoubleClick: onEdgeDoubleClick, onReconnectStart, onReconnectEnd, rfId, onError, edgeTypes, disableKeyboardA11y }, id);
  2046. })] });
  2047. }
  2048. EdgeRendererComponent.displayName = "EdgeRenderer";
  2049. var EdgeRenderer = react.memo(EdgeRendererComponent);
  2050. var selector$9 = (s) => `translate(${s.transform[0]}px,${s.transform[1]}px) scale(${s.transform[2]})`;
  2051. function Viewport({ children }) {
  2052. const transform = useStore(selector$9);
  2053. return jsxRuntime.jsx("div", { className: "react-flow__viewport xyflow__viewport react-flow__container", style: { transform }, children });
  2054. }
  2055. function useOnInitHandler(onInit) {
  2056. const rfInstance = useReactFlow();
  2057. const isInitialized = react.useRef(false);
  2058. react.useEffect(() => {
  2059. if (!isInitialized.current && rfInstance.viewportInitialized && onInit) {
  2060. setTimeout(() => onInit(rfInstance), 1);
  2061. isInitialized.current = true;
  2062. }
  2063. }, [onInit, rfInstance.viewportInitialized]);
  2064. }
  2065. var selector$8 = (state) => state.panZoom?.syncViewport;
  2066. function useViewportSync(viewport) {
  2067. const syncViewport = useStore(selector$8);
  2068. const store = useStoreApi();
  2069. react.useEffect(() => {
  2070. if (viewport) {
  2071. syncViewport?.(viewport);
  2072. store.setState({ transform: [viewport.x, viewport.y, viewport.zoom] });
  2073. }
  2074. }, [viewport, syncViewport]);
  2075. return null;
  2076. }
  2077. function storeSelector$1(s) {
  2078. return s.connection.inProgress ? { ...s.connection, to: system.pointToRendererPoint(s.connection.to, s.transform) } : { ...s.connection };
  2079. }
  2080. function getSelector(connectionSelector) {
  2081. if (connectionSelector) {
  2082. const combinedSelector = (s) => {
  2083. const connection = storeSelector$1(s);
  2084. return connectionSelector(connection);
  2085. };
  2086. return combinedSelector;
  2087. }
  2088. return storeSelector$1;
  2089. }
  2090. function useConnection(connectionSelector) {
  2091. const combinedSelector = getSelector(connectionSelector);
  2092. return useStore(combinedSelector, shallow.shallow);
  2093. }
  2094. var selector$7 = (s) => ({
  2095. nodesConnectable: s.nodesConnectable,
  2096. isValid: s.connection.isValid,
  2097. inProgress: s.connection.inProgress,
  2098. width: s.width,
  2099. height: s.height
  2100. });
  2101. function ConnectionLineWrapper({ containerStyle: containerStyle2, style: style2, type, component }) {
  2102. const { nodesConnectable, width, height, isValid, inProgress } = useStore(selector$7, shallow.shallow);
  2103. const renderConnection = !!(width && nodesConnectable && inProgress);
  2104. if (!renderConnection) {
  2105. return null;
  2106. }
  2107. return jsxRuntime.jsx("svg", { style: containerStyle2, width, height, className: "react-flow__connectionline react-flow__container", children: jsxRuntime.jsx("g", { className: cc(["react-flow__connection", system.getConnectionStatus(isValid)]), children: jsxRuntime.jsx(ConnectionLine, { style: style2, type, CustomComponent: component, isValid }) }) });
  2108. }
  2109. var ConnectionLine = ({ style: style2, type = system.ConnectionLineType.Bezier, CustomComponent, isValid }) => {
  2110. const { inProgress, from, fromNode, fromHandle, fromPosition, to, toNode, toHandle, toPosition } = useConnection();
  2111. if (!inProgress) {
  2112. return;
  2113. }
  2114. if (CustomComponent) {
  2115. return jsxRuntime.jsx(CustomComponent, { connectionLineType: type, connectionLineStyle: style2, fromNode, fromHandle, fromX: from.x, fromY: from.y, toX: to.x, toY: to.y, fromPosition, toPosition, connectionStatus: system.getConnectionStatus(isValid), toNode, toHandle });
  2116. }
  2117. let path = "";
  2118. const pathParams = {
  2119. sourceX: from.x,
  2120. sourceY: from.y,
  2121. sourcePosition: fromPosition,
  2122. targetX: to.x,
  2123. targetY: to.y,
  2124. targetPosition: toPosition
  2125. };
  2126. switch (type) {
  2127. case system.ConnectionLineType.Bezier:
  2128. [path] = system.getBezierPath(pathParams);
  2129. break;
  2130. case system.ConnectionLineType.SimpleBezier:
  2131. [path] = getSimpleBezierPath(pathParams);
  2132. break;
  2133. case system.ConnectionLineType.Step:
  2134. [path] = system.getSmoothStepPath({
  2135. ...pathParams,
  2136. borderRadius: 0
  2137. });
  2138. break;
  2139. case system.ConnectionLineType.SmoothStep:
  2140. [path] = system.getSmoothStepPath(pathParams);
  2141. break;
  2142. default:
  2143. [path] = system.getStraightPath(pathParams);
  2144. }
  2145. return jsxRuntime.jsx("path", { d: path, fill: "none", className: "react-flow__connection-path", style: style2 });
  2146. };
  2147. ConnectionLine.displayName = "ConnectionLine";
  2148. var emptyTypes = {};
  2149. function useNodeOrEdgeTypesWarning(nodeOrEdgeTypes = emptyTypes) {
  2150. const typesRef = react.useRef(nodeOrEdgeTypes);
  2151. const store = useStoreApi();
  2152. react.useEffect(() => {
  2153. {
  2154. const usedKeys = new Set([...Object.keys(typesRef.current), ...Object.keys(nodeOrEdgeTypes)]);
  2155. for (const key of usedKeys) {
  2156. if (typesRef.current[key] !== nodeOrEdgeTypes[key]) {
  2157. store.getState().onError?.("002", system.errorMessages["error002"]());
  2158. break;
  2159. }
  2160. }
  2161. typesRef.current = nodeOrEdgeTypes;
  2162. }
  2163. }, [nodeOrEdgeTypes]);
  2164. }
  2165. function useStylesLoadedWarning() {
  2166. const store = useStoreApi();
  2167. const checked = react.useRef(false);
  2168. react.useEffect(() => {
  2169. {
  2170. if (!checked.current) {
  2171. const pane = document.querySelector(".react-flow__pane");
  2172. if (pane && !(window.getComputedStyle(pane).zIndex === "1")) {
  2173. store.getState().onError?.("013", system.errorMessages["error013"]("react"));
  2174. }
  2175. checked.current = true;
  2176. }
  2177. }
  2178. }, []);
  2179. }
  2180. function GraphViewComponent({ nodeTypes, edgeTypes, onInit, onNodeClick, onEdgeClick, onNodeDoubleClick, onEdgeDoubleClick, onNodeMouseEnter, onNodeMouseMove, onNodeMouseLeave, onNodeContextMenu, onSelectionContextMenu, onSelectionStart, onSelectionEnd, connectionLineType, connectionLineStyle, connectionLineComponent, connectionLineContainerStyle, selectionKeyCode, selectionOnDrag, selectionMode, multiSelectionKeyCode, panActivationKeyCode, zoomActivationKeyCode, deleteKeyCode, onlyRenderVisibleElements, elementsSelectable, defaultViewport: defaultViewport2, translateExtent, minZoom, maxZoom, preventScrolling, defaultMarkerColor, zoomOnScroll, zoomOnPinch, panOnScroll, panOnScrollSpeed, panOnScrollMode, zoomOnDoubleClick, panOnDrag, onPaneClick, onPaneMouseEnter, onPaneMouseMove, onPaneMouseLeave, onPaneScroll, onPaneContextMenu, paneClickDistance, nodeClickDistance, onEdgeContextMenu, onEdgeMouseEnter, onEdgeMouseMove, onEdgeMouseLeave, reconnectRadius, onReconnect, onReconnectStart, onReconnectEnd, noDragClassName, noWheelClassName, noPanClassName, disableKeyboardA11y, nodeExtent, rfId, viewport, onViewportChange }) {
  2181. useNodeOrEdgeTypesWarning(nodeTypes);
  2182. useNodeOrEdgeTypesWarning(edgeTypes);
  2183. useStylesLoadedWarning();
  2184. useOnInitHandler(onInit);
  2185. useViewportSync(viewport);
  2186. return jsxRuntime.jsx(FlowRenderer, { onPaneClick, onPaneMouseEnter, onPaneMouseMove, onPaneMouseLeave, onPaneContextMenu, onPaneScroll, paneClickDistance, deleteKeyCode, selectionKeyCode, selectionOnDrag, selectionMode, onSelectionStart, onSelectionEnd, multiSelectionKeyCode, panActivationKeyCode, zoomActivationKeyCode, elementsSelectable, zoomOnScroll, zoomOnPinch, zoomOnDoubleClick, panOnScroll, panOnScrollSpeed, panOnScrollMode, panOnDrag, defaultViewport: defaultViewport2, translateExtent, minZoom, maxZoom, onSelectionContextMenu, preventScrolling, noDragClassName, noWheelClassName, noPanClassName, disableKeyboardA11y, onViewportChange, isControlledViewport: !!viewport, children: jsxRuntime.jsxs(Viewport, { children: [jsxRuntime.jsx(EdgeRenderer, { edgeTypes, onEdgeClick, onEdgeDoubleClick, onReconnect, onReconnectStart, onReconnectEnd, onlyRenderVisibleElements, onEdgeContextMenu, onEdgeMouseEnter, onEdgeMouseMove, onEdgeMouseLeave, reconnectRadius, defaultMarkerColor, noPanClassName, disableKeyboardA11y, rfId }), jsxRuntime.jsx(ConnectionLineWrapper, { style: connectionLineStyle, type: connectionLineType, component: connectionLineComponent, containerStyle: connectionLineContainerStyle }), jsxRuntime.jsx("div", { className: "react-flow__edgelabel-renderer" }), jsxRuntime.jsx(NodeRenderer, { nodeTypes, onNodeClick, onNodeDoubleClick, onNodeMouseEnter, onNodeMouseMove, onNodeMouseLeave, onNodeContextMenu, nodeClickDistance, onlyRenderVisibleElements, noPanClassName, noDragClassName, disableKeyboardA11y, nodeExtent, rfId }), jsxRuntime.jsx("div", { className: "react-flow__viewport-portal" })] }) });
  2187. }
  2188. GraphViewComponent.displayName = "GraphView";
  2189. var GraphView = react.memo(GraphViewComponent);
  2190. var getInitialState = ({ nodes, edges, defaultNodes, defaultEdges, width, height, fitView: fitView2, nodeOrigin, nodeExtent } = {}) => {
  2191. const nodeLookup = new Map();
  2192. const parentLookup = new Map();
  2193. const connectionLookup = new Map();
  2194. const edgeLookup = new Map();
  2195. const storeEdges = defaultEdges ?? edges ?? [];
  2196. const storeNodes = defaultNodes ?? nodes ?? [];
  2197. const storeNodeOrigin = nodeOrigin ?? [0, 0];
  2198. const storeNodeExtent = nodeExtent ?? system.infiniteExtent;
  2199. system.updateConnectionLookup(connectionLookup, edgeLookup, storeEdges);
  2200. system.adoptUserNodes(storeNodes, nodeLookup, parentLookup, {
  2201. nodeOrigin: storeNodeOrigin,
  2202. nodeExtent: storeNodeExtent,
  2203. elevateNodesOnSelect: false
  2204. });
  2205. let transform = [0, 0, 1];
  2206. if (fitView2 && width && height) {
  2207. const bounds = system.getInternalNodesBounds(nodeLookup, {
  2208. filter: (node) => !!((node.width || node.initialWidth) && (node.height || node.initialHeight))
  2209. });
  2210. const { x, y, zoom } = system.getViewportForBounds(bounds, width, height, 0.5, 2, 0.1);
  2211. transform = [x, y, zoom];
  2212. }
  2213. return {
  2214. rfId: "1",
  2215. width: 0,
  2216. height: 0,
  2217. transform,
  2218. nodes: storeNodes,
  2219. nodeLookup,
  2220. parentLookup,
  2221. edges: storeEdges,
  2222. edgeLookup,
  2223. connectionLookup,
  2224. onNodesChange: null,
  2225. onEdgesChange: null,
  2226. hasDefaultNodes: defaultNodes !== void 0,
  2227. hasDefaultEdges: defaultEdges !== void 0,
  2228. panZoom: null,
  2229. minZoom: 0.5,
  2230. maxZoom: 2,
  2231. translateExtent: system.infiniteExtent,
  2232. nodeExtent: storeNodeExtent,
  2233. nodesSelectionActive: false,
  2234. userSelectionActive: false,
  2235. userSelectionRect: null,
  2236. connectionMode: system.ConnectionMode.Strict,
  2237. domNode: null,
  2238. paneDragging: false,
  2239. noPanClassName: "nopan",
  2240. nodeOrigin: storeNodeOrigin,
  2241. nodeDragThreshold: 1,
  2242. snapGrid: [15, 15],
  2243. snapToGrid: false,
  2244. nodesDraggable: true,
  2245. nodesConnectable: true,
  2246. nodesFocusable: true,
  2247. edgesFocusable: true,
  2248. edgesReconnectable: true,
  2249. elementsSelectable: true,
  2250. elevateNodesOnSelect: true,
  2251. elevateEdgesOnSelect: false,
  2252. fitViewOnInit: false,
  2253. fitViewDone: false,
  2254. fitViewOnInitOptions: void 0,
  2255. selectNodesOnDrag: true,
  2256. multiSelectionActive: false,
  2257. connection: { ...system.initialConnection },
  2258. connectionClickStartHandle: null,
  2259. connectOnClick: true,
  2260. ariaLiveMessage: "",
  2261. autoPanOnConnect: true,
  2262. autoPanOnNodeDrag: true,
  2263. autoPanSpeed: 15,
  2264. connectionRadius: 20,
  2265. onError: system.devWarn,
  2266. isValidConnection: void 0,
  2267. onSelectionChangeHandlers: [],
  2268. lib: "react",
  2269. debug: false
  2270. };
  2271. };
  2272. var createStore = ({ nodes, edges, defaultNodes, defaultEdges, width, height, fitView: fitView$1, nodeOrigin, nodeExtent }) => traditional.createWithEqualityFn((set, get) => ({
  2273. ...getInitialState({ nodes, edges, width, height, fitView: fitView$1, nodeOrigin, nodeExtent, defaultNodes, defaultEdges }),
  2274. setNodes: (nodes2) => {
  2275. const { nodeLookup, parentLookup, nodeOrigin: nodeOrigin2, elevateNodesOnSelect } = get();
  2276. system.adoptUserNodes(nodes2, nodeLookup, parentLookup, {
  2277. nodeOrigin: nodeOrigin2,
  2278. nodeExtent,
  2279. elevateNodesOnSelect,
  2280. checkEquality: true
  2281. });
  2282. set({ nodes: nodes2 });
  2283. },
  2284. setEdges: (edges2) => {
  2285. const { connectionLookup, edgeLookup } = get();
  2286. system.updateConnectionLookup(connectionLookup, edgeLookup, edges2);
  2287. set({ edges: edges2 });
  2288. },
  2289. setDefaultNodesAndEdges: (nodes2, edges2) => {
  2290. if (nodes2) {
  2291. const { setNodes } = get();
  2292. setNodes(nodes2);
  2293. set({ hasDefaultNodes: true });
  2294. }
  2295. if (edges2) {
  2296. const { setEdges } = get();
  2297. setEdges(edges2);
  2298. set({ hasDefaultEdges: true });
  2299. }
  2300. },
  2301. updateNodeInternals: (updates, params = { triggerFitView: true }) => {
  2302. const { triggerNodeChanges, nodeLookup, parentLookup, fitViewOnInit, fitViewDone, fitViewOnInitOptions, domNode, nodeOrigin: nodeOrigin2, nodeExtent: nodeExtent2, debug, fitViewSync } = get();
  2303. const { changes, updatedInternals } = system.updateNodeInternals(updates, nodeLookup, parentLookup, domNode, nodeOrigin2, nodeExtent2);
  2304. if (!updatedInternals) {
  2305. return;
  2306. }
  2307. system.updateAbsolutePositions(nodeLookup, parentLookup, { nodeOrigin: nodeOrigin2, nodeExtent: nodeExtent2 });
  2308. if (params.triggerFitView) {
  2309. let nextFitViewDone = fitViewDone;
  2310. if (!fitViewDone && fitViewOnInit) {
  2311. nextFitViewDone = fitViewSync({
  2312. ...fitViewOnInitOptions,
  2313. nodes: fitViewOnInitOptions?.nodes
  2314. });
  2315. }
  2316. set({ fitViewDone: nextFitViewDone });
  2317. } else {
  2318. set({});
  2319. }
  2320. if (changes?.length > 0) {
  2321. if (debug) {
  2322. console.log("React Flow: trigger node changes", changes);
  2323. }
  2324. triggerNodeChanges?.(changes);
  2325. }
  2326. },
  2327. updateNodePositions: (nodeDragItems, dragging = false) => {
  2328. const parentExpandChildren = [];
  2329. const changes = [];
  2330. for (const [id, dragItem] of nodeDragItems) {
  2331. const expandParent = !!(dragItem?.expandParent && dragItem?.parentId && dragItem?.position);
  2332. const change = {
  2333. id,
  2334. type: "position",
  2335. position: expandParent ? {
  2336. x: Math.max(0, dragItem.position.x),
  2337. y: Math.max(0, dragItem.position.y)
  2338. } : dragItem.position,
  2339. dragging
  2340. };
  2341. if (expandParent) {
  2342. parentExpandChildren.push({
  2343. id,
  2344. parentId: dragItem.parentId,
  2345. rect: {
  2346. ...dragItem.internals.positionAbsolute,
  2347. width: dragItem.measured.width,
  2348. height: dragItem.measured.height
  2349. }
  2350. });
  2351. }
  2352. changes.push(change);
  2353. }
  2354. if (parentExpandChildren.length > 0) {
  2355. const { nodeLookup, parentLookup, nodeOrigin: nodeOrigin2 } = get();
  2356. const parentExpandChanges = system.handleExpandParent(parentExpandChildren, nodeLookup, parentLookup, nodeOrigin2);
  2357. changes.push(...parentExpandChanges);
  2358. }
  2359. get().triggerNodeChanges(changes);
  2360. },
  2361. triggerNodeChanges: (changes) => {
  2362. const { onNodesChange, setNodes, nodes: nodes2, hasDefaultNodes, debug } = get();
  2363. if (changes?.length) {
  2364. if (hasDefaultNodes) {
  2365. const updatedNodes = applyNodeChanges(changes, nodes2);
  2366. setNodes(updatedNodes);
  2367. }
  2368. if (debug) {
  2369. console.log("React Flow: trigger node changes", changes);
  2370. }
  2371. onNodesChange?.(changes);
  2372. }
  2373. },
  2374. triggerEdgeChanges: (changes) => {
  2375. const { onEdgesChange, setEdges, edges: edges2, hasDefaultEdges, debug } = get();
  2376. if (changes?.length) {
  2377. if (hasDefaultEdges) {
  2378. const updatedEdges = applyEdgeChanges(changes, edges2);
  2379. setEdges(updatedEdges);
  2380. }
  2381. if (debug) {
  2382. console.log("React Flow: trigger edge changes", changes);
  2383. }
  2384. onEdgesChange?.(changes);
  2385. }
  2386. },
  2387. addSelectedNodes: (selectedNodeIds) => {
  2388. const { multiSelectionActive, edgeLookup, nodeLookup, triggerNodeChanges, triggerEdgeChanges } = get();
  2389. if (multiSelectionActive) {
  2390. const nodeChanges = selectedNodeIds.map((nodeId) => createSelectionChange(nodeId, true));
  2391. triggerNodeChanges(nodeChanges);
  2392. return;
  2393. }
  2394. triggerNodeChanges(getSelectionChanges(nodeLookup, new Set([...selectedNodeIds]), true));
  2395. triggerEdgeChanges(getSelectionChanges(edgeLookup));
  2396. },
  2397. addSelectedEdges: (selectedEdgeIds) => {
  2398. const { multiSelectionActive, edgeLookup, nodeLookup, triggerNodeChanges, triggerEdgeChanges } = get();
  2399. if (multiSelectionActive) {
  2400. const changedEdges = selectedEdgeIds.map((edgeId) => createSelectionChange(edgeId, true));
  2401. triggerEdgeChanges(changedEdges);
  2402. return;
  2403. }
  2404. triggerEdgeChanges(getSelectionChanges(edgeLookup, new Set([...selectedEdgeIds])));
  2405. triggerNodeChanges(getSelectionChanges(nodeLookup, new Set(), true));
  2406. },
  2407. unselectNodesAndEdges: ({ nodes: nodes2, edges: edges2 } = {}) => {
  2408. const { edges: storeEdges, nodes: storeNodes, nodeLookup, triggerNodeChanges, triggerEdgeChanges } = get();
  2409. const nodesToUnselect = nodes2 ? nodes2 : storeNodes;
  2410. const edgesToUnselect = edges2 ? edges2 : storeEdges;
  2411. const nodeChanges = nodesToUnselect.map((n) => {
  2412. const internalNode = nodeLookup.get(n.id);
  2413. if (internalNode) {
  2414. internalNode.selected = false;
  2415. }
  2416. return createSelectionChange(n.id, false);
  2417. });
  2418. const edgeChanges = edgesToUnselect.map((edge) => createSelectionChange(edge.id, false));
  2419. triggerNodeChanges(nodeChanges);
  2420. triggerEdgeChanges(edgeChanges);
  2421. },
  2422. setMinZoom: (minZoom) => {
  2423. const { panZoom, maxZoom } = get();
  2424. panZoom?.setScaleExtent([minZoom, maxZoom]);
  2425. set({ minZoom });
  2426. },
  2427. setMaxZoom: (maxZoom) => {
  2428. const { panZoom, minZoom } = get();
  2429. panZoom?.setScaleExtent([minZoom, maxZoom]);
  2430. set({ maxZoom });
  2431. },
  2432. setTranslateExtent: (translateExtent) => {
  2433. get().panZoom?.setTranslateExtent(translateExtent);
  2434. set({ translateExtent });
  2435. },
  2436. setPaneClickDistance: (clickDistance) => {
  2437. get().panZoom?.setClickDistance(clickDistance);
  2438. },
  2439. resetSelectedElements: () => {
  2440. const { edges: edges2, nodes: nodes2, triggerNodeChanges, triggerEdgeChanges } = get();
  2441. const nodeChanges = nodes2.reduce((res, node) => node.selected ? [...res, createSelectionChange(node.id, false)] : res, []);
  2442. const edgeChanges = edges2.reduce((res, edge) => edge.selected ? [...res, createSelectionChange(edge.id, false)] : res, []);
  2443. triggerNodeChanges(nodeChanges);
  2444. triggerEdgeChanges(edgeChanges);
  2445. },
  2446. setNodeExtent: (nextNodeExtent) => {
  2447. const { nodes: nodes2, nodeLookup, parentLookup, nodeOrigin: nodeOrigin2, elevateNodesOnSelect, nodeExtent: nodeExtent2 } = get();
  2448. if (nextNodeExtent[0][0] === nodeExtent2[0][0] && nextNodeExtent[0][1] === nodeExtent2[0][1] && nextNodeExtent[1][0] === nodeExtent2[1][0] && nextNodeExtent[1][1] === nodeExtent2[1][1]) {
  2449. return;
  2450. }
  2451. system.adoptUserNodes(nodes2, nodeLookup, parentLookup, {
  2452. nodeOrigin: nodeOrigin2,
  2453. nodeExtent: nextNodeExtent,
  2454. elevateNodesOnSelect,
  2455. checkEquality: false
  2456. });
  2457. set({ nodeExtent: nextNodeExtent });
  2458. },
  2459. panBy: (delta) => {
  2460. const { transform, width: width2, height: height2, panZoom, translateExtent } = get();
  2461. return system.panBy({ delta, panZoom, transform, translateExtent, width: width2, height: height2 });
  2462. },
  2463. fitView: (options) => {
  2464. const { panZoom, width: width2, height: height2, minZoom, maxZoom, nodeLookup } = get();
  2465. if (!panZoom) {
  2466. return Promise.resolve(false);
  2467. }
  2468. const fitViewNodes = system.getFitViewNodes(nodeLookup, options);
  2469. return system.fitView({
  2470. nodes: fitViewNodes,
  2471. width: width2,
  2472. height: height2,
  2473. panZoom,
  2474. minZoom,
  2475. maxZoom
  2476. }, options);
  2477. },
  2478. fitViewSync: (options) => {
  2479. const { panZoom, width: width2, height: height2, minZoom, maxZoom, nodeLookup } = get();
  2480. if (!panZoom) {
  2481. return false;
  2482. }
  2483. const fitViewNodes = system.getFitViewNodes(nodeLookup, options);
  2484. system.fitView({
  2485. nodes: fitViewNodes,
  2486. width: width2,
  2487. height: height2,
  2488. panZoom,
  2489. minZoom,
  2490. maxZoom
  2491. }, options);
  2492. return fitViewNodes.size > 0;
  2493. },
  2494. cancelConnection: () => {
  2495. set({
  2496. connection: { ...system.initialConnection }
  2497. });
  2498. },
  2499. updateConnection: (connection) => {
  2500. set({ connection });
  2501. },
  2502. reset: () => set({ ...getInitialState() })
  2503. }), Object.is);
  2504. function ReactFlowProvider({ initialNodes: nodes, initialEdges: edges, defaultNodes, defaultEdges, initialWidth: width, initialHeight: height, fitView: fitView2, nodeOrigin, nodeExtent, children }) {
  2505. const [store] = react.useState(() => createStore({
  2506. nodes,
  2507. edges,
  2508. defaultNodes,
  2509. defaultEdges,
  2510. width,
  2511. height,
  2512. fitView: fitView2,
  2513. nodeOrigin,
  2514. nodeExtent
  2515. }));
  2516. return jsxRuntime.jsx(Provider$1, { value: store, children: jsxRuntime.jsx(BatchProvider, { children }) });
  2517. }
  2518. function Wrapper({ children, nodes, edges, defaultNodes, defaultEdges, width, height, fitView: fitView2, nodeOrigin, nodeExtent }) {
  2519. const isWrapped = react.useContext(StoreContext);
  2520. if (isWrapped) {
  2521. return jsxRuntime.jsx(jsxRuntime.Fragment, { children });
  2522. }
  2523. return jsxRuntime.jsx(ReactFlowProvider, { initialNodes: nodes, initialEdges: edges, defaultNodes, defaultEdges, initialWidth: width, initialHeight: height, fitView: fitView2, nodeOrigin, nodeExtent, children });
  2524. }
  2525. var wrapperStyle = {
  2526. width: "100%",
  2527. height: "100%",
  2528. overflow: "hidden",
  2529. position: "relative",
  2530. zIndex: 0
  2531. };
  2532. function ReactFlow({ nodes, edges, defaultNodes, defaultEdges, className, nodeTypes, edgeTypes, onNodeClick, onEdgeClick, onInit, onMove, onMoveStart, onMoveEnd, onConnect, onConnectStart, onConnectEnd, onClickConnectStart, onClickConnectEnd, onNodeMouseEnter, onNodeMouseMove, onNodeMouseLeave, onNodeContextMenu, onNodeDoubleClick, onNodeDragStart, onNodeDrag, onNodeDragStop, onNodesDelete, onEdgesDelete, onDelete, onSelectionChange, onSelectionDragStart, onSelectionDrag, onSelectionDragStop, onSelectionContextMenu, onSelectionStart, onSelectionEnd, onBeforeDelete, connectionMode, connectionLineType = system.ConnectionLineType.Bezier, connectionLineStyle, connectionLineComponent, connectionLineContainerStyle, deleteKeyCode = "Backspace", selectionKeyCode = "Shift", selectionOnDrag = false, selectionMode = system.SelectionMode.Full, panActivationKeyCode = "Space", multiSelectionKeyCode = system.isMacOs() ? "Meta" : "Control", zoomActivationKeyCode = system.isMacOs() ? "Meta" : "Control", snapToGrid, snapGrid, onlyRenderVisibleElements = false, selectNodesOnDrag, nodesDraggable, nodesConnectable, nodesFocusable, nodeOrigin = defaultNodeOrigin, edgesFocusable, edgesReconnectable, elementsSelectable = true, defaultViewport: defaultViewport$1 = defaultViewport, minZoom = 0.5, maxZoom = 2, translateExtent = system.infiniteExtent, preventScrolling = true, nodeExtent, defaultMarkerColor = "#b1b1b7", zoomOnScroll = true, zoomOnPinch = true, panOnScroll = false, panOnScrollSpeed = 0.5, panOnScrollMode = system.PanOnScrollMode.Free, zoomOnDoubleClick = true, panOnDrag = true, onPaneClick, onPaneMouseEnter, onPaneMouseMove, onPaneMouseLeave, onPaneScroll, onPaneContextMenu, paneClickDistance = 0, nodeClickDistance = 0, children, onReconnect, onReconnectStart, onReconnectEnd, onEdgeContextMenu, onEdgeDoubleClick, onEdgeMouseEnter, onEdgeMouseMove, onEdgeMouseLeave, reconnectRadius = 10, onNodesChange, onEdgesChange, noDragClassName = "nodrag", noWheelClassName = "nowheel", noPanClassName = "nopan", fitView: fitView2, fitViewOptions, connectOnClick, attributionPosition, proOptions, defaultEdgeOptions, elevateNodesOnSelect, elevateEdgesOnSelect, disableKeyboardA11y = false, autoPanOnConnect, autoPanOnNodeDrag, autoPanSpeed, connectionRadius, isValidConnection, onError, style: style2, id, nodeDragThreshold, viewport, onViewportChange, width, height, colorMode = "light", debug, ...rest }, ref) {
  2533. const rfId = id || "1";
  2534. const colorModeClassName = useColorModeClass(colorMode);
  2535. return jsxRuntime.jsx("div", { "data-testid": "rf__wrapper", ...rest, style: { ...style2, ...wrapperStyle }, ref, className: cc(["react-flow", className, colorModeClassName]), id, children: jsxRuntime.jsxs(Wrapper, { nodes, edges, width, height, fitView: fitView2, nodeOrigin, nodeExtent, children: [jsxRuntime.jsx(GraphView, { onInit, onNodeClick, onEdgeClick, onNodeMouseEnter, onNodeMouseMove, onNodeMouseLeave, onNodeContextMenu, onNodeDoubleClick, nodeTypes, edgeTypes, connectionLineType, connectionLineStyle, connectionLineComponent, connectionLineContainerStyle, selectionKeyCode, selectionOnDrag, selectionMode, deleteKeyCode, multiSelectionKeyCode, panActivationKeyCode, zoomActivationKeyCode, onlyRenderVisibleElements, defaultViewport: defaultViewport$1, translateExtent, minZoom, maxZoom, preventScrolling, zoomOnScroll, zoomOnPinch, zoomOnDoubleClick, panOnScroll, panOnScrollSpeed, panOnScrollMode, panOnDrag, onPaneClick, onPaneMouseEnter, onPaneMouseMove, onPaneMouseLeave, onPaneScroll, onPaneContextMenu, paneClickDistance, nodeClickDistance, onSelectionContextMenu, onSelectionStart, onSelectionEnd, onReconnect, onReconnectStart, onReconnectEnd, onEdgeContextMenu, onEdgeDoubleClick, onEdgeMouseEnter, onEdgeMouseMove, onEdgeMouseLeave, reconnectRadius, defaultMarkerColor, noDragClassName, noWheelClassName, noPanClassName, rfId, disableKeyboardA11y, nodeExtent, viewport, onViewportChange }), jsxRuntime.jsx(StoreUpdater, { nodes, edges, defaultNodes, defaultEdges, onConnect, onConnectStart, onConnectEnd, onClickConnectStart, onClickConnectEnd, nodesDraggable, nodesConnectable, nodesFocusable, edgesFocusable, edgesReconnectable, elementsSelectable, elevateNodesOnSelect, elevateEdgesOnSelect, minZoom, maxZoom, nodeExtent, onNodesChange, onEdgesChange, snapToGrid, snapGrid, connectionMode, translateExtent, connectOnClick, defaultEdgeOptions, fitView: fitView2, fitViewOptions, onNodesDelete, onEdgesDelete, onDelete, onNodeDragStart, onNodeDrag, onNodeDragStop, onSelectionDrag, onSelectionDragStart, onSelectionDragStop, onMove, onMoveStart, onMoveEnd, noPanClassName, nodeOrigin, rfId, autoPanOnConnect, autoPanOnNodeDrag, autoPanSpeed, onError, connectionRadius, isValidConnection, selectNodesOnDrag, nodeDragThreshold, onBeforeDelete, paneClickDistance, debug }), jsxRuntime.jsx(SelectionListener, { onSelectionChange }), children, jsxRuntime.jsx(Attribution, { proOptions, position: attributionPosition }), jsxRuntime.jsx(A11yDescriptions, { rfId, disableKeyboardA11y })] }) });
  2536. }
  2537. var index = fixedForwardRef(ReactFlow);
  2538. var selector$6 = (s) => s.domNode?.querySelector(".react-flow__edgelabel-renderer");
  2539. function EdgeLabelRenderer({ children }) {
  2540. const edgeLabelRenderer = useStore(selector$6);
  2541. if (!edgeLabelRenderer) {
  2542. return null;
  2543. }
  2544. return reactDom.createPortal(children, edgeLabelRenderer);
  2545. }
  2546. var selector$5 = (s) => s.domNode?.querySelector(".react-flow__viewport-portal");
  2547. function ViewportPortal({ children }) {
  2548. const viewPortalDiv = useStore(selector$5);
  2549. if (!viewPortalDiv) {
  2550. return null;
  2551. }
  2552. return reactDom.createPortal(children, viewPortalDiv);
  2553. }
  2554. function useUpdateNodeInternals() {
  2555. const store = useStoreApi();
  2556. return react.useCallback((id) => {
  2557. const { domNode, updateNodeInternals: updateNodeInternals2 } = store.getState();
  2558. const updateIds = Array.isArray(id) ? id : [id];
  2559. const updates = new Map();
  2560. updateIds.forEach((updateId) => {
  2561. const nodeElement = domNode?.querySelector(`.react-flow__node[data-id="${updateId}"]`);
  2562. if (nodeElement) {
  2563. updates.set(updateId, { id: updateId, nodeElement, force: true });
  2564. }
  2565. });
  2566. requestAnimationFrame(() => updateNodeInternals2(updates, { triggerFitView: false }));
  2567. }, []);
  2568. }
  2569. var nodesSelector = (state) => state.nodes;
  2570. function useNodes() {
  2571. const nodes = useStore(nodesSelector, shallow.shallow);
  2572. return nodes;
  2573. }
  2574. var edgesSelector = (state) => state.edges;
  2575. function useEdges() {
  2576. const edges = useStore(edgesSelector, shallow.shallow);
  2577. return edges;
  2578. }
  2579. var viewportSelector = (state) => ({
  2580. x: state.transform[0],
  2581. y: state.transform[1],
  2582. zoom: state.transform[2]
  2583. });
  2584. function useViewport() {
  2585. const viewport = useStore(viewportSelector, shallow.shallow);
  2586. return viewport;
  2587. }
  2588. function useNodesState(initialNodes) {
  2589. const [nodes, setNodes] = react.useState(initialNodes);
  2590. const onNodesChange = react.useCallback((changes) => setNodes((nds) => applyNodeChanges(changes, nds)), []);
  2591. return [nodes, setNodes, onNodesChange];
  2592. }
  2593. function useEdgesState(initialEdges) {
  2594. const [edges, setEdges] = react.useState(initialEdges);
  2595. const onEdgesChange = react.useCallback((changes) => setEdges((eds) => applyEdgeChanges(changes, eds)), []);
  2596. return [edges, setEdges, onEdgesChange];
  2597. }
  2598. function useOnViewportChange({ onStart, onChange, onEnd }) {
  2599. const store = useStoreApi();
  2600. react.useEffect(() => {
  2601. store.setState({ onViewportChangeStart: onStart });
  2602. }, [onStart]);
  2603. react.useEffect(() => {
  2604. store.setState({ onViewportChange: onChange });
  2605. }, [onChange]);
  2606. react.useEffect(() => {
  2607. store.setState({ onViewportChangeEnd: onEnd });
  2608. }, [onEnd]);
  2609. }
  2610. function useOnSelectionChange({ onChange }) {
  2611. const store = useStoreApi();
  2612. react.useEffect(() => {
  2613. const nextOnSelectionChangeHandlers = [...store.getState().onSelectionChangeHandlers, onChange];
  2614. store.setState({ onSelectionChangeHandlers: nextOnSelectionChangeHandlers });
  2615. return () => {
  2616. const nextHandlers = store.getState().onSelectionChangeHandlers.filter((fn) => fn !== onChange);
  2617. store.setState({ onSelectionChangeHandlers: nextHandlers });
  2618. };
  2619. }, [onChange]);
  2620. }
  2621. var selector$4 = (options) => (s) => {
  2622. if (s.nodeLookup.size === 0) {
  2623. return false;
  2624. }
  2625. for (const [, { hidden, internals }] of s.nodeLookup) {
  2626. if (options.includeHiddenNodes || !hidden) {
  2627. if (internals.handleBounds === void 0 || !system.nodeHasDimensions(internals.userNode)) {
  2628. return false;
  2629. }
  2630. }
  2631. }
  2632. return true;
  2633. };
  2634. var defaultOptions = {
  2635. includeHiddenNodes: false
  2636. };
  2637. function useNodesInitialized(options = defaultOptions) {
  2638. const initialized = useStore(selector$4(options));
  2639. return initialized;
  2640. }
  2641. function useHandleConnections({ type, id = null, nodeId, onConnect, onDisconnect }) {
  2642. const _nodeId = useNodeId();
  2643. const currentNodeId = nodeId ?? _nodeId;
  2644. const prevConnections = react.useRef(null);
  2645. const connections = useStore((state) => state.connectionLookup.get(`${currentNodeId}-${type}-${id}`), system.areConnectionMapsEqual);
  2646. react.useEffect(() => {
  2647. if (prevConnections.current && prevConnections.current !== connections) {
  2648. const _connections = connections ?? new Map();
  2649. system.handleConnectionChange(prevConnections.current, _connections, onDisconnect);
  2650. system.handleConnectionChange(_connections, prevConnections.current, onConnect);
  2651. }
  2652. prevConnections.current = connections ?? new Map();
  2653. }, [connections, onConnect, onDisconnect]);
  2654. return react.useMemo(() => Array.from(connections?.values() ?? []), [connections]);
  2655. }
  2656. function useNodesData(nodeIds) {
  2657. const nodesData = useStore(react.useCallback((s) => {
  2658. const data = [];
  2659. const isArrayOfIds = Array.isArray(nodeIds);
  2660. const _nodeIds = isArrayOfIds ? nodeIds : [nodeIds];
  2661. for (const nodeId of _nodeIds) {
  2662. const node = s.nodeLookup.get(nodeId);
  2663. if (node) {
  2664. data.push({
  2665. id: node.id,
  2666. type: node.type,
  2667. data: node.data
  2668. });
  2669. }
  2670. }
  2671. return isArrayOfIds ? data : data[0] ?? null;
  2672. }, [nodeIds]), system.shallowNodeData);
  2673. return nodesData;
  2674. }
  2675. function useInternalNode(id) {
  2676. const node = useStore(react.useCallback((s) => s.nodeLookup.get(id), [id]), shallow.shallow);
  2677. return node;
  2678. }
  2679. function LinePattern({ dimensions, lineWidth, variant, className }) {
  2680. return jsxRuntime.jsx("path", { strokeWidth: lineWidth, d: `M${dimensions[0] / 2} 0 V${dimensions[1]} M0 ${dimensions[1] / 2} H${dimensions[0]}`, className: cc(["react-flow__background-pattern", variant, className]) });
  2681. }
  2682. function DotPattern({ radius, className }) {
  2683. return jsxRuntime.jsx("circle", { cx: radius, cy: radius, r: radius, className: cc(["react-flow__background-pattern", "dots", className]) });
  2684. }
  2685. exports.BackgroundVariant = void 0;
  2686. (function(BackgroundVariant2) {
  2687. BackgroundVariant2["Lines"] = "lines";
  2688. BackgroundVariant2["Dots"] = "dots";
  2689. BackgroundVariant2["Cross"] = "cross";
  2690. })(exports.BackgroundVariant || (exports.BackgroundVariant = {}));
  2691. var defaultSize = {
  2692. [exports.BackgroundVariant.Dots]: 1,
  2693. [exports.BackgroundVariant.Lines]: 1,
  2694. [exports.BackgroundVariant.Cross]: 6
  2695. };
  2696. var selector$3 = (s) => ({ transform: s.transform, patternId: `pattern-${s.rfId}` });
  2697. function BackgroundComponent({
  2698. id,
  2699. variant = exports.BackgroundVariant.Dots,
  2700. gap = 20,
  2701. size,
  2702. lineWidth = 1,
  2703. offset = 0,
  2704. color,
  2705. bgColor,
  2706. style: style2,
  2707. className,
  2708. patternClassName
  2709. }) {
  2710. const ref = react.useRef(null);
  2711. const { transform, patternId } = useStore(selector$3, shallow.shallow);
  2712. const patternSize = size || defaultSize[variant];
  2713. const isDots = variant === exports.BackgroundVariant.Dots;
  2714. const isCross = variant === exports.BackgroundVariant.Cross;
  2715. const gapXY = Array.isArray(gap) ? gap : [gap, gap];
  2716. const scaledGap = [gapXY[0] * transform[2] || 1, gapXY[1] * transform[2] || 1];
  2717. const scaledSize = patternSize * transform[2];
  2718. const offsetXY = Array.isArray(offset) ? offset : [offset, offset];
  2719. const patternDimensions = isCross ? [scaledSize, scaledSize] : scaledGap;
  2720. const scaledOffset = [
  2721. offsetXY[0] * transform[2] || 1 + patternDimensions[0] / 2,
  2722. offsetXY[1] * transform[2] || 1 + patternDimensions[1] / 2
  2723. ];
  2724. const _patternId = `${patternId}${id ? id : ""}`;
  2725. return jsxRuntime.jsxs("svg", { className: cc(["react-flow__background", className]), style: {
  2726. ...style2,
  2727. ...containerStyle,
  2728. "--xy-background-color-props": bgColor,
  2729. "--xy-background-pattern-color-props": color
  2730. }, ref, "data-testid": "rf__background", children: [jsxRuntime.jsx("pattern", { id: _patternId, x: transform[0] % scaledGap[0], y: transform[1] % scaledGap[1], width: scaledGap[0], height: scaledGap[1], patternUnits: "userSpaceOnUse", patternTransform: `translate(-${scaledOffset[0]},-${scaledOffset[1]})`, children: isDots ? jsxRuntime.jsx(DotPattern, { radius: scaledSize / 2, className: patternClassName }) : jsxRuntime.jsx(LinePattern, { dimensions: patternDimensions, lineWidth, variant, className: patternClassName }) }), jsxRuntime.jsx("rect", { x: "0", y: "0", width: "100%", height: "100%", fill: `url(#${_patternId})` })] });
  2731. }
  2732. BackgroundComponent.displayName = "Background";
  2733. var Background = react.memo(BackgroundComponent);
  2734. function PlusIcon() {
  2735. return jsxRuntime.jsx("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 32 32", children: jsxRuntime.jsx("path", { d: "M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z" }) });
  2736. }
  2737. function MinusIcon() {
  2738. return jsxRuntime.jsx("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 32 5", children: jsxRuntime.jsx("path", { d: "M0 0h32v4.2H0z" }) });
  2739. }
  2740. function FitViewIcon() {
  2741. return jsxRuntime.jsx("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 32 30", children: jsxRuntime.jsx("path", { d: "M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z" }) });
  2742. }
  2743. function LockIcon() {
  2744. return jsxRuntime.jsx("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 25 32", children: jsxRuntime.jsx("path", { d: "M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z" }) });
  2745. }
  2746. function UnlockIcon() {
  2747. return jsxRuntime.jsx("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 25 32", children: jsxRuntime.jsx("path", { d: "M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z" }) });
  2748. }
  2749. function ControlButton({ children, className, ...rest }) {
  2750. return jsxRuntime.jsx("button", { type: "button", className: cc(["react-flow__controls-button", className]), ...rest, children });
  2751. }
  2752. var selector$2 = (s) => ({
  2753. isInteractive: s.nodesDraggable || s.nodesConnectable || s.elementsSelectable,
  2754. minZoomReached: s.transform[2] <= s.minZoom,
  2755. maxZoomReached: s.transform[2] >= s.maxZoom
  2756. });
  2757. function ControlsComponent({ style: style2, showZoom = true, showFitView = true, showInteractive = true, fitViewOptions, onZoomIn, onZoomOut, onFitView, onInteractiveChange, className, children, position = "bottom-left", orientation = "vertical", "aria-label": ariaLabel = "React Flow controls" }) {
  2758. const store = useStoreApi();
  2759. const { isInteractive, minZoomReached, maxZoomReached } = useStore(selector$2, shallow.shallow);
  2760. const { zoomIn, zoomOut, fitView: fitView2 } = useReactFlow();
  2761. const onZoomInHandler = () => {
  2762. zoomIn();
  2763. onZoomIn?.();
  2764. };
  2765. const onZoomOutHandler = () => {
  2766. zoomOut();
  2767. onZoomOut?.();
  2768. };
  2769. const onFitViewHandler = () => {
  2770. fitView2(fitViewOptions);
  2771. onFitView?.();
  2772. };
  2773. const onToggleInteractivity = () => {
  2774. store.setState({
  2775. nodesDraggable: !isInteractive,
  2776. nodesConnectable: !isInteractive,
  2777. elementsSelectable: !isInteractive
  2778. });
  2779. onInteractiveChange?.(!isInteractive);
  2780. };
  2781. const orientationClass = orientation === "horizontal" ? "horizontal" : "vertical";
  2782. return jsxRuntime.jsxs(Panel, { className: cc(["react-flow__controls", orientationClass, className]), position, style: style2, "data-testid": "rf__controls", "aria-label": ariaLabel, children: [showZoom && jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx(ControlButton, { onClick: onZoomInHandler, className: "react-flow__controls-zoomin", title: "zoom in", "aria-label": "zoom in", disabled: maxZoomReached, children: jsxRuntime.jsx(PlusIcon, {}) }), jsxRuntime.jsx(ControlButton, { onClick: onZoomOutHandler, className: "react-flow__controls-zoomout", title: "zoom out", "aria-label": "zoom out", disabled: minZoomReached, children: jsxRuntime.jsx(MinusIcon, {}) })] }), showFitView && jsxRuntime.jsx(ControlButton, { className: "react-flow__controls-fitview", onClick: onFitViewHandler, title: "fit view", "aria-label": "fit view", children: jsxRuntime.jsx(FitViewIcon, {}) }), showInteractive && jsxRuntime.jsx(ControlButton, { className: "react-flow__controls-interactive", onClick: onToggleInteractivity, title: "toggle interactivity", "aria-label": "toggle interactivity", children: isInteractive ? jsxRuntime.jsx(UnlockIcon, {}) : jsxRuntime.jsx(LockIcon, {}) }), children] });
  2783. }
  2784. ControlsComponent.displayName = "Controls";
  2785. var Controls = react.memo(ControlsComponent);
  2786. function MiniMapNodeComponent({ id, x, y, width, height, style: style2, color, strokeColor, strokeWidth, className, borderRadius, shapeRendering, selected: selected2, onClick }) {
  2787. const { background, backgroundColor } = style2 || {};
  2788. const fill = color || background || backgroundColor;
  2789. return jsxRuntime.jsx("rect", { className: cc(["react-flow__minimap-node", { selected: selected2 }, className]), x, y, rx: borderRadius, ry: borderRadius, width, height, style: {
  2790. fill,
  2791. stroke: strokeColor,
  2792. strokeWidth
  2793. }, shapeRendering, onClick: onClick ? (event) => onClick(event, id) : void 0 });
  2794. }
  2795. var MiniMapNode = react.memo(MiniMapNodeComponent);
  2796. var selectorNodeIds = (s) => s.nodes.map((node) => node.id);
  2797. var getAttrFunction = (func) => func instanceof Function ? func : () => func;
  2798. function MiniMapNodes({
  2799. nodeStrokeColor,
  2800. nodeColor,
  2801. nodeClassName = "",
  2802. nodeBorderRadius = 5,
  2803. nodeStrokeWidth,
  2804. nodeComponent: NodeComponent = MiniMapNode,
  2805. onClick
  2806. }) {
  2807. const nodeIds = useStore(selectorNodeIds, shallow.shallow);
  2808. const nodeColorFunc = getAttrFunction(nodeColor);
  2809. const nodeStrokeColorFunc = getAttrFunction(nodeStrokeColor);
  2810. const nodeClassNameFunc = getAttrFunction(nodeClassName);
  2811. const shapeRendering = typeof window === "undefined" || !!window.chrome ? "crispEdges" : "geometricPrecision";
  2812. return jsxRuntime.jsx(jsxRuntime.Fragment, { children: nodeIds.map((nodeId) => (
  2813. jsxRuntime.jsx(NodeComponentWrapper, { id: nodeId, nodeColorFunc, nodeStrokeColorFunc, nodeClassNameFunc, nodeBorderRadius, nodeStrokeWidth, NodeComponent, onClick, shapeRendering }, nodeId)
  2814. )) });
  2815. }
  2816. function NodeComponentWrapperInner({ id, nodeColorFunc, nodeStrokeColorFunc, nodeClassNameFunc, nodeBorderRadius, nodeStrokeWidth, shapeRendering, NodeComponent, onClick }) {
  2817. const { node, x, y, width, height } = useStore((s) => {
  2818. const node2 = s.nodeLookup.get(id);
  2819. const { x: x2, y: y2 } = node2.internals.positionAbsolute;
  2820. const { width: width2, height: height2 } = system.getNodeDimensions(node2);
  2821. return {
  2822. node: node2,
  2823. x: x2,
  2824. y: y2,
  2825. width: width2,
  2826. height: height2
  2827. };
  2828. }, shallow.shallow);
  2829. if (!node || node.hidden || !system.nodeHasDimensions(node)) {
  2830. return null;
  2831. }
  2832. return jsxRuntime.jsx(NodeComponent, { x, y, width, height, style: node.style, selected: !!node.selected, className: nodeClassNameFunc(node), color: nodeColorFunc(node), borderRadius: nodeBorderRadius, strokeColor: nodeStrokeColorFunc(node), strokeWidth: nodeStrokeWidth, shapeRendering, onClick, id: node.id });
  2833. }
  2834. var NodeComponentWrapper = react.memo(NodeComponentWrapperInner);
  2835. var MiniMapNodes$1 = react.memo(MiniMapNodes);
  2836. var defaultWidth = 200;
  2837. var defaultHeight = 150;
  2838. var selector$1 = (s) => {
  2839. const viewBB = {
  2840. x: -s.transform[0] / s.transform[2],
  2841. y: -s.transform[1] / s.transform[2],
  2842. width: s.width / s.transform[2],
  2843. height: s.height / s.transform[2]
  2844. };
  2845. return {
  2846. viewBB,
  2847. boundingRect: s.nodeLookup.size > 0 ? system.getBoundsOfRects(system.getInternalNodesBounds(s.nodeLookup), viewBB) : viewBB,
  2848. rfId: s.rfId,
  2849. panZoom: s.panZoom,
  2850. translateExtent: s.translateExtent,
  2851. flowWidth: s.width,
  2852. flowHeight: s.height
  2853. };
  2854. };
  2855. var ARIA_LABEL_KEY = "react-flow__minimap-desc";
  2856. function MiniMapComponent({
  2857. style: style2,
  2858. className,
  2859. nodeStrokeColor,
  2860. nodeColor,
  2861. nodeClassName = "",
  2862. nodeBorderRadius = 5,
  2863. nodeStrokeWidth,
  2864. nodeComponent,
  2865. bgColor,
  2866. maskColor,
  2867. maskStrokeColor,
  2868. maskStrokeWidth,
  2869. position = "bottom-right",
  2870. onClick,
  2871. onNodeClick,
  2872. pannable = false,
  2873. zoomable = false,
  2874. ariaLabel = "React Flow mini map",
  2875. inversePan,
  2876. zoomStep = 10,
  2877. offsetScale = 5
  2878. }) {
  2879. const store = useStoreApi();
  2880. const svg = react.useRef(null);
  2881. const { boundingRect, viewBB, rfId, panZoom, translateExtent, flowWidth, flowHeight } = useStore(selector$1, shallow.shallow);
  2882. const elementWidth = style2?.width ?? defaultWidth;
  2883. const elementHeight = style2?.height ?? defaultHeight;
  2884. const scaledWidth = boundingRect.width / elementWidth;
  2885. const scaledHeight = boundingRect.height / elementHeight;
  2886. const viewScale = Math.max(scaledWidth, scaledHeight);
  2887. const viewWidth = viewScale * elementWidth;
  2888. const viewHeight = viewScale * elementHeight;
  2889. const offset = offsetScale * viewScale;
  2890. const x = boundingRect.x - (viewWidth - boundingRect.width) / 2 - offset;
  2891. const y = boundingRect.y - (viewHeight - boundingRect.height) / 2 - offset;
  2892. const width = viewWidth + offset * 2;
  2893. const height = viewHeight + offset * 2;
  2894. const labelledBy = `${ARIA_LABEL_KEY}-${rfId}`;
  2895. const viewScaleRef = react.useRef(0);
  2896. const minimapInstance = react.useRef();
  2897. viewScaleRef.current = viewScale;
  2898. react.useEffect(() => {
  2899. if (svg.current && panZoom) {
  2900. minimapInstance.current = system.XYMinimap({
  2901. domNode: svg.current,
  2902. panZoom,
  2903. getTransform: () => store.getState().transform,
  2904. getViewScale: () => viewScaleRef.current
  2905. });
  2906. return () => {
  2907. minimapInstance.current?.destroy();
  2908. };
  2909. }
  2910. }, [panZoom]);
  2911. react.useEffect(() => {
  2912. minimapInstance.current?.update({
  2913. translateExtent,
  2914. width: flowWidth,
  2915. height: flowHeight,
  2916. inversePan,
  2917. pannable,
  2918. zoomStep,
  2919. zoomable
  2920. });
  2921. }, [pannable, zoomable, inversePan, zoomStep, translateExtent, flowWidth, flowHeight]);
  2922. const onSvgClick = onClick ? (event) => {
  2923. const [x2, y2] = minimapInstance.current?.pointer(event) || [0, 0];
  2924. onClick(event, { x: x2, y: y2 });
  2925. } : void 0;
  2926. const onSvgNodeClick = onNodeClick ? react.useCallback((event, nodeId) => {
  2927. const node = store.getState().nodeLookup.get(nodeId);
  2928. onNodeClick(event, node);
  2929. }, []) : void 0;
  2930. return jsxRuntime.jsx(Panel, { position, style: {
  2931. ...style2,
  2932. "--xy-minimap-background-color-props": typeof bgColor === "string" ? bgColor : void 0,
  2933. "--xy-minimap-mask-background-color-props": typeof maskColor === "string" ? maskColor : void 0,
  2934. "--xy-minimap-mask-stroke-color-props": typeof maskStrokeColor === "string" ? maskStrokeColor : void 0,
  2935. "--xy-minimap-mask-stroke-width-props": typeof maskStrokeWidth === "number" ? maskStrokeWidth * viewScale : void 0,
  2936. "--xy-minimap-node-background-color-props": typeof nodeColor === "string" ? nodeColor : void 0,
  2937. "--xy-minimap-node-stroke-color-props": typeof nodeStrokeColor === "string" ? nodeStrokeColor : void 0,
  2938. "--xy-minimap-node-stroke-width-props": typeof nodeStrokeWidth === "string" ? nodeStrokeWidth : void 0
  2939. }, className: cc(["react-flow__minimap", className]), "data-testid": "rf__minimap", children: jsxRuntime.jsxs("svg", { width: elementWidth, height: elementHeight, viewBox: `${x} ${y} ${width} ${height}`, className: "react-flow__minimap-svg", role: "img", "aria-labelledby": labelledBy, ref: svg, onClick: onSvgClick, children: [ariaLabel && jsxRuntime.jsx("title", { id: labelledBy, children: ariaLabel }), jsxRuntime.jsx(MiniMapNodes$1, { onClick: onSvgNodeClick, nodeColor, nodeStrokeColor, nodeBorderRadius, nodeClassName, nodeStrokeWidth, nodeComponent }), jsxRuntime.jsx("path", { className: "react-flow__minimap-mask", d: `M${x - offset},${y - offset}h${width + offset * 2}v${height + offset * 2}h${-width - offset * 2}z
  2940. M${viewBB.x},${viewBB.y}h${viewBB.width}v${viewBB.height}h${-viewBB.width}z`, fillRule: "evenodd", pointerEvents: "none" })] }) });
  2941. }
  2942. MiniMapComponent.displayName = "MiniMap";
  2943. var MiniMap = react.memo(MiniMapComponent);
  2944. function ResizeControl({ nodeId, position, variant = system.ResizeControlVariant.Handle, className, style: style2 = {}, children, color, minWidth = 10, minHeight = 10, maxWidth = Number.MAX_VALUE, maxHeight = Number.MAX_VALUE, keepAspectRatio = false, shouldResize, onResizeStart, onResize, onResizeEnd }) {
  2945. const contextNodeId = useNodeId();
  2946. const id = typeof nodeId === "string" ? nodeId : contextNodeId;
  2947. const store = useStoreApi();
  2948. const resizeControlRef = react.useRef(null);
  2949. const defaultPosition = variant === system.ResizeControlVariant.Line ? "right" : "bottom-right";
  2950. const controlPosition = position ?? defaultPosition;
  2951. const resizer = react.useRef(null);
  2952. react.useEffect(() => {
  2953. if (!resizeControlRef.current || !id) {
  2954. return;
  2955. }
  2956. if (!resizer.current) {
  2957. resizer.current = system.XYResizer({
  2958. domNode: resizeControlRef.current,
  2959. nodeId: id,
  2960. getStoreItems: () => {
  2961. const { nodeLookup, transform, snapGrid, snapToGrid, nodeOrigin, domNode } = store.getState();
  2962. return {
  2963. nodeLookup,
  2964. transform,
  2965. snapGrid,
  2966. snapToGrid,
  2967. nodeOrigin,
  2968. paneDomNode: domNode
  2969. };
  2970. },
  2971. onChange: (change, childChanges) => {
  2972. const { triggerNodeChanges, nodeLookup, parentLookup, nodeOrigin } = store.getState();
  2973. const changes = [];
  2974. const nextPosition = { x: change.x, y: change.y };
  2975. const node = nodeLookup.get(id);
  2976. if (node && node.expandParent && node.parentId) {
  2977. const origin = node.origin ?? nodeOrigin;
  2978. const width = change.width ?? node.measured.width;
  2979. const height = change.height ?? node.measured.height;
  2980. const child = {
  2981. id: node.id,
  2982. parentId: node.parentId,
  2983. rect: {
  2984. width,
  2985. height,
  2986. ...system.evaluateAbsolutePosition({
  2987. x: change.x ?? node.position.x,
  2988. y: change.y ?? node.position.y
  2989. }, { width, height }, node.parentId, nodeLookup, origin)
  2990. }
  2991. };
  2992. const parentExpandChanges = system.handleExpandParent([child], nodeLookup, parentLookup, nodeOrigin);
  2993. changes.push(...parentExpandChanges);
  2994. nextPosition.x = change.x ? Math.max(origin[0] * width, change.x) : void 0;
  2995. nextPosition.y = change.y ? Math.max(origin[1] * height, change.y) : void 0;
  2996. }
  2997. if (nextPosition.x !== void 0 && nextPosition.y !== void 0) {
  2998. const positionChange = {
  2999. id,
  3000. type: "position",
  3001. position: { ...nextPosition }
  3002. };
  3003. changes.push(positionChange);
  3004. }
  3005. if (change.width !== void 0 && change.height !== void 0) {
  3006. const dimensionChange = {
  3007. id,
  3008. type: "dimensions",
  3009. resizing: true,
  3010. setAttributes: true,
  3011. dimensions: {
  3012. width: change.width,
  3013. height: change.height
  3014. }
  3015. };
  3016. changes.push(dimensionChange);
  3017. }
  3018. for (const childChange of childChanges) {
  3019. const positionChange = {
  3020. ...childChange,
  3021. type: "position"
  3022. };
  3023. changes.push(positionChange);
  3024. }
  3025. triggerNodeChanges(changes);
  3026. },
  3027. onEnd: () => {
  3028. const dimensionChange = {
  3029. id,
  3030. type: "dimensions",
  3031. resizing: false
  3032. };
  3033. store.getState().triggerNodeChanges([dimensionChange]);
  3034. }
  3035. });
  3036. }
  3037. resizer.current.update({
  3038. controlPosition,
  3039. boundaries: {
  3040. minWidth,
  3041. minHeight,
  3042. maxWidth,
  3043. maxHeight
  3044. },
  3045. keepAspectRatio,
  3046. onResizeStart,
  3047. onResize,
  3048. onResizeEnd,
  3049. shouldResize
  3050. });
  3051. return () => {
  3052. resizer.current?.destroy();
  3053. };
  3054. }, [
  3055. controlPosition,
  3056. minWidth,
  3057. minHeight,
  3058. maxWidth,
  3059. maxHeight,
  3060. keepAspectRatio,
  3061. onResizeStart,
  3062. onResize,
  3063. onResizeEnd,
  3064. shouldResize
  3065. ]);
  3066. const positionClassNames = controlPosition.split("-");
  3067. const colorStyleProp = variant === system.ResizeControlVariant.Line ? "borderColor" : "backgroundColor";
  3068. const controlStyle = color ? { ...style2, [colorStyleProp]: color } : style2;
  3069. return jsxRuntime.jsx("div", { className: cc(["react-flow__resize-control", "nodrag", ...positionClassNames, variant, className]), ref: resizeControlRef, style: controlStyle, children });
  3070. }
  3071. var NodeResizeControl = react.memo(ResizeControl);
  3072. function NodeResizer({ nodeId, isVisible = true, handleClassName, handleStyle, lineClassName, lineStyle, color, minWidth = 10, minHeight = 10, maxWidth = Number.MAX_VALUE, maxHeight = Number.MAX_VALUE, keepAspectRatio = false, shouldResize, onResizeStart, onResize, onResizeEnd }) {
  3073. if (!isVisible) {
  3074. return null;
  3075. }
  3076. return jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [system.XY_RESIZER_LINE_POSITIONS.map((position) => jsxRuntime.jsx(NodeResizeControl, { className: lineClassName, style: lineStyle, nodeId, position, variant: system.ResizeControlVariant.Line, color, minWidth, minHeight, maxWidth, maxHeight, onResizeStart, keepAspectRatio, shouldResize, onResize, onResizeEnd }, position)), system.XY_RESIZER_HANDLE_POSITIONS.map((position) => jsxRuntime.jsx(NodeResizeControl, { className: handleClassName, style: handleStyle, nodeId, position, color, minWidth, minHeight, maxWidth, maxHeight, onResizeStart, keepAspectRatio, shouldResize, onResize, onResizeEnd }, position))] });
  3077. }
  3078. var selector = (state) => state.domNode?.querySelector(".react-flow__renderer");
  3079. function NodeToolbarPortal({ children }) {
  3080. const wrapperRef = useStore(selector);
  3081. if (!wrapperRef) {
  3082. return null;
  3083. }
  3084. return reactDom.createPortal(children, wrapperRef);
  3085. }
  3086. var nodeEqualityFn = (a, b) => a?.internals.positionAbsolute.x !== b?.internals.positionAbsolute.x || a?.internals.positionAbsolute.y !== b?.internals.positionAbsolute.y || a?.measured.width !== b?.measured.width || a?.measured.height !== b?.measured.height || a?.selected !== b?.selected || a?.internals.z !== b?.internals.z;
  3087. var nodesEqualityFn = (a, b) => {
  3088. if (a.size !== b.size) {
  3089. return false;
  3090. }
  3091. for (const [key, node] of a) {
  3092. if (nodeEqualityFn(node, b.get(key))) {
  3093. return false;
  3094. }
  3095. }
  3096. return true;
  3097. };
  3098. var storeSelector = (state) => ({
  3099. x: state.transform[0],
  3100. y: state.transform[1],
  3101. zoom: state.transform[2],
  3102. selectedNodesCount: state.nodes.filter((node) => node.selected).length
  3103. });
  3104. function NodeToolbar({ nodeId, children, className, style: style2, isVisible, position = system.Position.Top, offset = 10, align = "center", ...rest }) {
  3105. const contextNodeId = useNodeId();
  3106. const nodesSelector2 = react.useCallback((state) => {
  3107. const nodeIds = Array.isArray(nodeId) ? nodeId : [nodeId || contextNodeId || ""];
  3108. const internalNodes = nodeIds.reduce((res, id) => {
  3109. const node = state.nodeLookup.get(id);
  3110. if (node) {
  3111. res.set(node.id, node);
  3112. }
  3113. return res;
  3114. }, new Map());
  3115. return internalNodes;
  3116. }, [nodeId, contextNodeId]);
  3117. const nodes = useStore(nodesSelector2, nodesEqualityFn);
  3118. const { x, y, zoom, selectedNodesCount } = useStore(storeSelector, shallow.shallow);
  3119. const isActive = typeof isVisible === "boolean" ? isVisible : nodes.size === 1 && nodes.values().next().value.selected && selectedNodesCount === 1;
  3120. if (!isActive || !nodes.size) {
  3121. return null;
  3122. }
  3123. const nodeRect = system.getInternalNodesBounds(nodes);
  3124. const nodesArray = Array.from(nodes.values());
  3125. const zIndex = Math.max(...nodesArray.map((node) => node.internals.z + 1));
  3126. const wrapperStyle2 = {
  3127. position: "absolute",
  3128. transform: system.getNodeToolbarTransform(nodeRect, { x, y, zoom }, position, offset, align),
  3129. zIndex,
  3130. ...style2
  3131. };
  3132. return jsxRuntime.jsx(NodeToolbarPortal, { children: jsxRuntime.jsx("div", { style: wrapperStyle2, className: cc(["react-flow__node-toolbar", className]), ...rest, "data-id": nodesArray.reduce((acc, node) => `${acc}${node.id} `, "").trim(), children }) });
  3133. }
  3134.  
  3135. Object.defineProperty(exports, "ConnectionLineType", {
  3136. enumerable: true,
  3137. get: function () { return system.ConnectionLineType; }
  3138. });
  3139. Object.defineProperty(exports, "ConnectionMode", {
  3140. enumerable: true,
  3141. get: function () { return system.ConnectionMode; }
  3142. });
  3143. Object.defineProperty(exports, "MarkerType", {
  3144. enumerable: true,
  3145. get: function () { return system.MarkerType; }
  3146. });
  3147. Object.defineProperty(exports, "PanOnScrollMode", {
  3148. enumerable: true,
  3149. get: function () { return system.PanOnScrollMode; }
  3150. });
  3151. Object.defineProperty(exports, "Position", {
  3152. enumerable: true,
  3153. get: function () { return system.Position; }
  3154. });
  3155. Object.defineProperty(exports, "SelectionMode", {
  3156. enumerable: true,
  3157. get: function () { return system.SelectionMode; }
  3158. });
  3159. Object.defineProperty(exports, "addEdge", {
  3160. enumerable: true,
  3161. get: function () { return system.addEdge; }
  3162. });
  3163. Object.defineProperty(exports, "getBezierEdgeCenter", {
  3164. enumerable: true,
  3165. get: function () { return system.getBezierEdgeCenter; }
  3166. });
  3167. Object.defineProperty(exports, "getBezierPath", {
  3168. enumerable: true,
  3169. get: function () { return system.getBezierPath; }
  3170. });
  3171. Object.defineProperty(exports, "getConnectedEdges", {
  3172. enumerable: true,
  3173. get: function () { return system.getConnectedEdges; }
  3174. });
  3175. Object.defineProperty(exports, "getEdgeCenter", {
  3176. enumerable: true,
  3177. get: function () { return system.getEdgeCenter; }
  3178. });
  3179. Object.defineProperty(exports, "getIncomers", {
  3180. enumerable: true,
  3181. get: function () { return system.getIncomers; }
  3182. });
  3183. Object.defineProperty(exports, "getNodesBounds", {
  3184. enumerable: true,
  3185. get: function () { return system.getNodesBounds; }
  3186. });
  3187. Object.defineProperty(exports, "getOutgoers", {
  3188. enumerable: true,
  3189. get: function () { return system.getOutgoers; }
  3190. });
  3191. Object.defineProperty(exports, "getSmoothStepPath", {
  3192. enumerable: true,
  3193. get: function () { return system.getSmoothStepPath; }
  3194. });
  3195. Object.defineProperty(exports, "getStraightPath", {
  3196. enumerable: true,
  3197. get: function () { return system.getStraightPath; }
  3198. });
  3199. Object.defineProperty(exports, "getViewportForBounds", {
  3200. enumerable: true,
  3201. get: function () { return system.getViewportForBounds; }
  3202. });
  3203. Object.defineProperty(exports, "reconnectEdge", {
  3204. enumerable: true,
  3205. get: function () { return system.reconnectEdge; }
  3206. });
  3207. exports.Background = Background;
  3208. exports.BaseEdge = BaseEdge;
  3209. exports.BezierEdge = BezierEdge;
  3210. exports.ControlButton = ControlButton;
  3211. exports.Controls = Controls;
  3212. exports.EdgeLabelRenderer = EdgeLabelRenderer;
  3213. exports.EdgeText = EdgeText;
  3214. exports.Handle = Handle;
  3215. exports.MiniMap = MiniMap;
  3216. exports.NodeResizeControl = NodeResizeControl;
  3217. exports.NodeResizer = NodeResizer;
  3218. exports.NodeToolbar = NodeToolbar;
  3219. exports.Panel = Panel;
  3220. exports.ReactFlow = index;
  3221. exports.ReactFlowProvider = ReactFlowProvider;
  3222. exports.SimpleBezierEdge = SimpleBezierEdge;
  3223. exports.SmoothStepEdge = SmoothStepEdge;
  3224. exports.StepEdge = StepEdge;
  3225. exports.StraightEdge = StraightEdge;
  3226. exports.ViewportPortal = ViewportPortal;
  3227. exports.applyEdgeChanges = applyEdgeChanges;
  3228. exports.applyNodeChanges = applyNodeChanges;
  3229. exports.getSimpleBezierPath = getSimpleBezierPath;
  3230. exports.isEdge = isEdge;
  3231. exports.isNode = isNode;
  3232. exports.useConnection = useConnection;
  3233. exports.useEdges = useEdges;
  3234. exports.useEdgesState = useEdgesState;
  3235. exports.useHandleConnections = useHandleConnections;
  3236. exports.useInternalNode = useInternalNode;
  3237. exports.useKeyPress = useKeyPress;
  3238. exports.useNodeId = useNodeId;
  3239. exports.useNodes = useNodes;
  3240. exports.useNodesData = useNodesData;
  3241. exports.useNodesInitialized = useNodesInitialized;
  3242. exports.useNodesState = useNodesState;
  3243. exports.useOnSelectionChange = useOnSelectionChange;
  3244. exports.useOnViewportChange = useOnViewportChange;
  3245. exports.useReactFlow = useReactFlow;
  3246. exports.useStore = useStore;
  3247. exports.useStoreApi = useStoreApi;
  3248. exports.useUpdateNodeInternals = useUpdateNodeInternals;
  3249. exports.useViewport = useViewport;
  3250. }));