@rkmodules/rules 0.0.54 → 0.0.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { create, all } from 'mathjs';
2
- import React, { createContext, useLayoutEffect, useEffect, useState, useCallback, useMemo, isValidElement, cloneElement, useContext } from 'react';
2
+ import React, { createContext, memo, useEffect, useLayoutEffect, useState, useCallback, useMemo, isValidElement, cloneElement, useContext } from 'react';
3
3
  import { Handle, Position, useConnection, getSimpleBezierPath, ReactFlowProvider, useOnSelectionChange, applyNodeChanges, applyEdgeChanges, ReactFlow, Background, BackgroundVariant, Controls } from '@xyflow/react';
4
4
  import katex from 'katex';
5
5
  import classNames from 'classnames';
6
6
  import rcin from 'rc-input-number';
7
7
  import { create as create$1 } from 'zustand';
8
8
  import { persist } from 'zustand/middleware';
9
+ import { HTML5Backend } from 'react-dnd-html5-backend';
10
+ import { jsx } from 'react/jsx-runtime';
9
11
 
10
12
  /******************************************************************************
11
13
  Copyright (c) Microsoft Corporation.
@@ -594,7 +596,7 @@ var primitives$6 = (_a$6 = {},
594
596
  _a$6[value.name] = value,
595
597
  _a$6);
596
598
 
597
- var add = {
599
+ var add$1 = {
598
600
  name: "add",
599
601
  label: "Add",
600
602
  description: "Add two numbers",
@@ -804,8 +806,8 @@ var greaterThan = {
804
806
  label: "Greater Than",
805
807
  description: "Compare on greater than or greater than or equal to",
806
808
  inputs: {
807
- a: "number",
808
- b: "number",
809
+ a: { type: "number", default: 0 },
810
+ b: { type: "number", default: 0 },
809
811
  },
810
812
  outputs: {
811
813
  gt: "boolean",
@@ -815,9 +817,13 @@ var greaterThan = {
815
817
  return __generator(this, function (_a) {
816
818
  return [2 /*return*/, {
817
819
  gt: binaryOnTree(inputs.a, inputs.b, function (itemA, itemB) {
820
+ if (itemA === undefined || itemB === undefined)
821
+ return DISCARD;
818
822
  return itemA > itemB;
819
823
  }, true),
820
824
  gte: binaryOnTree(inputs.a, inputs.b, function (itemA, itemB) {
825
+ if (itemA === undefined || itemB === undefined)
826
+ return DISCARD;
821
827
  return itemA >= itemB;
822
828
  }, true),
823
829
  }];
@@ -830,8 +836,8 @@ var lessThan = {
830
836
  label: "Less Than",
831
837
  description: "Compare on less than or less than or equal to",
832
838
  inputs: {
833
- a: "number",
834
- b: "number",
839
+ a: { type: "number", default: 0 },
840
+ b: { type: "number", default: 0 },
835
841
  },
836
842
  outputs: {
837
843
  lt: "boolean",
@@ -841,9 +847,13 @@ var lessThan = {
841
847
  return __generator(this, function (_a) {
842
848
  return [2 /*return*/, {
843
849
  lt: binaryOnTree(inputs.a, inputs.b, function (itemA, itemB) {
850
+ if (itemA === undefined || itemB === undefined)
851
+ return DISCARD;
844
852
  return itemA < itemB;
845
853
  }, true),
846
854
  lte: binaryOnTree(inputs.a, inputs.b, function (itemA, itemB) {
855
+ if (itemA === undefined || itemB === undefined)
856
+ return DISCARD;
847
857
  return itemA <= itemB;
848
858
  }, true),
849
859
  }];
@@ -873,7 +883,7 @@ var multiply = {
873
883
  }); },
874
884
  };
875
885
 
876
- var subtract = {
886
+ var subtract$1 = {
877
887
  name: "subtract",
878
888
  label: "Subtract",
879
889
  description: "Subtract two numbers",
@@ -900,8 +910,8 @@ var primitives$5 = (_a$5 = {},
900
910
  _a$5[calc.name] = calc,
901
911
  _a$5[lessThan.name] = lessThan,
902
912
  _a$5[greaterThan.name] = greaterThan,
903
- _a$5[add.name] = add,
904
- _a$5[subtract.name] = subtract,
913
+ _a$5[add$1.name] = add$1,
914
+ _a$5[subtract$1.name] = subtract$1,
905
915
  _a$5[multiply.name] = multiply,
906
916
  _a$5[divide.name] = divide,
907
917
  _a$5);
@@ -963,21 +973,23 @@ var listItem = {
963
973
  },
964
974
  outputs: {
965
975
  item: "any",
976
+ others: "any",
966
977
  },
967
978
  impl: function (inputs) { return __awaiter(void 0, void 0, void 0, function () {
979
+ var item, others;
968
980
  return __generator(this, function (_a) {
981
+ item = binaryOnTreeBranch(inputs.list || {}, inputs.index || {}, function (branch, indices) {
982
+ if (indices) {
983
+ return indices.map(function (i) { return branch[i]; });
984
+ }
985
+ });
986
+ others = binaryOnTreeBranch(inputs.list || {}, inputs.index || {}, function (branch, indices) {
987
+ console.log("others", branch, indices);
988
+ return branch.filter(function (i) { return !(indices === null || indices === void 0 ? void 0 : indices.includes(i)); });
989
+ });
969
990
  return [2 /*return*/, {
970
- // item: mapTreeBranch(inputs.list, (branch, path) => {
971
- // let indices = getBranch(inputs.index, path);
972
- // if (indices) {
973
- // return indices.map((i) => branch[i]);
974
- // }
975
- // }),
976
- item: binaryOnTreeBranch(inputs.list || {}, inputs.index || {}, function (branch, indices) {
977
- if (indices) {
978
- return indices.map(function (i) { return branch[i]; });
979
- }
980
- }),
991
+ item: item,
992
+ others: others,
981
993
  }];
982
994
  });
983
995
  }); },
@@ -1524,116 +1536,1902 @@ var Engine = /** @class */ (function () {
1524
1536
  }
1525
1537
  });
1526
1538
  });
1527
- return newFn;
1539
+ return newFn;
1540
+ };
1541
+ Engine.prototype.applyEdgeDelete = function (oldFn, fromNode, toNode, fromField, toField) {
1542
+ var newFn = __assign(__assign({}, oldFn), { body: __assign({}, oldFn.body) });
1543
+ var from = newFn.body[fromNode];
1544
+ var to = newFn.body[toNode];
1545
+ if (!from || !to) {
1546
+ console.warn("Invalid nodes for edge deletion");
1547
+ return newFn;
1548
+ }
1549
+ if (to.inputs && to.inputs[toField] === "<".concat(fromNode, ".").concat(fromField, ">")) {
1550
+ delete to.inputs[toField];
1551
+ }
1552
+ else {
1553
+ console.warn("No matching edge found to delete");
1554
+ }
1555
+ return newFn;
1556
+ };
1557
+ Engine.prototype.applyNodeAdd = function (oldFn, nodeName, callback) {
1558
+ var newFn = __assign(__assign({}, oldFn), { body: __assign({}, oldFn.body) });
1559
+ var id = uid$1();
1560
+ // ensure unique id
1561
+ while (newFn.body[id]) {
1562
+ id = uid$1();
1563
+ }
1564
+ // get inputs defaults
1565
+ var inputs = {};
1566
+ Object.entries(this.fnIndex[nodeName].inputs || {}).forEach(function (_a) {
1567
+ var _b = __read(_a, 2), key = _b[0], def = _b[1];
1568
+ var normDef = normalizeVarDef(def);
1569
+ if (normDef.default !== undefined) {
1570
+ inputs[key] = normDef.default;
1571
+ }
1572
+ });
1573
+ // get params defaults
1574
+ var params = {};
1575
+ Object.entries(this.fnIndex[nodeName].params || {}).forEach(function (_a) {
1576
+ var _b = __read(_a, 2), key = _b[0], def = _b[1];
1577
+ var normDef = normalizeVarDef(def);
1578
+ if (normDef.default !== undefined) {
1579
+ params[key] = normDef.default;
1580
+ }
1581
+ });
1582
+ var newCall = {
1583
+ name: nodeName,
1584
+ inputs: inputs,
1585
+ params: params,
1586
+ };
1587
+ newFn.body[id] = newCall;
1588
+ callback === null || callback === void 0 ? void 0 : callback(newCall, id);
1589
+ return topSort(newFn);
1590
+ };
1591
+ Engine.prototype.applyNodeConnect = function (oldFn, fromNode, toNode, fromField, toField) {
1592
+ var newFn = __assign(__assign({}, oldFn), { body: __assign({}, oldFn.body) });
1593
+ var from = newFn.body[fromNode];
1594
+ var to = __assign({}, newFn.body[toNode]);
1595
+ if (!from || !to) {
1596
+ console.warn("Invalid nodes for connection");
1597
+ return newFn;
1598
+ }
1599
+ if (!to.inputs) {
1600
+ to.inputs = {};
1601
+ }
1602
+ // add the reference
1603
+ to.inputs[toField] = "<".concat(fromNode, ".").concat(fromField, ">");
1604
+ newFn.body[toNode] = to;
1605
+ return topSort(newFn);
1606
+ };
1607
+ return Engine;
1608
+ }());
1609
+
1610
+ /**
1611
+ * Create the React Context
1612
+ */ const DndContext = createContext({
1613
+ dragDropManager: undefined
1614
+ });
1615
+
1616
+ /**
1617
+ * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
1618
+ *
1619
+ * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
1620
+ * during build.
1621
+ * @param {number} code
1622
+ */
1623
+ function formatProdErrorMessage(code) {
1624
+ return "Minified Redux error #" + code + "; visit https://redux.js.org/Errors?code=" + code + " for the full message or " + 'use the non-minified dev environment for full errors. ';
1625
+ }
1626
+
1627
+ // Inlined version of the `symbol-observable` polyfill
1628
+ var $$observable = (function () {
1629
+ return typeof Symbol === 'function' && Symbol.observable || '@@observable';
1630
+ })();
1631
+
1632
+ /**
1633
+ * These are private action types reserved by Redux.
1634
+ * For any unknown actions, you must return the current state.
1635
+ * If the current state is undefined, you must return the initial state.
1636
+ * Do not reference these action types directly in your code.
1637
+ */
1638
+ var randomString = function randomString() {
1639
+ return Math.random().toString(36).substring(7).split('').join('.');
1640
+ };
1641
+
1642
+ var ActionTypes = {
1643
+ INIT: "@@redux/INIT" + randomString(),
1644
+ REPLACE: "@@redux/REPLACE" + randomString()};
1645
+
1646
+ /**
1647
+ * @param {any} obj The object to inspect.
1648
+ * @returns {boolean} True if the argument appears to be a plain object.
1649
+ */
1650
+ function isPlainObject(obj) {
1651
+ if (typeof obj !== 'object' || obj === null) return false;
1652
+ var proto = obj;
1653
+
1654
+ while (Object.getPrototypeOf(proto) !== null) {
1655
+ proto = Object.getPrototypeOf(proto);
1656
+ }
1657
+
1658
+ return Object.getPrototypeOf(obj) === proto;
1659
+ }
1660
+
1661
+ // Inlined / shortened version of `kindOf` from https://github.com/jonschlinkert/kind-of
1662
+ function miniKindOf(val) {
1663
+ if (val === void 0) return 'undefined';
1664
+ if (val === null) return 'null';
1665
+ var type = typeof val;
1666
+
1667
+ switch (type) {
1668
+ case 'boolean':
1669
+ case 'string':
1670
+ case 'number':
1671
+ case 'symbol':
1672
+ case 'function':
1673
+ {
1674
+ return type;
1675
+ }
1676
+ }
1677
+
1678
+ if (Array.isArray(val)) return 'array';
1679
+ if (isDate(val)) return 'date';
1680
+ if (isError(val)) return 'error';
1681
+ var constructorName = ctorName(val);
1682
+
1683
+ switch (constructorName) {
1684
+ case 'Symbol':
1685
+ case 'Promise':
1686
+ case 'WeakMap':
1687
+ case 'WeakSet':
1688
+ case 'Map':
1689
+ case 'Set':
1690
+ return constructorName;
1691
+ } // other
1692
+
1693
+
1694
+ return type.slice(8, -1).toLowerCase().replace(/\s/g, '');
1695
+ }
1696
+
1697
+ function ctorName(val) {
1698
+ return typeof val.constructor === 'function' ? val.constructor.name : null;
1699
+ }
1700
+
1701
+ function isError(val) {
1702
+ return val instanceof Error || typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number';
1703
+ }
1704
+
1705
+ function isDate(val) {
1706
+ if (val instanceof Date) return true;
1707
+ return typeof val.toDateString === 'function' && typeof val.getDate === 'function' && typeof val.setDate === 'function';
1708
+ }
1709
+
1710
+ function kindOf(val) {
1711
+ var typeOfVal = typeof val;
1712
+
1713
+ if (process.env.NODE_ENV !== 'production') {
1714
+ typeOfVal = miniKindOf(val);
1715
+ }
1716
+
1717
+ return typeOfVal;
1718
+ }
1719
+
1720
+ /**
1721
+ * @deprecated
1722
+ *
1723
+ * **We recommend using the `configureStore` method
1724
+ * of the `@reduxjs/toolkit` package**, which replaces `createStore`.
1725
+ *
1726
+ * Redux Toolkit is our recommended approach for writing Redux logic today,
1727
+ * including store setup, reducers, data fetching, and more.
1728
+ *
1729
+ * **For more details, please read this Redux docs page:**
1730
+ * **https://redux.js.org/introduction/why-rtk-is-redux-today**
1731
+ *
1732
+ * `configureStore` from Redux Toolkit is an improved version of `createStore` that
1733
+ * simplifies setup and helps avoid common bugs.
1734
+ *
1735
+ * You should not be using the `redux` core package by itself today, except for learning purposes.
1736
+ * The `createStore` method from the core `redux` package will not be removed, but we encourage
1737
+ * all users to migrate to using Redux Toolkit for all Redux code.
1738
+ *
1739
+ * If you want to use `createStore` without this visual deprecation warning, use
1740
+ * the `legacy_createStore` import instead:
1741
+ *
1742
+ * `import { legacy_createStore as createStore} from 'redux'`
1743
+ *
1744
+ */
1745
+
1746
+ function createStore(reducer, preloadedState, enhancer) {
1747
+ var _ref2;
1748
+
1749
+ if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {
1750
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(0) : 'It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.');
1751
+ }
1752
+
1753
+ if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
1754
+ enhancer = preloadedState;
1755
+ preloadedState = undefined;
1756
+ }
1757
+
1758
+ if (typeof enhancer !== 'undefined') {
1759
+ if (typeof enhancer !== 'function') {
1760
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(1) : "Expected the enhancer to be a function. Instead, received: '" + kindOf(enhancer) + "'");
1761
+ }
1762
+
1763
+ return enhancer(createStore)(reducer, preloadedState);
1764
+ }
1765
+
1766
+ if (typeof reducer !== 'function') {
1767
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(2) : "Expected the root reducer to be a function. Instead, received: '" + kindOf(reducer) + "'");
1768
+ }
1769
+
1770
+ var currentReducer = reducer;
1771
+ var currentState = preloadedState;
1772
+ var currentListeners = [];
1773
+ var nextListeners = currentListeners;
1774
+ var isDispatching = false;
1775
+ /**
1776
+ * This makes a shallow copy of currentListeners so we can use
1777
+ * nextListeners as a temporary list while dispatching.
1778
+ *
1779
+ * This prevents any bugs around consumers calling
1780
+ * subscribe/unsubscribe in the middle of a dispatch.
1781
+ */
1782
+
1783
+ function ensureCanMutateNextListeners() {
1784
+ if (nextListeners === currentListeners) {
1785
+ nextListeners = currentListeners.slice();
1786
+ }
1787
+ }
1788
+ /**
1789
+ * Reads the state tree managed by the store.
1790
+ *
1791
+ * @returns {any} The current state tree of your application.
1792
+ */
1793
+
1794
+
1795
+ function getState() {
1796
+ if (isDispatching) {
1797
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(3) : 'You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.');
1798
+ }
1799
+
1800
+ return currentState;
1801
+ }
1802
+ /**
1803
+ * Adds a change listener. It will be called any time an action is dispatched,
1804
+ * and some part of the state tree may potentially have changed. You may then
1805
+ * call `getState()` to read the current state tree inside the callback.
1806
+ *
1807
+ * You may call `dispatch()` from a change listener, with the following
1808
+ * caveats:
1809
+ *
1810
+ * 1. The subscriptions are snapshotted just before every `dispatch()` call.
1811
+ * If you subscribe or unsubscribe while the listeners are being invoked, this
1812
+ * will not have any effect on the `dispatch()` that is currently in progress.
1813
+ * However, the next `dispatch()` call, whether nested or not, will use a more
1814
+ * recent snapshot of the subscription list.
1815
+ *
1816
+ * 2. The listener should not expect to see all state changes, as the state
1817
+ * might have been updated multiple times during a nested `dispatch()` before
1818
+ * the listener is called. It is, however, guaranteed that all subscribers
1819
+ * registered before the `dispatch()` started will be called with the latest
1820
+ * state by the time it exits.
1821
+ *
1822
+ * @param {Function} listener A callback to be invoked on every dispatch.
1823
+ * @returns {Function} A function to remove this change listener.
1824
+ */
1825
+
1826
+
1827
+ function subscribe(listener) {
1828
+ if (typeof listener !== 'function') {
1829
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(4) : "Expected the listener to be a function. Instead, received: '" + kindOf(listener) + "'");
1830
+ }
1831
+
1832
+ if (isDispatching) {
1833
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(5) : 'You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');
1834
+ }
1835
+
1836
+ var isSubscribed = true;
1837
+ ensureCanMutateNextListeners();
1838
+ nextListeners.push(listener);
1839
+ return function unsubscribe() {
1840
+ if (!isSubscribed) {
1841
+ return;
1842
+ }
1843
+
1844
+ if (isDispatching) {
1845
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(6) : 'You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');
1846
+ }
1847
+
1848
+ isSubscribed = false;
1849
+ ensureCanMutateNextListeners();
1850
+ var index = nextListeners.indexOf(listener);
1851
+ nextListeners.splice(index, 1);
1852
+ currentListeners = null;
1853
+ };
1854
+ }
1855
+ /**
1856
+ * Dispatches an action. It is the only way to trigger a state change.
1857
+ *
1858
+ * The `reducer` function, used to create the store, will be called with the
1859
+ * current state tree and the given `action`. Its return value will
1860
+ * be considered the **next** state of the tree, and the change listeners
1861
+ * will be notified.
1862
+ *
1863
+ * The base implementation only supports plain object actions. If you want to
1864
+ * dispatch a Promise, an Observable, a thunk, or something else, you need to
1865
+ * wrap your store creating function into the corresponding middleware. For
1866
+ * example, see the documentation for the `redux-thunk` package. Even the
1867
+ * middleware will eventually dispatch plain object actions using this method.
1868
+ *
1869
+ * @param {Object} action A plain object representing “what changed”. It is
1870
+ * a good idea to keep actions serializable so you can record and replay user
1871
+ * sessions, or use the time travelling `redux-devtools`. An action must have
1872
+ * a `type` property which may not be `undefined`. It is a good idea to use
1873
+ * string constants for action types.
1874
+ *
1875
+ * @returns {Object} For convenience, the same action object you dispatched.
1876
+ *
1877
+ * Note that, if you use a custom middleware, it may wrap `dispatch()` to
1878
+ * return something else (for example, a Promise you can await).
1879
+ */
1880
+
1881
+
1882
+ function dispatch(action) {
1883
+ if (!isPlainObject(action)) {
1884
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(7) : "Actions must be plain objects. Instead, the actual type was: '" + kindOf(action) + "'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.");
1885
+ }
1886
+
1887
+ if (typeof action.type === 'undefined') {
1888
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(8) : 'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');
1889
+ }
1890
+
1891
+ if (isDispatching) {
1892
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(9) : 'Reducers may not dispatch actions.');
1893
+ }
1894
+
1895
+ try {
1896
+ isDispatching = true;
1897
+ currentState = currentReducer(currentState, action);
1898
+ } finally {
1899
+ isDispatching = false;
1900
+ }
1901
+
1902
+ var listeners = currentListeners = nextListeners;
1903
+
1904
+ for (var i = 0; i < listeners.length; i++) {
1905
+ var listener = listeners[i];
1906
+ listener();
1907
+ }
1908
+
1909
+ return action;
1910
+ }
1911
+ /**
1912
+ * Replaces the reducer currently used by the store to calculate the state.
1913
+ *
1914
+ * You might need this if your app implements code splitting and you want to
1915
+ * load some of the reducers dynamically. You might also need this if you
1916
+ * implement a hot reloading mechanism for Redux.
1917
+ *
1918
+ * @param {Function} nextReducer The reducer for the store to use instead.
1919
+ * @returns {void}
1920
+ */
1921
+
1922
+
1923
+ function replaceReducer(nextReducer) {
1924
+ if (typeof nextReducer !== 'function') {
1925
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(10) : "Expected the nextReducer to be a function. Instead, received: '" + kindOf(nextReducer));
1926
+ }
1927
+
1928
+ currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT.
1929
+ // Any reducers that existed in both the new and old rootReducer
1930
+ // will receive the previous state. This effectively populates
1931
+ // the new state tree with any relevant data from the old one.
1932
+
1933
+ dispatch({
1934
+ type: ActionTypes.REPLACE
1935
+ });
1936
+ }
1937
+ /**
1938
+ * Interoperability point for observable/reactive libraries.
1939
+ * @returns {observable} A minimal observable of state changes.
1940
+ * For more information, see the observable proposal:
1941
+ * https://github.com/tc39/proposal-observable
1942
+ */
1943
+
1944
+
1945
+ function observable() {
1946
+ var _ref;
1947
+
1948
+ var outerSubscribe = subscribe;
1949
+ return _ref = {
1950
+ /**
1951
+ * The minimal observable subscription method.
1952
+ * @param {Object} observer Any object that can be used as an observer.
1953
+ * The observer object should have a `next` method.
1954
+ * @returns {subscription} An object with an `unsubscribe` method that can
1955
+ * be used to unsubscribe the observable from the store, and prevent further
1956
+ * emission of values from the observable.
1957
+ */
1958
+ subscribe: function subscribe(observer) {
1959
+ if (typeof observer !== 'object' || observer === null) {
1960
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(11) : "Expected the observer to be an object. Instead, received: '" + kindOf(observer) + "'");
1961
+ }
1962
+
1963
+ function observeState() {
1964
+ if (observer.next) {
1965
+ observer.next(getState());
1966
+ }
1967
+ }
1968
+
1969
+ observeState();
1970
+ var unsubscribe = outerSubscribe(observeState);
1971
+ return {
1972
+ unsubscribe: unsubscribe
1973
+ };
1974
+ }
1975
+ }, _ref[$$observable] = function () {
1976
+ return this;
1977
+ }, _ref;
1978
+ } // When a store is created, an "INIT" action is dispatched so that every
1979
+ // reducer returns their initial state. This effectively populates
1980
+ // the initial state tree.
1981
+
1982
+
1983
+ dispatch({
1984
+ type: ActionTypes.INIT
1985
+ });
1986
+ return _ref2 = {
1987
+ dispatch: dispatch,
1988
+ subscribe: subscribe,
1989
+ getState: getState,
1990
+ replaceReducer: replaceReducer
1991
+ }, _ref2[$$observable] = observable, _ref2;
1992
+ }
1993
+
1994
+ /**
1995
+ * Use invariant() to assert state which your program assumes to be true.
1996
+ *
1997
+ * Provide sprintf-style format (only %s is supported) and arguments
1998
+ * to provide information about what broke and what you were
1999
+ * expecting.
2000
+ *
2001
+ * The invariant message will be stripped in production, but the invariant
2002
+ * will remain to ensure logic does not differ in production.
2003
+ */ function invariant(condition, format, ...args) {
2004
+ if (isProduction()) {
2005
+ if (format === undefined) {
2006
+ throw new Error('invariant requires an error message argument');
2007
+ }
2008
+ }
2009
+ if (!condition) {
2010
+ let error;
2011
+ if (format === undefined) {
2012
+ error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
2013
+ } else {
2014
+ let argIndex = 0;
2015
+ error = new Error(format.replace(/%s/g, function() {
2016
+ return args[argIndex++];
2017
+ }));
2018
+ error.name = 'Invariant Violation';
2019
+ }
2020
+ error.framesToPop = 1 // we don't care about invariant's own frame
2021
+ ;
2022
+ throw error;
2023
+ }
2024
+ }
2025
+ function isProduction() {
2026
+ return typeof process !== 'undefined' && process.env['NODE_ENV'] === 'production';
2027
+ }
2028
+
2029
+ // cheap lodash replacements
2030
+ /**
2031
+ * drop-in replacement for _.get
2032
+ * @param obj
2033
+ * @param path
2034
+ * @param defaultValue
2035
+ */ function get(obj, path, defaultValue) {
2036
+ return path.split('.').reduce((a, c)=>a && a[c] ? a[c] : defaultValue || null
2037
+ , obj);
2038
+ }
2039
+ /**
2040
+ * drop-in replacement for _.without
2041
+ */ function without(items, item) {
2042
+ return items.filter((i)=>i !== item
2043
+ );
2044
+ }
2045
+ /**
2046
+ * drop-in replacement for _.isString
2047
+ * @param input
2048
+ */ function isObject(input) {
2049
+ return typeof input === 'object';
2050
+ }
2051
+ /**
2052
+ * replacement for _.xor
2053
+ * @param itemsA
2054
+ * @param itemsB
2055
+ */ function xor(itemsA, itemsB) {
2056
+ const map = new Map();
2057
+ const insertItem = (item)=>{
2058
+ map.set(item, map.has(item) ? map.get(item) + 1 : 1);
2059
+ };
2060
+ itemsA.forEach(insertItem);
2061
+ itemsB.forEach(insertItem);
2062
+ const result = [];
2063
+ map.forEach((count, key)=>{
2064
+ if (count === 1) {
2065
+ result.push(key);
2066
+ }
2067
+ });
2068
+ return result;
2069
+ }
2070
+ /**
2071
+ * replacement for _.intersection
2072
+ * @param itemsA
2073
+ * @param itemsB
2074
+ */ function intersection(itemsA, itemsB) {
2075
+ return itemsA.filter((t)=>itemsB.indexOf(t) > -1
2076
+ );
2077
+ }
2078
+
2079
+ const INIT_COORDS = 'dnd-core/INIT_COORDS';
2080
+ const BEGIN_DRAG = 'dnd-core/BEGIN_DRAG';
2081
+ const PUBLISH_DRAG_SOURCE = 'dnd-core/PUBLISH_DRAG_SOURCE';
2082
+ const HOVER = 'dnd-core/HOVER';
2083
+ const DROP = 'dnd-core/DROP';
2084
+ const END_DRAG = 'dnd-core/END_DRAG';
2085
+
2086
+ function setClientOffset(clientOffset, sourceClientOffset) {
2087
+ return {
2088
+ type: INIT_COORDS,
2089
+ payload: {
2090
+ sourceClientOffset: sourceClientOffset || null,
2091
+ clientOffset: clientOffset || null
2092
+ }
2093
+ };
2094
+ }
2095
+
2096
+ const ResetCoordinatesAction = {
2097
+ type: INIT_COORDS,
2098
+ payload: {
2099
+ clientOffset: null,
2100
+ sourceClientOffset: null
2101
+ }
2102
+ };
2103
+ function createBeginDrag(manager) {
2104
+ return function beginDrag(sourceIds = [], options = {
2105
+ publishSource: true
2106
+ }) {
2107
+ const { publishSource =true , clientOffset , getSourceClientOffset , } = options;
2108
+ const monitor = manager.getMonitor();
2109
+ const registry = manager.getRegistry();
2110
+ // Initialize the coordinates using the client offset
2111
+ manager.dispatch(setClientOffset(clientOffset));
2112
+ verifyInvariants$1(sourceIds, monitor, registry);
2113
+ // Get the draggable source
2114
+ const sourceId = getDraggableSource(sourceIds, monitor);
2115
+ if (sourceId == null) {
2116
+ manager.dispatch(ResetCoordinatesAction);
2117
+ return;
2118
+ }
2119
+ // Get the source client offset
2120
+ let sourceClientOffset = null;
2121
+ if (clientOffset) {
2122
+ if (!getSourceClientOffset) {
2123
+ throw new Error('getSourceClientOffset must be defined');
2124
+ }
2125
+ verifyGetSourceClientOffsetIsFunction(getSourceClientOffset);
2126
+ sourceClientOffset = getSourceClientOffset(sourceId);
2127
+ }
2128
+ // Initialize the full coordinates
2129
+ manager.dispatch(setClientOffset(clientOffset, sourceClientOffset));
2130
+ const source = registry.getSource(sourceId);
2131
+ const item = source.beginDrag(monitor, sourceId);
2132
+ // If source.beginDrag returns null, this is an indicator to cancel the drag
2133
+ if (item == null) {
2134
+ return undefined;
2135
+ }
2136
+ verifyItemIsObject(item);
2137
+ registry.pinSource(sourceId);
2138
+ const itemType = registry.getSourceType(sourceId);
2139
+ return {
2140
+ type: BEGIN_DRAG,
2141
+ payload: {
2142
+ itemType,
2143
+ item,
2144
+ sourceId,
2145
+ clientOffset: clientOffset || null,
2146
+ sourceClientOffset: sourceClientOffset || null,
2147
+ isSourcePublic: !!publishSource
2148
+ }
2149
+ };
2150
+ };
2151
+ }
2152
+ function verifyInvariants$1(sourceIds, monitor, registry) {
2153
+ invariant(!monitor.isDragging(), 'Cannot call beginDrag while dragging.');
2154
+ sourceIds.forEach(function(sourceId) {
2155
+ invariant(registry.getSource(sourceId), 'Expected sourceIds to be registered.');
2156
+ });
2157
+ }
2158
+ function verifyGetSourceClientOffsetIsFunction(getSourceClientOffset) {
2159
+ invariant(typeof getSourceClientOffset === 'function', 'When clientOffset is provided, getSourceClientOffset must be a function.');
2160
+ }
2161
+ function verifyItemIsObject(item) {
2162
+ invariant(isObject(item), 'Item must be an object.');
2163
+ }
2164
+ function getDraggableSource(sourceIds, monitor) {
2165
+ let sourceId = null;
2166
+ for(let i = sourceIds.length - 1; i >= 0; i--){
2167
+ if (monitor.canDragSource(sourceIds[i])) {
2168
+ sourceId = sourceIds[i];
2169
+ break;
2170
+ }
2171
+ }
2172
+ return sourceId;
2173
+ }
2174
+
2175
+ function _defineProperty$3(obj, key, value) {
2176
+ if (key in obj) {
2177
+ Object.defineProperty(obj, key, {
2178
+ value: value,
2179
+ enumerable: true,
2180
+ configurable: true,
2181
+ writable: true
2182
+ });
2183
+ } else {
2184
+ obj[key] = value;
2185
+ }
2186
+ return obj;
2187
+ }
2188
+ function _objectSpread$3(target) {
2189
+ for(var i = 1; i < arguments.length; i++){
2190
+ var source = arguments[i] != null ? arguments[i] : {};
2191
+ var ownKeys = Object.keys(source);
2192
+ if (typeof Object.getOwnPropertySymbols === 'function') {
2193
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
2194
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
2195
+ }));
2196
+ }
2197
+ ownKeys.forEach(function(key) {
2198
+ _defineProperty$3(target, key, source[key]);
2199
+ });
2200
+ }
2201
+ return target;
2202
+ }
2203
+ function createDrop(manager) {
2204
+ return function drop(options = {}) {
2205
+ const monitor = manager.getMonitor();
2206
+ const registry = manager.getRegistry();
2207
+ verifyInvariants(monitor);
2208
+ const targetIds = getDroppableTargets(monitor);
2209
+ // Multiple actions are dispatched here, which is why this doesn't return an action
2210
+ targetIds.forEach((targetId, index)=>{
2211
+ const dropResult = determineDropResult(targetId, index, registry, monitor);
2212
+ const action = {
2213
+ type: DROP,
2214
+ payload: {
2215
+ dropResult: _objectSpread$3({}, options, dropResult)
2216
+ }
2217
+ };
2218
+ manager.dispatch(action);
2219
+ });
2220
+ };
2221
+ }
2222
+ function verifyInvariants(monitor) {
2223
+ invariant(monitor.isDragging(), 'Cannot call drop while not dragging.');
2224
+ invariant(!monitor.didDrop(), 'Cannot call drop twice during one drag operation.');
2225
+ }
2226
+ function determineDropResult(targetId, index, registry, monitor) {
2227
+ const target = registry.getTarget(targetId);
2228
+ let dropResult = target ? target.drop(monitor, targetId) : undefined;
2229
+ verifyDropResultType(dropResult);
2230
+ if (typeof dropResult === 'undefined') {
2231
+ dropResult = index === 0 ? {} : monitor.getDropResult();
2232
+ }
2233
+ return dropResult;
2234
+ }
2235
+ function verifyDropResultType(dropResult) {
2236
+ invariant(typeof dropResult === 'undefined' || isObject(dropResult), 'Drop result must either be an object or undefined.');
2237
+ }
2238
+ function getDroppableTargets(monitor) {
2239
+ const targetIds = monitor.getTargetIds().filter(monitor.canDropOnTarget, monitor);
2240
+ targetIds.reverse();
2241
+ return targetIds;
2242
+ }
2243
+
2244
+ function createEndDrag(manager) {
2245
+ return function endDrag() {
2246
+ const monitor = manager.getMonitor();
2247
+ const registry = manager.getRegistry();
2248
+ verifyIsDragging(monitor);
2249
+ const sourceId = monitor.getSourceId();
2250
+ if (sourceId != null) {
2251
+ const source = registry.getSource(sourceId, true);
2252
+ source.endDrag(monitor, sourceId);
2253
+ registry.unpinSource();
2254
+ }
2255
+ return {
2256
+ type: END_DRAG
2257
+ };
2258
+ };
2259
+ }
2260
+ function verifyIsDragging(monitor) {
2261
+ invariant(monitor.isDragging(), 'Cannot call endDrag while not dragging.');
2262
+ }
2263
+
2264
+ function matchesType(targetType, draggedItemType) {
2265
+ if (draggedItemType === null) {
2266
+ return targetType === null;
2267
+ }
2268
+ return Array.isArray(targetType) ? targetType.some((t)=>t === draggedItemType
2269
+ ) : targetType === draggedItemType;
2270
+ }
2271
+
2272
+ function createHover(manager) {
2273
+ return function hover(targetIdsArg, { clientOffset } = {}) {
2274
+ verifyTargetIdsIsArray(targetIdsArg);
2275
+ const targetIds = targetIdsArg.slice(0);
2276
+ const monitor = manager.getMonitor();
2277
+ const registry = manager.getRegistry();
2278
+ const draggedItemType = monitor.getItemType();
2279
+ removeNonMatchingTargetIds(targetIds, registry, draggedItemType);
2280
+ checkInvariants(targetIds, monitor, registry);
2281
+ hoverAllTargets(targetIds, monitor, registry);
2282
+ return {
2283
+ type: HOVER,
2284
+ payload: {
2285
+ targetIds,
2286
+ clientOffset: clientOffset || null
2287
+ }
2288
+ };
2289
+ };
2290
+ }
2291
+ function verifyTargetIdsIsArray(targetIdsArg) {
2292
+ invariant(Array.isArray(targetIdsArg), 'Expected targetIds to be an array.');
2293
+ }
2294
+ function checkInvariants(targetIds, monitor, registry) {
2295
+ invariant(monitor.isDragging(), 'Cannot call hover while not dragging.');
2296
+ invariant(!monitor.didDrop(), 'Cannot call hover after drop.');
2297
+ for(let i = 0; i < targetIds.length; i++){
2298
+ const targetId = targetIds[i];
2299
+ invariant(targetIds.lastIndexOf(targetId) === i, 'Expected targetIds to be unique in the passed array.');
2300
+ const target = registry.getTarget(targetId);
2301
+ invariant(target, 'Expected targetIds to be registered.');
2302
+ }
2303
+ }
2304
+ function removeNonMatchingTargetIds(targetIds, registry, draggedItemType) {
2305
+ // Remove those targetIds that don't match the targetType. This
2306
+ // fixes shallow isOver which would only be non-shallow because of
2307
+ // non-matching targets.
2308
+ for(let i = targetIds.length - 1; i >= 0; i--){
2309
+ const targetId = targetIds[i];
2310
+ const targetType = registry.getTargetType(targetId);
2311
+ if (!matchesType(targetType, draggedItemType)) {
2312
+ targetIds.splice(i, 1);
2313
+ }
2314
+ }
2315
+ }
2316
+ function hoverAllTargets(targetIds, monitor, registry) {
2317
+ // Finally call hover on all matching targets.
2318
+ targetIds.forEach(function(targetId) {
2319
+ const target = registry.getTarget(targetId);
2320
+ target.hover(monitor, targetId);
2321
+ });
2322
+ }
2323
+
2324
+ function createPublishDragSource(manager) {
2325
+ return function publishDragSource() {
2326
+ const monitor = manager.getMonitor();
2327
+ if (monitor.isDragging()) {
2328
+ return {
2329
+ type: PUBLISH_DRAG_SOURCE
2330
+ };
2331
+ }
2332
+ return;
2333
+ };
2334
+ }
2335
+
2336
+ function createDragDropActions(manager) {
2337
+ return {
2338
+ beginDrag: createBeginDrag(manager),
2339
+ publishDragSource: createPublishDragSource(manager),
2340
+ hover: createHover(manager),
2341
+ drop: createDrop(manager),
2342
+ endDrag: createEndDrag(manager)
2343
+ };
2344
+ }
2345
+
2346
+ class DragDropManagerImpl {
2347
+ receiveBackend(backend) {
2348
+ this.backend = backend;
2349
+ }
2350
+ getMonitor() {
2351
+ return this.monitor;
2352
+ }
2353
+ getBackend() {
2354
+ return this.backend;
2355
+ }
2356
+ getRegistry() {
2357
+ return this.monitor.registry;
2358
+ }
2359
+ getActions() {
2360
+ /* eslint-disable-next-line @typescript-eslint/no-this-alias */ const manager = this;
2361
+ const { dispatch } = this.store;
2362
+ function bindActionCreator(actionCreator) {
2363
+ return (...args)=>{
2364
+ const action = actionCreator.apply(manager, args);
2365
+ if (typeof action !== 'undefined') {
2366
+ dispatch(action);
2367
+ }
2368
+ };
2369
+ }
2370
+ const actions = createDragDropActions(this);
2371
+ return Object.keys(actions).reduce((boundActions, key)=>{
2372
+ const action = actions[key];
2373
+ boundActions[key] = bindActionCreator(action);
2374
+ return boundActions;
2375
+ }, {});
2376
+ }
2377
+ dispatch(action) {
2378
+ this.store.dispatch(action);
2379
+ }
2380
+ constructor(store, monitor){
2381
+ this.isSetUp = false;
2382
+ this.handleRefCountChange = ()=>{
2383
+ const shouldSetUp = this.store.getState().refCount > 0;
2384
+ if (this.backend) {
2385
+ if (shouldSetUp && !this.isSetUp) {
2386
+ this.backend.setup();
2387
+ this.isSetUp = true;
2388
+ } else if (!shouldSetUp && this.isSetUp) {
2389
+ this.backend.teardown();
2390
+ this.isSetUp = false;
2391
+ }
2392
+ }
2393
+ };
2394
+ this.store = store;
2395
+ this.monitor = monitor;
2396
+ store.subscribe(this.handleRefCountChange);
2397
+ }
2398
+ }
2399
+
2400
+ /**
2401
+ * Coordinate addition
2402
+ * @param a The first coordinate
2403
+ * @param b The second coordinate
2404
+ */ function add(a, b) {
2405
+ return {
2406
+ x: a.x + b.x,
2407
+ y: a.y + b.y
2408
+ };
2409
+ }
2410
+ /**
2411
+ * Coordinate subtraction
2412
+ * @param a The first coordinate
2413
+ * @param b The second coordinate
2414
+ */ function subtract(a, b) {
2415
+ return {
2416
+ x: a.x - b.x,
2417
+ y: a.y - b.y
2418
+ };
2419
+ }
2420
+ /**
2421
+ * Returns the cartesian distance of the drag source component's position, based on its position
2422
+ * at the time when the current drag operation has started, and the movement difference.
2423
+ *
2424
+ * Returns null if no item is being dragged.
2425
+ *
2426
+ * @param state The offset state to compute from
2427
+ */ function getSourceClientOffset(state) {
2428
+ const { clientOffset , initialClientOffset , initialSourceClientOffset } = state;
2429
+ if (!clientOffset || !initialClientOffset || !initialSourceClientOffset) {
2430
+ return null;
2431
+ }
2432
+ return subtract(add(clientOffset, initialSourceClientOffset), initialClientOffset);
2433
+ }
2434
+ /**
2435
+ * Determines the x,y offset between the client offset and the initial client offset
2436
+ *
2437
+ * @param state The offset state to compute from
2438
+ */ function getDifferenceFromInitialOffset(state) {
2439
+ const { clientOffset , initialClientOffset } = state;
2440
+ if (!clientOffset || !initialClientOffset) {
2441
+ return null;
2442
+ }
2443
+ return subtract(clientOffset, initialClientOffset);
2444
+ }
2445
+
2446
+ const NONE = [];
2447
+ const ALL = [];
2448
+ NONE.__IS_NONE__ = true;
2449
+ ALL.__IS_ALL__ = true;
2450
+ /**
2451
+ * Determines if the given handler IDs are dirty or not.
2452
+ *
2453
+ * @param dirtyIds The set of dirty handler ids
2454
+ * @param handlerIds The set of handler ids to check
2455
+ */ function areDirty(dirtyIds, handlerIds) {
2456
+ if (dirtyIds === NONE) {
2457
+ return false;
2458
+ }
2459
+ if (dirtyIds === ALL || typeof handlerIds === 'undefined') {
2460
+ return true;
2461
+ }
2462
+ const commonIds = intersection(handlerIds, dirtyIds);
2463
+ return commonIds.length > 0;
2464
+ }
2465
+
2466
+ class DragDropMonitorImpl {
2467
+ subscribeToStateChange(listener, options = {}) {
2468
+ const { handlerIds } = options;
2469
+ invariant(typeof listener === 'function', 'listener must be a function.');
2470
+ invariant(typeof handlerIds === 'undefined' || Array.isArray(handlerIds), 'handlerIds, when specified, must be an array of strings.');
2471
+ let prevStateId = this.store.getState().stateId;
2472
+ const handleChange = ()=>{
2473
+ const state = this.store.getState();
2474
+ const currentStateId = state.stateId;
2475
+ try {
2476
+ const canSkipListener = currentStateId === prevStateId || currentStateId === prevStateId + 1 && !areDirty(state.dirtyHandlerIds, handlerIds);
2477
+ if (!canSkipListener) {
2478
+ listener();
2479
+ }
2480
+ } finally{
2481
+ prevStateId = currentStateId;
2482
+ }
2483
+ };
2484
+ return this.store.subscribe(handleChange);
2485
+ }
2486
+ subscribeToOffsetChange(listener) {
2487
+ invariant(typeof listener === 'function', 'listener must be a function.');
2488
+ let previousState = this.store.getState().dragOffset;
2489
+ const handleChange = ()=>{
2490
+ const nextState = this.store.getState().dragOffset;
2491
+ if (nextState === previousState) {
2492
+ return;
2493
+ }
2494
+ previousState = nextState;
2495
+ listener();
2496
+ };
2497
+ return this.store.subscribe(handleChange);
2498
+ }
2499
+ canDragSource(sourceId) {
2500
+ if (!sourceId) {
2501
+ return false;
2502
+ }
2503
+ const source = this.registry.getSource(sourceId);
2504
+ invariant(source, `Expected to find a valid source. sourceId=${sourceId}`);
2505
+ if (this.isDragging()) {
2506
+ return false;
2507
+ }
2508
+ return source.canDrag(this, sourceId);
2509
+ }
2510
+ canDropOnTarget(targetId) {
2511
+ // undefined on initial render
2512
+ if (!targetId) {
2513
+ return false;
2514
+ }
2515
+ const target = this.registry.getTarget(targetId);
2516
+ invariant(target, `Expected to find a valid target. targetId=${targetId}`);
2517
+ if (!this.isDragging() || this.didDrop()) {
2518
+ return false;
2519
+ }
2520
+ const targetType = this.registry.getTargetType(targetId);
2521
+ const draggedItemType = this.getItemType();
2522
+ return matchesType(targetType, draggedItemType) && target.canDrop(this, targetId);
2523
+ }
2524
+ isDragging() {
2525
+ return Boolean(this.getItemType());
2526
+ }
2527
+ isDraggingSource(sourceId) {
2528
+ // undefined on initial render
2529
+ if (!sourceId) {
2530
+ return false;
2531
+ }
2532
+ const source = this.registry.getSource(sourceId, true);
2533
+ invariant(source, `Expected to find a valid source. sourceId=${sourceId}`);
2534
+ if (!this.isDragging() || !this.isSourcePublic()) {
2535
+ return false;
2536
+ }
2537
+ const sourceType = this.registry.getSourceType(sourceId);
2538
+ const draggedItemType = this.getItemType();
2539
+ if (sourceType !== draggedItemType) {
2540
+ return false;
2541
+ }
2542
+ return source.isDragging(this, sourceId);
2543
+ }
2544
+ isOverTarget(targetId, options = {
2545
+ shallow: false
2546
+ }) {
2547
+ // undefined on initial render
2548
+ if (!targetId) {
2549
+ return false;
2550
+ }
2551
+ const { shallow } = options;
2552
+ if (!this.isDragging()) {
2553
+ return false;
2554
+ }
2555
+ const targetType = this.registry.getTargetType(targetId);
2556
+ const draggedItemType = this.getItemType();
2557
+ if (draggedItemType && !matchesType(targetType, draggedItemType)) {
2558
+ return false;
2559
+ }
2560
+ const targetIds = this.getTargetIds();
2561
+ if (!targetIds.length) {
2562
+ return false;
2563
+ }
2564
+ const index = targetIds.indexOf(targetId);
2565
+ if (shallow) {
2566
+ return index === targetIds.length - 1;
2567
+ } else {
2568
+ return index > -1;
2569
+ }
2570
+ }
2571
+ getItemType() {
2572
+ return this.store.getState().dragOperation.itemType;
2573
+ }
2574
+ getItem() {
2575
+ return this.store.getState().dragOperation.item;
2576
+ }
2577
+ getSourceId() {
2578
+ return this.store.getState().dragOperation.sourceId;
2579
+ }
2580
+ getTargetIds() {
2581
+ return this.store.getState().dragOperation.targetIds;
2582
+ }
2583
+ getDropResult() {
2584
+ return this.store.getState().dragOperation.dropResult;
2585
+ }
2586
+ didDrop() {
2587
+ return this.store.getState().dragOperation.didDrop;
2588
+ }
2589
+ isSourcePublic() {
2590
+ return Boolean(this.store.getState().dragOperation.isSourcePublic);
2591
+ }
2592
+ getInitialClientOffset() {
2593
+ return this.store.getState().dragOffset.initialClientOffset;
2594
+ }
2595
+ getInitialSourceClientOffset() {
2596
+ return this.store.getState().dragOffset.initialSourceClientOffset;
2597
+ }
2598
+ getClientOffset() {
2599
+ return this.store.getState().dragOffset.clientOffset;
2600
+ }
2601
+ getSourceClientOffset() {
2602
+ return getSourceClientOffset(this.store.getState().dragOffset);
2603
+ }
2604
+ getDifferenceFromInitialOffset() {
2605
+ return getDifferenceFromInitialOffset(this.store.getState().dragOffset);
2606
+ }
2607
+ constructor(store, registry){
2608
+ this.store = store;
2609
+ this.registry = registry;
2610
+ }
2611
+ }
2612
+
2613
+ // Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that
2614
+ // have WebKitMutationObserver but not un-prefixed MutationObserver.
2615
+ // Must use `global` or `self` instead of `window` to work in both frames and web
2616
+ // workers. `global` is a provision of Browserify, Mr, Mrs, or Mop.
2617
+ /* globals self */ const scope = typeof global !== 'undefined' ? global : self;
2618
+ const BrowserMutationObserver = scope.MutationObserver || scope.WebKitMutationObserver;
2619
+ function makeRequestCallFromTimer(callback) {
2620
+ return function requestCall() {
2621
+ // We dispatch a timeout with a specified delay of 0 for engines that
2622
+ // can reliably accommodate that request. This will usually be snapped
2623
+ // to a 4 milisecond delay, but once we're flushing, there's no delay
2624
+ // between events.
2625
+ const timeoutHandle = setTimeout(handleTimer, 0);
2626
+ // However, since this timer gets frequently dropped in Firefox
2627
+ // workers, we enlist an interval handle that will try to fire
2628
+ // an event 20 times per second until it succeeds.
2629
+ const intervalHandle = setInterval(handleTimer, 50);
2630
+ function handleTimer() {
2631
+ // Whichever timer succeeds will cancel both timers and
2632
+ // execute the callback.
2633
+ clearTimeout(timeoutHandle);
2634
+ clearInterval(intervalHandle);
2635
+ callback();
2636
+ }
2637
+ };
2638
+ }
2639
+ // To request a high priority event, we induce a mutation observer by toggling
2640
+ // the text of a text node between "1" and "-1".
2641
+ function makeRequestCallFromMutationObserver(callback) {
2642
+ let toggle = 1;
2643
+ const observer = new BrowserMutationObserver(callback);
2644
+ const node = document.createTextNode('');
2645
+ observer.observe(node, {
2646
+ characterData: true
2647
+ });
2648
+ return function requestCall() {
2649
+ toggle = -toggle;
2650
+ node.data = toggle;
2651
+ };
2652
+ }
2653
+ const makeRequestCall = typeof BrowserMutationObserver === 'function' ? // reliably everywhere they are implemented.
2654
+ // They are implemented in all modern browsers.
2655
+ //
2656
+ // - Android 4-4.3
2657
+ // - Chrome 26-34
2658
+ // - Firefox 14-29
2659
+ // - Internet Explorer 11
2660
+ // - iPad Safari 6-7.1
2661
+ // - iPhone Safari 7-7.1
2662
+ // - Safari 6-7
2663
+ makeRequestCallFromMutationObserver : // task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera
2664
+ // 11-12, and in web workers in many engines.
2665
+ // Although message channels yield to any queued rendering and IO tasks, they
2666
+ // would be better than imposing the 4ms delay of timers.
2667
+ // However, they do not work reliably in Internet Explorer or Safari.
2668
+ // Internet Explorer 10 is the only browser that has setImmediate but does
2669
+ // not have MutationObservers.
2670
+ // Although setImmediate yields to the browser's renderer, it would be
2671
+ // preferrable to falling back to setTimeout since it does not have
2672
+ // the minimum 4ms penalty.
2673
+ // Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and
2674
+ // Desktop to a lesser extent) that renders both setImmediate and
2675
+ // MessageChannel useless for the purposes of ASAP.
2676
+ // https://github.com/kriskowal/q/issues/396
2677
+ // Timers are implemented universally.
2678
+ // We fall back to timers in workers in most engines, and in foreground
2679
+ // contexts in the following browsers.
2680
+ // However, note that even this simple case requires nuances to operate in a
2681
+ // broad spectrum of browsers.
2682
+ //
2683
+ // - Firefox 3-13
2684
+ // - Internet Explorer 6-9
2685
+ // - iPad Safari 4.3
2686
+ // - Lynx 2.8.7
2687
+ makeRequestCallFromTimer;
2688
+
2689
+ class AsapQueue {
2690
+ // Use the fastest means possible to execute a task in its own turn, with
2691
+ // priority over other events including IO, animation, reflow, and redraw
2692
+ // events in browsers.
2693
+ //
2694
+ // An exception thrown by a task will permanently interrupt the processing of
2695
+ // subsequent tasks. The higher level `asap` function ensures that if an
2696
+ // exception is thrown by a task, that the task queue will continue flushing as
2697
+ // soon as possible, but if you use `rawAsap` directly, you are responsible to
2698
+ // either ensure that no exceptions are thrown from your task, or to manually
2699
+ // call `rawAsap.requestFlush` if an exception is thrown.
2700
+ enqueueTask(task) {
2701
+ const { queue: q , requestFlush } = this;
2702
+ if (!q.length) {
2703
+ requestFlush();
2704
+ this.flushing = true;
2705
+ }
2706
+ // Equivalent to push, but avoids a function call.
2707
+ q[q.length] = task;
2708
+ }
2709
+ constructor(){
2710
+ this.queue = [];
2711
+ // We queue errors to ensure they are thrown in right order (FIFO).
2712
+ // Array-as-queue is good enough here, since we are just dealing with exceptions.
2713
+ this.pendingErrors = [];
2714
+ // Once a flush has been requested, no further calls to `requestFlush` are
2715
+ // necessary until the next `flush` completes.
2716
+ // @ts-ignore
2717
+ this.flushing = false;
2718
+ // The position of the next task to execute in the task queue. This is
2719
+ // preserved between calls to `flush` so that it can be resumed if
2720
+ // a task throws an exception.
2721
+ this.index = 0;
2722
+ // If a task schedules additional tasks recursively, the task queue can grow
2723
+ // unbounded. To prevent memory exhaustion, the task queue will periodically
2724
+ // truncate already-completed tasks.
2725
+ this.capacity = 1024;
2726
+ // The flush function processes all tasks that have been scheduled with
2727
+ // `rawAsap` unless and until one of those tasks throws an exception.
2728
+ // If a task throws an exception, `flush` ensures that its state will remain
2729
+ // consistent and will resume where it left off when called again.
2730
+ // However, `flush` does not make any arrangements to be called again if an
2731
+ // exception is thrown.
2732
+ this.flush = ()=>{
2733
+ const { queue: q } = this;
2734
+ while(this.index < q.length){
2735
+ const currentIndex = this.index;
2736
+ // Advance the index before calling the task. This ensures that we will
2737
+ // begin flushing on the next task the task throws an error.
2738
+ this.index++;
2739
+ q[currentIndex].call();
2740
+ // Prevent leaking memory for long chains of recursive calls to `asap`.
2741
+ // If we call `asap` within tasks scheduled by `asap`, the queue will
2742
+ // grow, but to avoid an O(n) walk for every task we execute, we don't
2743
+ // shift tasks off the queue after they have been executed.
2744
+ // Instead, we periodically shift 1024 tasks off the queue.
2745
+ if (this.index > this.capacity) {
2746
+ // Manually shift all values starting at the index back to the
2747
+ // beginning of the queue.
2748
+ for(let scan = 0, newLength = q.length - this.index; scan < newLength; scan++){
2749
+ q[scan] = q[scan + this.index];
2750
+ }
2751
+ q.length -= this.index;
2752
+ this.index = 0;
2753
+ }
2754
+ }
2755
+ q.length = 0;
2756
+ this.index = 0;
2757
+ this.flushing = false;
2758
+ };
2759
+ // In a web browser, exceptions are not fatal. However, to avoid
2760
+ // slowing down the queue of pending tasks, we rethrow the error in a
2761
+ // lower priority turn.
2762
+ this.registerPendingError = (err)=>{
2763
+ this.pendingErrors.push(err);
2764
+ this.requestErrorThrow();
2765
+ };
2766
+ // `requestFlush` requests that the high priority event queue be flushed as
2767
+ // soon as possible.
2768
+ // This is useful to prevent an error thrown in a task from stalling the event
2769
+ // queue if the exception handled by Node.js’s
2770
+ // `process.on("uncaughtException")` or by a domain.
2771
+ // `requestFlush` is implemented using a strategy based on data collected from
2772
+ // every available SauceLabs Selenium web driver worker at time of writing.
2773
+ // https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593
2774
+ this.requestFlush = makeRequestCall(this.flush);
2775
+ this.requestErrorThrow = makeRequestCallFromTimer(()=>{
2776
+ // Throw first error
2777
+ if (this.pendingErrors.length) {
2778
+ throw this.pendingErrors.shift();
2779
+ }
2780
+ });
2781
+ }
2782
+ } // The message channel technique was discovered by Malte Ubl and was the
2783
+ // original foundation for this library.
2784
+ // http://www.nonblocking.io/2011/06/windownexttick.html
2785
+ // Safari 6.0.5 (at least) intermittently fails to create message ports on a
2786
+ // page's first load. Thankfully, this version of Safari supports
2787
+ // MutationObservers, so we don't need to fall back in that case.
2788
+ // function makeRequestCallFromMessageChannel(callback) {
2789
+ // var channel = new MessageChannel();
2790
+ // channel.port1.onmessage = callback;
2791
+ // return function requestCall() {
2792
+ // channel.port2.postMessage(0);
2793
+ // };
2794
+ // }
2795
+ // For reasons explained above, we are also unable to use `setImmediate`
2796
+ // under any circumstances.
2797
+ // Even if we were, there is another bug in Internet Explorer 10.
2798
+ // It is not sufficient to assign `setImmediate` to `requestFlush` because
2799
+ // `setImmediate` must be called *by name* and therefore must be wrapped in a
2800
+ // closure.
2801
+ // Never forget.
2802
+ // function makeRequestCallFromSetImmediate(callback) {
2803
+ // return function requestCall() {
2804
+ // setImmediate(callback);
2805
+ // };
2806
+ // }
2807
+ // Safari 6.0 has a problem where timers will get lost while the user is
2808
+ // scrolling. This problem does not impact ASAP because Safari 6.0 supports
2809
+ // mutation observers, so that implementation is used instead.
2810
+ // However, if we ever elect to use timers in Safari, the prevalent work-around
2811
+ // is to add a scroll event listener that calls for a flush.
2812
+ // `setTimeout` does not call the passed callback if the delay is less than
2813
+ // approximately 7 in web workers in Firefox 8 through 18, and sometimes not
2814
+ // even then.
2815
+ // This is for `asap.js` only.
2816
+ // Its name will be periodically randomized to break any code that depends on
2817
+ // // its existence.
2818
+ // rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer
2819
+ // ASAP was originally a nextTick shim included in Q. This was factored out
2820
+ // into this ASAP package. It was later adapted to RSVP which made further
2821
+ // amendments. These decisions, particularly to marginalize MessageChannel and
2822
+ // to capture the MutationObserver implementation in a closure, were integrated
2823
+ // back into ASAP proper.
2824
+ // https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js
2825
+
2826
+ // `call`, just like a function.
2827
+ class RawTask {
2828
+ call() {
2829
+ try {
2830
+ this.task && this.task();
2831
+ } catch (error) {
2832
+ this.onError(error);
2833
+ } finally{
2834
+ this.task = null;
2835
+ this.release(this);
2836
+ }
2837
+ }
2838
+ constructor(onError, release){
2839
+ this.onError = onError;
2840
+ this.release = release;
2841
+ this.task = null;
2842
+ }
2843
+ }
2844
+
2845
+ class TaskFactory {
2846
+ create(task) {
2847
+ const tasks = this.freeTasks;
2848
+ const t1 = tasks.length ? tasks.pop() : new RawTask(this.onError, (t)=>tasks[tasks.length] = t
2849
+ );
2850
+ t1.task = task;
2851
+ return t1;
2852
+ }
2853
+ constructor(onError){
2854
+ this.onError = onError;
2855
+ this.freeTasks = [];
2856
+ }
2857
+ }
2858
+
2859
+ const asapQueue = new AsapQueue();
2860
+ const taskFactory = new TaskFactory(asapQueue.registerPendingError);
2861
+ /**
2862
+ * Calls a task as soon as possible after returning, in its own event, with priority
2863
+ * over other events like animation, reflow, and repaint. An error thrown from an
2864
+ * event will not interrupt, nor even substantially slow down the processing of
2865
+ * other events, but will be rather postponed to a lower priority event.
2866
+ * @param {{call}} task A callable object, typically a function that takes no
2867
+ * arguments.
2868
+ */ function asap(task) {
2869
+ asapQueue.enqueueTask(taskFactory.create(task));
2870
+ }
2871
+
2872
+ const ADD_SOURCE = 'dnd-core/ADD_SOURCE';
2873
+ const ADD_TARGET = 'dnd-core/ADD_TARGET';
2874
+ const REMOVE_SOURCE = 'dnd-core/REMOVE_SOURCE';
2875
+ const REMOVE_TARGET = 'dnd-core/REMOVE_TARGET';
2876
+ function addSource(sourceId) {
2877
+ return {
2878
+ type: ADD_SOURCE,
2879
+ payload: {
2880
+ sourceId
2881
+ }
1528
2882
  };
1529
- Engine.prototype.applyEdgeDelete = function (oldFn, fromNode, toNode, fromField, toField) {
1530
- var newFn = __assign(__assign({}, oldFn), { body: __assign({}, oldFn.body) });
1531
- var from = newFn.body[fromNode];
1532
- var to = newFn.body[toNode];
1533
- if (!from || !to) {
1534
- console.warn("Invalid nodes for edge deletion");
1535
- return newFn;
2883
+ }
2884
+ function addTarget(targetId) {
2885
+ return {
2886
+ type: ADD_TARGET,
2887
+ payload: {
2888
+ targetId
1536
2889
  }
1537
- if (to.inputs && to.inputs[toField] === "<".concat(fromNode, ".").concat(fromField, ">")) {
1538
- delete to.inputs[toField];
2890
+ };
2891
+ }
2892
+ function removeSource(sourceId) {
2893
+ return {
2894
+ type: REMOVE_SOURCE,
2895
+ payload: {
2896
+ sourceId
1539
2897
  }
1540
- else {
1541
- console.warn("No matching edge found to delete");
2898
+ };
2899
+ }
2900
+ function removeTarget(targetId) {
2901
+ return {
2902
+ type: REMOVE_TARGET,
2903
+ payload: {
2904
+ targetId
1542
2905
  }
1543
- return newFn;
1544
2906
  };
1545
- Engine.prototype.applyNodeAdd = function (oldFn, nodeName, callback) {
1546
- var newFn = __assign(__assign({}, oldFn), { body: __assign({}, oldFn.body) });
1547
- var id = uid$1();
1548
- // ensure unique id
1549
- while (newFn.body[id]) {
1550
- id = uid$1();
2907
+ }
2908
+
2909
+ function validateSourceContract(source) {
2910
+ invariant(typeof source.canDrag === 'function', 'Expected canDrag to be a function.');
2911
+ invariant(typeof source.beginDrag === 'function', 'Expected beginDrag to be a function.');
2912
+ invariant(typeof source.endDrag === 'function', 'Expected endDrag to be a function.');
2913
+ }
2914
+ function validateTargetContract(target) {
2915
+ invariant(typeof target.canDrop === 'function', 'Expected canDrop to be a function.');
2916
+ invariant(typeof target.hover === 'function', 'Expected hover to be a function.');
2917
+ invariant(typeof target.drop === 'function', 'Expected beginDrag to be a function.');
2918
+ }
2919
+ function validateType(type, allowArray) {
2920
+ if (allowArray && Array.isArray(type)) {
2921
+ type.forEach((t)=>validateType(t, false)
2922
+ );
2923
+ return;
2924
+ }
2925
+ invariant(typeof type === 'string' || typeof type === 'symbol', allowArray ? 'Type can only be a string, a symbol, or an array of either.' : 'Type can only be a string or a symbol.');
2926
+ }
2927
+
2928
+ var HandlerRole;
2929
+ (function(HandlerRole) {
2930
+ HandlerRole["SOURCE"] = "SOURCE";
2931
+ HandlerRole["TARGET"] = "TARGET";
2932
+ })(HandlerRole || (HandlerRole = {}));
2933
+
2934
+ let nextUniqueId = 0;
2935
+ function getNextUniqueId() {
2936
+ return nextUniqueId++;
2937
+ }
2938
+
2939
+ function getNextHandlerId(role) {
2940
+ const id = getNextUniqueId().toString();
2941
+ switch(role){
2942
+ case HandlerRole.SOURCE:
2943
+ return `S${id}`;
2944
+ case HandlerRole.TARGET:
2945
+ return `T${id}`;
2946
+ default:
2947
+ throw new Error(`Unknown Handler Role: ${role}`);
2948
+ }
2949
+ }
2950
+ function parseRoleFromHandlerId(handlerId) {
2951
+ switch(handlerId[0]){
2952
+ case 'S':
2953
+ return HandlerRole.SOURCE;
2954
+ case 'T':
2955
+ return HandlerRole.TARGET;
2956
+ default:
2957
+ throw new Error(`Cannot parse handler ID: ${handlerId}`);
2958
+ }
2959
+ }
2960
+ function mapContainsValue(map, searchValue) {
2961
+ const entries = map.entries();
2962
+ let isDone = false;
2963
+ do {
2964
+ const { done , value: [, value] , } = entries.next();
2965
+ if (value === searchValue) {
2966
+ return true;
1551
2967
  }
1552
- // get inputs defaults
1553
- var inputs = {};
1554
- Object.entries(this.fnIndex[nodeName].inputs || {}).forEach(function (_a) {
1555
- var _b = __read(_a, 2), key = _b[0], def = _b[1];
1556
- var normDef = normalizeVarDef(def);
1557
- if (normDef.default !== undefined) {
1558
- inputs[key] = normDef.default;
1559
- }
2968
+ isDone = !!done;
2969
+ }while (!isDone)
2970
+ return false;
2971
+ }
2972
+ class HandlerRegistryImpl {
2973
+ addSource(type, source) {
2974
+ validateType(type);
2975
+ validateSourceContract(source);
2976
+ const sourceId = this.addHandler(HandlerRole.SOURCE, type, source);
2977
+ this.store.dispatch(addSource(sourceId));
2978
+ return sourceId;
2979
+ }
2980
+ addTarget(type, target) {
2981
+ validateType(type, true);
2982
+ validateTargetContract(target);
2983
+ const targetId = this.addHandler(HandlerRole.TARGET, type, target);
2984
+ this.store.dispatch(addTarget(targetId));
2985
+ return targetId;
2986
+ }
2987
+ containsHandler(handler) {
2988
+ return mapContainsValue(this.dragSources, handler) || mapContainsValue(this.dropTargets, handler);
2989
+ }
2990
+ getSource(sourceId, includePinned = false) {
2991
+ invariant(this.isSourceId(sourceId), 'Expected a valid source ID.');
2992
+ const isPinned = includePinned && sourceId === this.pinnedSourceId;
2993
+ const source = isPinned ? this.pinnedSource : this.dragSources.get(sourceId);
2994
+ return source;
2995
+ }
2996
+ getTarget(targetId) {
2997
+ invariant(this.isTargetId(targetId), 'Expected a valid target ID.');
2998
+ return this.dropTargets.get(targetId);
2999
+ }
3000
+ getSourceType(sourceId) {
3001
+ invariant(this.isSourceId(sourceId), 'Expected a valid source ID.');
3002
+ return this.types.get(sourceId);
3003
+ }
3004
+ getTargetType(targetId) {
3005
+ invariant(this.isTargetId(targetId), 'Expected a valid target ID.');
3006
+ return this.types.get(targetId);
3007
+ }
3008
+ isSourceId(handlerId) {
3009
+ const role = parseRoleFromHandlerId(handlerId);
3010
+ return role === HandlerRole.SOURCE;
3011
+ }
3012
+ isTargetId(handlerId) {
3013
+ const role = parseRoleFromHandlerId(handlerId);
3014
+ return role === HandlerRole.TARGET;
3015
+ }
3016
+ removeSource(sourceId) {
3017
+ invariant(this.getSource(sourceId), 'Expected an existing source.');
3018
+ this.store.dispatch(removeSource(sourceId));
3019
+ asap(()=>{
3020
+ this.dragSources.delete(sourceId);
3021
+ this.types.delete(sourceId);
1560
3022
  });
1561
- // get params defaults
1562
- var params = {};
1563
- Object.entries(this.fnIndex[nodeName].params || {}).forEach(function (_a) {
1564
- var _b = __read(_a, 2), key = _b[0], def = _b[1];
1565
- var normDef = normalizeVarDef(def);
1566
- if (normDef.default !== undefined) {
1567
- params[key] = normDef.default;
3023
+ }
3024
+ removeTarget(targetId) {
3025
+ invariant(this.getTarget(targetId), 'Expected an existing target.');
3026
+ this.store.dispatch(removeTarget(targetId));
3027
+ this.dropTargets.delete(targetId);
3028
+ this.types.delete(targetId);
3029
+ }
3030
+ pinSource(sourceId) {
3031
+ const source = this.getSource(sourceId);
3032
+ invariant(source, 'Expected an existing source.');
3033
+ this.pinnedSourceId = sourceId;
3034
+ this.pinnedSource = source;
3035
+ }
3036
+ unpinSource() {
3037
+ invariant(this.pinnedSource, 'No source is pinned at the time.');
3038
+ this.pinnedSourceId = null;
3039
+ this.pinnedSource = null;
3040
+ }
3041
+ addHandler(role, type, handler) {
3042
+ const id = getNextHandlerId(role);
3043
+ this.types.set(id, type);
3044
+ if (role === HandlerRole.SOURCE) {
3045
+ this.dragSources.set(id, handler);
3046
+ } else if (role === HandlerRole.TARGET) {
3047
+ this.dropTargets.set(id, handler);
3048
+ }
3049
+ return id;
3050
+ }
3051
+ constructor(store){
3052
+ this.types = new Map();
3053
+ this.dragSources = new Map();
3054
+ this.dropTargets = new Map();
3055
+ this.pinnedSourceId = null;
3056
+ this.pinnedSource = null;
3057
+ this.store = store;
3058
+ }
3059
+ }
3060
+
3061
+ const strictEquality = (a, b)=>a === b
3062
+ ;
3063
+ /**
3064
+ * Determine if two cartesian coordinate offsets are equal
3065
+ * @param offsetA
3066
+ * @param offsetB
3067
+ */ function areCoordsEqual(offsetA, offsetB) {
3068
+ if (!offsetA && !offsetB) {
3069
+ return true;
3070
+ } else if (!offsetA || !offsetB) {
3071
+ return false;
3072
+ } else {
3073
+ return offsetA.x === offsetB.x && offsetA.y === offsetB.y;
3074
+ }
3075
+ }
3076
+ /**
3077
+ * Determines if two arrays of items are equal
3078
+ * @param a The first array of items
3079
+ * @param b The second array of items
3080
+ */ function areArraysEqual(a, b, isEqual = strictEquality) {
3081
+ if (a.length !== b.length) {
3082
+ return false;
3083
+ }
3084
+ for(let i = 0; i < a.length; ++i){
3085
+ if (!isEqual(a[i], b[i])) {
3086
+ return false;
3087
+ }
3088
+ }
3089
+ return true;
3090
+ }
3091
+
3092
+ function reduce$5(// eslint-disable-next-line @typescript-eslint/no-unused-vars
3093
+ _state = NONE, action) {
3094
+ switch(action.type){
3095
+ case HOVER:
3096
+ break;
3097
+ case ADD_SOURCE:
3098
+ case ADD_TARGET:
3099
+ case REMOVE_TARGET:
3100
+ case REMOVE_SOURCE:
3101
+ return NONE;
3102
+ case BEGIN_DRAG:
3103
+ case PUBLISH_DRAG_SOURCE:
3104
+ case END_DRAG:
3105
+ case DROP:
3106
+ default:
3107
+ return ALL;
3108
+ }
3109
+ const { targetIds =[] , prevTargetIds =[] } = action.payload;
3110
+ const result = xor(targetIds, prevTargetIds);
3111
+ const didChange = result.length > 0 || !areArraysEqual(targetIds, prevTargetIds);
3112
+ if (!didChange) {
3113
+ return NONE;
3114
+ }
3115
+ // Check the target ids at the innermost position. If they are valid, add them
3116
+ // to the result
3117
+ const prevInnermostTargetId = prevTargetIds[prevTargetIds.length - 1];
3118
+ const innermostTargetId = targetIds[targetIds.length - 1];
3119
+ if (prevInnermostTargetId !== innermostTargetId) {
3120
+ if (prevInnermostTargetId) {
3121
+ result.push(prevInnermostTargetId);
3122
+ }
3123
+ if (innermostTargetId) {
3124
+ result.push(innermostTargetId);
3125
+ }
3126
+ }
3127
+ return result;
3128
+ }
3129
+
3130
+ function _defineProperty$2(obj, key, value) {
3131
+ if (key in obj) {
3132
+ Object.defineProperty(obj, key, {
3133
+ value: value,
3134
+ enumerable: true,
3135
+ configurable: true,
3136
+ writable: true
3137
+ });
3138
+ } else {
3139
+ obj[key] = value;
3140
+ }
3141
+ return obj;
3142
+ }
3143
+ function _objectSpread$2(target) {
3144
+ for(var i = 1; i < arguments.length; i++){
3145
+ var source = arguments[i] != null ? arguments[i] : {};
3146
+ var ownKeys = Object.keys(source);
3147
+ if (typeof Object.getOwnPropertySymbols === 'function') {
3148
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
3149
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
3150
+ }));
3151
+ }
3152
+ ownKeys.forEach(function(key) {
3153
+ _defineProperty$2(target, key, source[key]);
3154
+ });
3155
+ }
3156
+ return target;
3157
+ }
3158
+ const initialState$1 = {
3159
+ initialSourceClientOffset: null,
3160
+ initialClientOffset: null,
3161
+ clientOffset: null
3162
+ };
3163
+ function reduce$4(state = initialState$1, action) {
3164
+ const { payload } = action;
3165
+ switch(action.type){
3166
+ case INIT_COORDS:
3167
+ case BEGIN_DRAG:
3168
+ return {
3169
+ initialSourceClientOffset: payload.sourceClientOffset,
3170
+ initialClientOffset: payload.clientOffset,
3171
+ clientOffset: payload.clientOffset
3172
+ };
3173
+ case HOVER:
3174
+ if (areCoordsEqual(state.clientOffset, payload.clientOffset)) {
3175
+ return state;
1568
3176
  }
3177
+ return _objectSpread$2({}, state, {
3178
+ clientOffset: payload.clientOffset
3179
+ });
3180
+ case END_DRAG:
3181
+ case DROP:
3182
+ return initialState$1;
3183
+ default:
3184
+ return state;
3185
+ }
3186
+ }
3187
+
3188
+ function _defineProperty$1(obj, key, value) {
3189
+ if (key in obj) {
3190
+ Object.defineProperty(obj, key, {
3191
+ value: value,
3192
+ enumerable: true,
3193
+ configurable: true,
3194
+ writable: true
1569
3195
  });
1570
- var newCall = {
1571
- name: nodeName,
1572
- inputs: inputs,
1573
- params: params,
1574
- };
1575
- newFn.body[id] = newCall;
1576
- callback === null || callback === void 0 ? void 0 : callback(newCall, id);
1577
- return topSort(newFn);
1578
- };
1579
- Engine.prototype.applyNodeConnect = function (oldFn, fromNode, toNode, fromField, toField) {
1580
- var newFn = __assign(__assign({}, oldFn), { body: __assign({}, oldFn.body) });
1581
- var from = newFn.body[fromNode];
1582
- var to = __assign({}, newFn.body[toNode]);
1583
- if (!from || !to) {
1584
- console.warn("Invalid nodes for connection");
1585
- return newFn;
3196
+ } else {
3197
+ obj[key] = value;
3198
+ }
3199
+ return obj;
3200
+ }
3201
+ function _objectSpread$1(target) {
3202
+ for(var i = 1; i < arguments.length; i++){
3203
+ var source = arguments[i] != null ? arguments[i] : {};
3204
+ var ownKeys = Object.keys(source);
3205
+ if (typeof Object.getOwnPropertySymbols === 'function') {
3206
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
3207
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
3208
+ }));
1586
3209
  }
1587
- if (!to.inputs) {
1588
- to.inputs = {};
3210
+ ownKeys.forEach(function(key) {
3211
+ _defineProperty$1(target, key, source[key]);
3212
+ });
3213
+ }
3214
+ return target;
3215
+ }
3216
+ const initialState = {
3217
+ itemType: null,
3218
+ item: null,
3219
+ sourceId: null,
3220
+ targetIds: [],
3221
+ dropResult: null,
3222
+ didDrop: false,
3223
+ isSourcePublic: null
3224
+ };
3225
+ function reduce$3(state = initialState, action) {
3226
+ const { payload } = action;
3227
+ switch(action.type){
3228
+ case BEGIN_DRAG:
3229
+ return _objectSpread$1({}, state, {
3230
+ itemType: payload.itemType,
3231
+ item: payload.item,
3232
+ sourceId: payload.sourceId,
3233
+ isSourcePublic: payload.isSourcePublic,
3234
+ dropResult: null,
3235
+ didDrop: false
3236
+ });
3237
+ case PUBLISH_DRAG_SOURCE:
3238
+ return _objectSpread$1({}, state, {
3239
+ isSourcePublic: true
3240
+ });
3241
+ case HOVER:
3242
+ return _objectSpread$1({}, state, {
3243
+ targetIds: payload.targetIds
3244
+ });
3245
+ case REMOVE_TARGET:
3246
+ if (state.targetIds.indexOf(payload.targetId) === -1) {
3247
+ return state;
3248
+ }
3249
+ return _objectSpread$1({}, state, {
3250
+ targetIds: without(state.targetIds, payload.targetId)
3251
+ });
3252
+ case DROP:
3253
+ return _objectSpread$1({}, state, {
3254
+ dropResult: payload.dropResult,
3255
+ didDrop: true,
3256
+ targetIds: []
3257
+ });
3258
+ case END_DRAG:
3259
+ return _objectSpread$1({}, state, {
3260
+ itemType: null,
3261
+ item: null,
3262
+ sourceId: null,
3263
+ dropResult: null,
3264
+ didDrop: false,
3265
+ isSourcePublic: null,
3266
+ targetIds: []
3267
+ });
3268
+ default:
3269
+ return state;
3270
+ }
3271
+ }
3272
+
3273
+ function reduce$2(state = 0, action) {
3274
+ switch(action.type){
3275
+ case ADD_SOURCE:
3276
+ case ADD_TARGET:
3277
+ return state + 1;
3278
+ case REMOVE_SOURCE:
3279
+ case REMOVE_TARGET:
3280
+ return state - 1;
3281
+ default:
3282
+ return state;
3283
+ }
3284
+ }
3285
+
3286
+ function reduce$1(state = 0) {
3287
+ return state + 1;
3288
+ }
3289
+
3290
+ function _defineProperty(obj, key, value) {
3291
+ if (key in obj) {
3292
+ Object.defineProperty(obj, key, {
3293
+ value: value,
3294
+ enumerable: true,
3295
+ configurable: true,
3296
+ writable: true
3297
+ });
3298
+ } else {
3299
+ obj[key] = value;
3300
+ }
3301
+ return obj;
3302
+ }
3303
+ function _objectSpread(target) {
3304
+ for(var i = 1; i < arguments.length; i++){
3305
+ var source = arguments[i] != null ? arguments[i] : {};
3306
+ var ownKeys = Object.keys(source);
3307
+ if (typeof Object.getOwnPropertySymbols === 'function') {
3308
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
3309
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
3310
+ }));
1589
3311
  }
1590
- // add the reference
1591
- to.inputs[toField] = "<".concat(fromNode, ".").concat(fromField, ">");
1592
- newFn.body[toNode] = to;
1593
- return topSort(newFn);
3312
+ ownKeys.forEach(function(key) {
3313
+ _defineProperty(target, key, source[key]);
3314
+ });
3315
+ }
3316
+ return target;
3317
+ }
3318
+ function reduce(state = {}, action) {
3319
+ return {
3320
+ dirtyHandlerIds: reduce$5(state.dirtyHandlerIds, {
3321
+ type: action.type,
3322
+ payload: _objectSpread({}, action.payload, {
3323
+ prevTargetIds: get(state, 'dragOperation.targetIds', [])
3324
+ })
3325
+ }),
3326
+ dragOffset: reduce$4(state.dragOffset, action),
3327
+ refCount: reduce$2(state.refCount, action),
3328
+ dragOperation: reduce$3(state.dragOperation, action),
3329
+ stateId: reduce$1(state.stateId)
1594
3330
  };
1595
- return Engine;
1596
- }());
3331
+ }
1597
3332
 
1598
- /**
1599
- * Create the React Context
1600
- */ const DndContext = createContext({
1601
- dragDropManager: undefined
1602
- });
3333
+ function createDragDropManager(backendFactory, globalContext = undefined, backendOptions = {}, debugMode = false) {
3334
+ const store = makeStoreInstance(debugMode);
3335
+ const monitor = new DragDropMonitorImpl(store, new HandlerRegistryImpl(store));
3336
+ const manager = new DragDropManagerImpl(store, monitor);
3337
+ const backend = backendFactory(manager, globalContext, backendOptions);
3338
+ manager.receiveBackend(backend);
3339
+ return manager;
3340
+ }
3341
+ function makeStoreInstance(debugMode) {
3342
+ // TODO: if we ever make a react-native version of this,
3343
+ // we'll need to consider how to pull off dev-tooling
3344
+ const reduxDevTools = typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__;
3345
+ return createStore(reduce, debugMode && reduxDevTools && reduxDevTools({
3346
+ name: 'dnd-core',
3347
+ instanceId: 'dnd-core'
3348
+ }));
3349
+ }
1603
3350
 
1604
- /**
1605
- * Use invariant() to assert state which your program assumes to be true.
1606
- *
1607
- * Provide sprintf-style format (only %s is supported) and arguments
1608
- * to provide information about what broke and what you were
1609
- * expecting.
1610
- *
1611
- * The invariant message will be stripped in production, but the invariant
1612
- * will remain to ensure logic does not differ in production.
1613
- */ function invariant(condition, format, ...args) {
1614
- if (isProduction()) {
1615
- if (format === undefined) {
1616
- throw new Error('invariant requires an error message argument');
3351
+ function _objectWithoutProperties(source, excluded) {
3352
+ if (source == null) return {};
3353
+ var target = _objectWithoutPropertiesLoose(source, excluded);
3354
+ var key, i;
3355
+ if (Object.getOwnPropertySymbols) {
3356
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
3357
+ for(i = 0; i < sourceSymbolKeys.length; i++){
3358
+ key = sourceSymbolKeys[i];
3359
+ if (excluded.indexOf(key) >= 0) continue;
3360
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
3361
+ target[key] = source[key];
1617
3362
  }
1618
3363
  }
1619
- if (!condition) {
1620
- let error;
1621
- if (format === undefined) {
1622
- error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
1623
- } else {
1624
- let argIndex = 0;
1625
- error = new Error(format.replace(/%s/g, function() {
1626
- return args[argIndex++];
1627
- }));
1628
- error.name = 'Invariant Violation';
3364
+ return target;
3365
+ }
3366
+ function _objectWithoutPropertiesLoose(source, excluded) {
3367
+ if (source == null) return {};
3368
+ var target = {};
3369
+ var sourceKeys = Object.keys(source);
3370
+ var key, i;
3371
+ for(i = 0; i < sourceKeys.length; i++){
3372
+ key = sourceKeys[i];
3373
+ if (excluded.indexOf(key) >= 0) continue;
3374
+ target[key] = source[key];
3375
+ }
3376
+ return target;
3377
+ }
3378
+ let refCount = 0;
3379
+ const INSTANCE_SYM = Symbol.for('__REACT_DND_CONTEXT_INSTANCE__');
3380
+ var DndProvider = /*#__PURE__*/ memo(function DndProvider(_param) {
3381
+ var { children } = _param, props = _objectWithoutProperties(_param, [
3382
+ "children"
3383
+ ]);
3384
+ const [manager, isGlobalInstance] = getDndContextValue(props) // memoized from props
3385
+ ;
3386
+ /**
3387
+ * If the global context was used to store the DND context
3388
+ * then where theres no more references to it we should
3389
+ * clean it up to avoid memory leaks
3390
+ */ useEffect(()=>{
3391
+ if (isGlobalInstance) {
3392
+ const context = getGlobalContext();
3393
+ ++refCount;
3394
+ return ()=>{
3395
+ if (--refCount === 0) {
3396
+ context[INSTANCE_SYM] = null;
3397
+ }
3398
+ };
1629
3399
  }
1630
- error.framesToPop = 1 // we don't care about invariant's own frame
1631
- ;
1632
- throw error;
3400
+ return;
3401
+ }, []);
3402
+ return /*#__PURE__*/ jsx(DndContext.Provider, {
3403
+ value: manager,
3404
+ children: children
3405
+ });
3406
+ });
3407
+ function getDndContextValue(props) {
3408
+ if ('manager' in props) {
3409
+ const manager = {
3410
+ dragDropManager: props.manager
3411
+ };
3412
+ return [
3413
+ manager,
3414
+ false
3415
+ ];
3416
+ }
3417
+ const manager = createSingletonDndContext(props.backend, props.context, props.options, props.debugMode);
3418
+ const isGlobalInstance = !props.context;
3419
+ return [
3420
+ manager,
3421
+ isGlobalInstance
3422
+ ];
3423
+ }
3424
+ function createSingletonDndContext(backend, context = getGlobalContext(), options, debugMode) {
3425
+ const ctx = context;
3426
+ if (!ctx[INSTANCE_SYM]) {
3427
+ ctx[INSTANCE_SYM] = {
3428
+ dragDropManager: createDragDropManager(backend, context, options, debugMode)
3429
+ };
1633
3430
  }
3431
+ return ctx[INSTANCE_SYM];
1634
3432
  }
1635
- function isProduction() {
1636
- return typeof process !== 'undefined' && process.env['NODE_ENV'] === 'production';
3433
+ function getGlobalContext() {
3434
+ return typeof global !== 'undefined' ? global : window;
1637
3435
  }
1638
3436
 
1639
3437
  function getDefaultExportFromCjs (x) {
@@ -3293,5 +5091,10 @@ function useFunction(engine, fn, mount) {
3293
5091
  }); }, [builtFn, run, result]);
3294
5092
  }
3295
5093
 
3296
- export { DISCARD, Engine, Flow, Lib, binaryOnTree, binaryOnTreeBranch, broadCast, expandTree, getBranch, getReferences, getValue$1 as getValue, graftTree, interpolate, isReference, isSingleTon, isTree, mapTree, mapTreeBranch, nAryOnTree, nAryOnTreeBranch, normalizeVarDef, parseReference, primitives, sameShape, simplifyTree, toArray, topSort, treeSize, trimTree, uid$1 as uid, useDraggableNode, useFlow, useFunction, usePositions, useUpdatePositions, useVariable };
5094
+ function DDContext(_a) {
5095
+ var children = _a.children;
5096
+ return React.createElement(DndProvider, { backend: HTML5Backend }, children);
5097
+ }
5098
+
5099
+ export { DDContext, DISCARD, Engine, Flow, Lib, binaryOnTree, binaryOnTreeBranch, broadCast, expandTree, getBranch, getReferences, getValue$1 as getValue, graftTree, interpolate, isReference, isSingleTon, isTree, mapTree, mapTreeBranch, nAryOnTree, nAryOnTreeBranch, normalizeVarDef, parseReference, primitives, sameShape, simplifyTree, toArray, topSort, treeSize, trimTree, uid$1 as uid, useDraggableNode, useFlow, useFunction, usePositions, useUpdatePositions, useVariable };
3297
5100
  //# sourceMappingURL=index.esm.js.map