UNPKG

@hello-pangea/dnd

Version:

Beautiful and accessible drag and drop for lists with React

1,390 lines (1,346 loc) 274 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-dom')) : typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-dom'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactBeautifulDnd = {}, global.React, global.ReactDOM)); })(this, (function (exports, React, ReactDOM) { 'use strict'; function _interopNamespaceDefault(e) { var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React); const spacesAndTabs = /[ \t]{2,}/g; const lineStartWithSpaces = /^[ \t]*/gm; const clean$2 = value => value.replace(spacesAndTabs, ' ').replace(lineStartWithSpaces, '').trim(); const getDevMessage = message => clean$2(` %c@hello-pangea/dnd %c${clean$2(message)} %c👷‍ This is a development only message. It will be removed in production builds. `); const getFormattedMessage = message => [getDevMessage(message), 'color: #00C584; font-size: 1.2em; font-weight: bold;', 'line-height: 1.5', 'color: #723874;']; const isDisabledFlag = '__@hello-pangea/dnd-disable-dev-warnings'; function log(type, message) { if (typeof window !== 'undefined' && window[isDisabledFlag]) { return; } console[type](...getFormattedMessage(message)); } const warning$1 = log.bind(null, 'warn'); const error = log.bind(null, 'error'); function noop$2() {} function getOptions(shared, fromBinding) { return { ...shared, ...fromBinding }; } function bindEvents(el, bindings, sharedOptions) { const unbindings = bindings.map(binding => { const options = getOptions(sharedOptions, binding.options); el.addEventListener(binding.eventName, binding.fn, options); return function unbind() { el.removeEventListener(binding.eventName, binding.fn, options); }; }); return function unbindAll() { unbindings.forEach(unbind => { unbind(); }); }; } const prefix$2 = 'Invariant failed'; class RbdInvariant extends Error {} RbdInvariant.prototype.toString = function toString() { return this.message; }; function invariant$1(condition, message) { { throw new RbdInvariant(`${prefix$2}: ${message || ''}`); } } class ErrorBoundary extends React.Component { constructor(...args) { super(...args); this.callbacks = null; this.unbind = noop$2; this.onWindowError = event => { const callbacks = this.getCallbacks(); if (callbacks.isDragging()) { callbacks.tryAbort(); warning$1(` An error was caught by our window 'error' event listener while a drag was occurring. The active drag has been aborted. `) ; } const err = event.error; if (err instanceof RbdInvariant) { event.preventDefault(); { error(err.message); } } }; this.getCallbacks = () => { if (!this.callbacks) { throw new Error('Unable to find AppCallbacks in <ErrorBoundary/>'); } return this.callbacks; }; this.setCallbacks = callbacks => { this.callbacks = callbacks; }; } componentDidMount() { this.unbind = bindEvents(window, [{ eventName: 'error', fn: this.onWindowError }]); } componentDidCatch(err) { if (err instanceof RbdInvariant) { { error(err.message); } this.setState({}); return; } throw err; } componentWillUnmount() { this.unbind(); } render() { return this.props.children(this.setCallbacks); } } const dragHandleUsageInstructions = ` Press space bar to start a drag. When dragging you can use the arrow keys to move the item around and escape to cancel. Some screen readers may require you to be in focus mode or to use your pass through key `; const position = index => index + 1; const onDragStart = start => ` You have lifted an item in position ${position(start.source.index)} `; const withLocation = (source, destination) => { const isInHomeList = source.droppableId === destination.droppableId; const startPosition = position(source.index); const endPosition = position(destination.index); if (isInHomeList) { return ` You have moved the item from position ${startPosition} to position ${endPosition} `; } return ` You have moved the item from position ${startPosition} in list ${source.droppableId} to list ${destination.droppableId} in position ${endPosition} `; }; const withCombine = (id, source, combine) => { const inHomeList = source.droppableId === combine.droppableId; if (inHomeList) { return ` The item ${id} has been combined with ${combine.draggableId}`; } return ` The item ${id} in list ${source.droppableId} has been combined with ${combine.draggableId} in list ${combine.droppableId} `; }; const onDragUpdate = update => { const location = update.destination; if (location) { return withLocation(update.source, location); } const combine = update.combine; if (combine) { return withCombine(update.draggableId, update.source, combine); } return 'You are over an area that cannot be dropped on'; }; const returnedToStart = source => ` The item has returned to its starting position of ${position(source.index)} `; const onDragEnd = result => { if (result.reason === 'CANCEL') { return ` Movement cancelled. ${returnedToStart(result.source)} `; } const location = result.destination; const combine = result.combine; if (location) { return ` You have dropped the item. ${withLocation(result.source, location)} `; } if (combine) { return ` You have dropped the item. ${withCombine(result.draggableId, result.source, combine)} `; } return ` The item has been dropped while not over a drop area. ${returnedToStart(result.source)} `; }; const preset = { dragHandleUsageInstructions, onDragStart, onDragUpdate, onDragEnd }; // src/utils/formatProdErrorMessage.ts // src/utils/symbol-observable.ts var $$observable = /* @__PURE__ */ (() => typeof Symbol === "function" && Symbol.observable || "@@observable")(); var symbol_observable_default = $$observable; // src/utils/actionTypes.ts var randomString = () => Math.random().toString(36).substring(7).split("").join("."); var ActionTypes = { INIT: `@@redux/INIT${/* @__PURE__ */ randomString()}`, REPLACE: `@@redux/REPLACE${/* @__PURE__ */ randomString()}`}; var actionTypes_default = ActionTypes; // src/utils/isPlainObject.ts function isPlainObject$1(obj) { if (typeof obj !== "object" || obj === null) return false; let proto = obj; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(obj) === proto || Object.getPrototypeOf(obj) === null; } // src/utils/kindOf.ts function miniKindOf(val) { if (val === void 0) return "undefined"; if (val === null) return "null"; const type = typeof val; switch (type) { case "boolean": case "string": case "number": case "symbol": case "function": { return type; } } if (Array.isArray(val)) return "array"; if (isDate(val)) return "date"; if (isError(val)) return "error"; const constructorName = ctorName(val); switch (constructorName) { case "Symbol": case "Promise": case "WeakMap": case "WeakSet": case "Map": case "Set": return constructorName; } return Object.prototype.toString.call(val).slice(8, -1).toLowerCase().replace(/\s/g, ""); } function ctorName(val) { return typeof val.constructor === "function" ? val.constructor.name : null; } function isError(val) { return val instanceof Error || typeof val.message === "string" && val.constructor && typeof val.constructor.stackTraceLimit === "number"; } function isDate(val) { if (val instanceof Date) return true; return typeof val.toDateString === "function" && typeof val.getDate === "function" && typeof val.setDate === "function"; } function kindOf(val) { let typeOfVal = typeof val; { typeOfVal = miniKindOf(val); } return typeOfVal; } // src/createStore.ts function createStore$1(reducer, preloadedState, enhancer) { if (typeof reducer !== "function") { throw new Error(`Expected the root reducer to be a function. Instead, received: '${kindOf(reducer)}'`); } if (typeof preloadedState === "function" && typeof enhancer === "function" || typeof enhancer === "function" && typeof arguments[3] === "function") { throw new Error("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."); } if (typeof preloadedState === "function" && typeof enhancer === "undefined") { enhancer = preloadedState; preloadedState = void 0; } if (typeof enhancer !== "undefined") { if (typeof enhancer !== "function") { throw new Error(`Expected the enhancer to be a function. Instead, received: '${kindOf(enhancer)}'`); } return enhancer(createStore$1)(reducer, preloadedState); } let currentReducer = reducer; let currentState = preloadedState; let currentListeners = /* @__PURE__ */ new Map(); let nextListeners = currentListeners; let listenerIdCounter = 0; let isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = /* @__PURE__ */ new Map(); currentListeners.forEach((listener, key) => { nextListeners.set(key, listener); }); } } function getState() { if (isDispatching) { throw new Error("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."); } return currentState; } function subscribe(listener) { if (typeof listener !== "function") { throw new Error(`Expected the listener to be a function. Instead, received: '${kindOf(listener)}'`); } if (isDispatching) { throw new Error("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."); } let isSubscribed = true; ensureCanMutateNextListeners(); const listenerId = listenerIdCounter++; nextListeners.set(listenerId, listener); return function unsubscribe() { if (!isSubscribed) { return; } if (isDispatching) { throw new Error("You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details."); } isSubscribed = false; ensureCanMutateNextListeners(); nextListeners.delete(listenerId); currentListeners = null; }; } function dispatch(action) { if (!isPlainObject$1(action)) { throw new Error(`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.`); } if (typeof action.type === "undefined") { throw new Error('Actions may not have an undefined "type" property. You may have misspelled an action type string constant.'); } if (typeof action.type !== "string") { throw new Error(`Action "type" property must be a string. Instead, the actual type was: '${kindOf(action.type)}'. Value was: '${action.type}' (stringified)`); } if (isDispatching) { throw new Error("Reducers may not dispatch actions."); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } const listeners = currentListeners = nextListeners; listeners.forEach((listener) => { listener(); }); return action; } function replaceReducer(nextReducer) { if (typeof nextReducer !== "function") { throw new Error(`Expected the nextReducer to be a function. Instead, received: '${kindOf(nextReducer)}`); } currentReducer = nextReducer; dispatch({ type: actionTypes_default.REPLACE }); } function observable() { const outerSubscribe = subscribe; return { /** * The minimal observable subscription method. * @param observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe(observer) { if (typeof observer !== "object" || observer === null) { throw new Error(`Expected the observer to be an object. Instead, received: '${kindOf(observer)}'`); } function observeState() { const observerAsObserver = observer; if (observerAsObserver.next) { observerAsObserver.next(getState()); } } observeState(); const unsubscribe = outerSubscribe(observeState); return { unsubscribe }; }, [symbol_observable_default]() { return this; } }; } dispatch({ type: actionTypes_default.INIT }); const store = { dispatch, subscribe, getState, replaceReducer, [symbol_observable_default]: observable }; return store; } // src/bindActionCreators.ts function bindActionCreator(actionCreator, dispatch) { return function(...args) { return dispatch(actionCreator.apply(this, args)); }; } function bindActionCreators$1(actionCreators, dispatch) { if (typeof actionCreators === "function") { return bindActionCreator(actionCreators, dispatch); } if (typeof actionCreators !== "object" || actionCreators === null) { throw new Error(`bindActionCreators expected an object or a function, but instead received: '${kindOf(actionCreators)}'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`); } const boundActionCreators = {}; for (const key in actionCreators) { const actionCreator = actionCreators[key]; if (typeof actionCreator === "function") { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } // src/compose.ts function compose(...funcs) { if (funcs.length === 0) { return (arg) => arg; } if (funcs.length === 1) { return funcs[0]; } return funcs.reduce((a, b) => (...args) => a(b(...args))); } // src/applyMiddleware.ts function applyMiddleware(...middlewares) { return (createStore2) => (reducer, preloadedState) => { const store = createStore2(reducer, preloadedState); let dispatch = () => { throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch."); }; const middlewareAPI = { getState: store.getState, dispatch: (action, ...args) => dispatch(action, ...args) }; const chain = middlewares.map((middleware) => middleware(middlewareAPI)); dispatch = compose(...chain)(store.dispatch); return { ...store, dispatch }; }; } var useSyncExternalStoreWithSelector_development = {}; /** * @license React * use-sync-external-store-with-selector.development.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var hasRequiredUseSyncExternalStoreWithSelector_development; function requireUseSyncExternalStoreWithSelector_development () { if (hasRequiredUseSyncExternalStoreWithSelector_development) return useSyncExternalStoreWithSelector_development; hasRequiredUseSyncExternalStoreWithSelector_development = 1; ((function () { function is(x, y) { return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y); } "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); var React$1 = React, objectIs = "function" === typeof Object.is ? Object.is : is, useSyncExternalStore = React$1.useSyncExternalStore, useRef = React$1.useRef, useEffect = React$1.useEffect, useMemo = React$1.useMemo, useDebugValue = React$1.useDebugValue; useSyncExternalStoreWithSelector_development.useSyncExternalStoreWithSelector = function ( subscribe, getSnapshot, getServerSnapshot, selector, isEqual ) { var instRef = useRef(null); if (null === instRef.current) { var inst = { hasValue: false, value: null }; instRef.current = inst; } else inst = instRef.current; instRef = useMemo( function () { function memoizedSelector(nextSnapshot) { if (!hasMemo) { hasMemo = true; memoizedSnapshot = nextSnapshot; nextSnapshot = selector(nextSnapshot); if (void 0 !== isEqual && inst.hasValue) { var currentSelection = inst.value; if (isEqual(currentSelection, nextSnapshot)) return (memoizedSelection = currentSelection); } return (memoizedSelection = nextSnapshot); } currentSelection = memoizedSelection; if (objectIs(memoizedSnapshot, nextSnapshot)) return currentSelection; var nextSelection = selector(nextSnapshot); if (void 0 !== isEqual && isEqual(currentSelection, nextSelection)) return (memoizedSnapshot = nextSnapshot), currentSelection; memoizedSnapshot = nextSnapshot; return (memoizedSelection = nextSelection); } var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot; return [ function () { return memoizedSelector(getSnapshot()); }, null === maybeGetServerSnapshot ? void 0 : function () { return memoizedSelector(maybeGetServerSnapshot()); } ]; }, [getSnapshot, getServerSnapshot, selector, isEqual] ); var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]); useEffect( function () { inst.hasValue = true; inst.value = value; }, [value] ); useDebugValue(value); return value; }; "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); }))(); return useSyncExternalStoreWithSelector_development; } { requireUseSyncExternalStoreWithSelector_development(); } // src/utils/react.ts // src/utils/react-is.ts var IS_REACT_19 = /* @__PURE__ */ React__namespace.version.startsWith("19"); var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for( IS_REACT_19 ? "react.transitional.element" : "react.element" ); var REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"); var REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"); var REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"); var REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"); var REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"); var REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"); var REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"); var REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"); var REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for( "react.suspense_list" ); var REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"); var REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"); var REACT_OFFSCREEN_TYPE = /* @__PURE__ */ Symbol.for("react.offscreen"); var REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for( "react.client.reference" ); var ForwardRef = REACT_FORWARD_REF_TYPE; var Memo = REACT_MEMO_TYPE; function isValidElementType(type) { return typeof type === "string" || typeof type === "function" || type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_OFFSCREEN_TYPE || typeof type === "object" && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_CONSUMER_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_CLIENT_REFERENCE || type.getModuleId !== void 0) ? true : false; } function typeOf(object) { if (typeof object === "object" && object !== null) { const { $$typeof } = object; switch ($$typeof) { case REACT_ELEMENT_TYPE: switch (object = object.type, object) { case REACT_FRAGMENT_TYPE: case REACT_PROFILER_TYPE: case REACT_STRICT_MODE_TYPE: case REACT_SUSPENSE_TYPE: case REACT_SUSPENSE_LIST_TYPE: return object; default: switch (object = object && object.$$typeof, object) { case REACT_CONTEXT_TYPE: case REACT_FORWARD_REF_TYPE: case REACT_LAZY_TYPE: case REACT_MEMO_TYPE: return object; case REACT_CONSUMER_TYPE: return object; default: return $$typeof; } } case REACT_PORTAL_TYPE: return $$typeof; } } } function isContextConsumer(object) { return IS_REACT_19 ? typeOf(object) === REACT_CONSUMER_TYPE : typeOf(object) === REACT_CONTEXT_TYPE; } function isMemo(object) { return typeOf(object) === REACT_MEMO_TYPE; } // src/utils/warning.ts function warning(message) { if (typeof console !== "undefined" && typeof console.error === "function") { console.error(message); } try { throw new Error(message); } catch (e) { } } // src/connect/verifySubselectors.ts function verify(selector, methodName) { if (!selector) { throw new Error(`Unexpected value for ${methodName} in connect.`); } else if (methodName === "mapStateToProps" || methodName === "mapDispatchToProps") { if (!Object.prototype.hasOwnProperty.call(selector, "dependsOnOwnProps")) { warning( `The selector for ${methodName} of connect did not specify a value for dependsOnOwnProps.` ); } } } function verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps) { verify(mapStateToProps, "mapStateToProps"); verify(mapDispatchToProps, "mapDispatchToProps"); verify(mergeProps, "mergeProps"); } // src/connect/selectorFactory.ts function pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, { areStatesEqual, areOwnPropsEqual, areStatePropsEqual }) { let hasRunAtLeastOnce = false; let state; let ownProps; let stateProps; let dispatchProps; let mergedProps; function handleFirstCall(firstState, firstOwnProps) { state = firstState; ownProps = firstOwnProps; stateProps = mapStateToProps(state, ownProps); dispatchProps = mapDispatchToProps(dispatch, ownProps); mergedProps = mergeProps(stateProps, dispatchProps, ownProps); hasRunAtLeastOnce = true; return mergedProps; } function handleNewPropsAndNewState() { stateProps = mapStateToProps(state, ownProps); if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps); mergedProps = mergeProps(stateProps, dispatchProps, ownProps); return mergedProps; } function handleNewProps() { if (mapStateToProps.dependsOnOwnProps) stateProps = mapStateToProps(state, ownProps); if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps); mergedProps = mergeProps(stateProps, dispatchProps, ownProps); return mergedProps; } function handleNewState() { const nextStateProps = mapStateToProps(state, ownProps); const statePropsChanged = !areStatePropsEqual(nextStateProps, stateProps); stateProps = nextStateProps; if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps); return mergedProps; } function handleSubsequentCalls(nextState, nextOwnProps) { const propsChanged = !areOwnPropsEqual(nextOwnProps, ownProps); const stateChanged = !areStatesEqual( nextState, state, nextOwnProps, ownProps ); state = nextState; ownProps = nextOwnProps; if (propsChanged && stateChanged) return handleNewPropsAndNewState(); if (propsChanged) return handleNewProps(); if (stateChanged) return handleNewState(); return mergedProps; } return function pureFinalPropsSelector(nextState, nextOwnProps) { return hasRunAtLeastOnce ? handleSubsequentCalls(nextState, nextOwnProps) : handleFirstCall(nextState, nextOwnProps); }; } function finalPropsSelectorFactory(dispatch, { initMapStateToProps, initMapDispatchToProps, initMergeProps, ...options }) { const mapStateToProps = initMapStateToProps(dispatch, options); const mapDispatchToProps = initMapDispatchToProps(dispatch, options); const mergeProps = initMergeProps(dispatch, options); { verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps); } return pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, options); } // src/utils/bindActionCreators.ts function bindActionCreators(actionCreators, dispatch) { const boundActionCreators = {}; for (const key in actionCreators) { const actionCreator = actionCreators[key]; if (typeof actionCreator === "function") { boundActionCreators[key] = (...args) => dispatch(actionCreator(...args)); } } return boundActionCreators; } // src/utils/isPlainObject.ts function isPlainObject(obj) { if (typeof obj !== "object" || obj === null) return false; const proto = Object.getPrototypeOf(obj); if (proto === null) return true; let baseProto = proto; while (Object.getPrototypeOf(baseProto) !== null) { baseProto = Object.getPrototypeOf(baseProto); } return proto === baseProto; } // src/utils/verifyPlainObject.ts function verifyPlainObject(value, displayName, methodName) { if (!isPlainObject(value)) { warning( `${methodName}() in ${displayName} must return a plain object. Instead received ${value}.` ); } } // src/connect/wrapMapToProps.ts function wrapMapToPropsConstant(getConstant) { return function initConstantSelector(dispatch) { const constant = getConstant(dispatch); function constantSelector() { return constant; } constantSelector.dependsOnOwnProps = false; return constantSelector; }; } function getDependsOnOwnProps(mapToProps) { return mapToProps.dependsOnOwnProps ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1; } function wrapMapToPropsFunc(mapToProps, methodName) { return function initProxySelector(dispatch, { displayName }) { const proxy = function mapToPropsProxy(stateOrDispatch, ownProps) { return proxy.dependsOnOwnProps ? proxy.mapToProps(stateOrDispatch, ownProps) : proxy.mapToProps(stateOrDispatch, void 0); }; proxy.dependsOnOwnProps = true; proxy.mapToProps = function detectFactoryAndVerify(stateOrDispatch, ownProps) { proxy.mapToProps = mapToProps; proxy.dependsOnOwnProps = getDependsOnOwnProps(mapToProps); let props = proxy(stateOrDispatch, ownProps); if (typeof props === "function") { proxy.mapToProps = props; proxy.dependsOnOwnProps = getDependsOnOwnProps(props); props = proxy(stateOrDispatch, ownProps); } verifyPlainObject(props, displayName, methodName); return props; }; return proxy; }; } // src/connect/invalidArgFactory.ts function createInvalidArgFactory(arg, name) { return (dispatch, options) => { throw new Error( `Invalid value of type ${typeof arg} for ${name} argument when connecting component ${options.wrappedComponentName}.` ); }; } // src/connect/mapDispatchToProps.ts function mapDispatchToPropsFactory(mapDispatchToProps) { return mapDispatchToProps && typeof mapDispatchToProps === "object" ? wrapMapToPropsConstant( (dispatch) => ( // @ts-ignore bindActionCreators(mapDispatchToProps, dispatch) ) ) : !mapDispatchToProps ? wrapMapToPropsConstant((dispatch) => ({ dispatch })) : typeof mapDispatchToProps === "function" ? ( // @ts-ignore wrapMapToPropsFunc(mapDispatchToProps, "mapDispatchToProps") ) : createInvalidArgFactory(mapDispatchToProps, "mapDispatchToProps"); } // src/connect/mapStateToProps.ts function mapStateToPropsFactory(mapStateToProps) { return !mapStateToProps ? wrapMapToPropsConstant(() => ({})) : typeof mapStateToProps === "function" ? ( // @ts-ignore wrapMapToPropsFunc(mapStateToProps, "mapStateToProps") ) : createInvalidArgFactory(mapStateToProps, "mapStateToProps"); } // src/connect/mergeProps.ts function defaultMergeProps(stateProps, dispatchProps, ownProps) { return { ...ownProps, ...stateProps, ...dispatchProps }; } function wrapMergePropsFunc(mergeProps) { return function initMergePropsProxy(dispatch, { displayName, areMergedPropsEqual }) { let hasRunOnce = false; let mergedProps; return function mergePropsProxy(stateProps, dispatchProps, ownProps) { const nextMergedProps = mergeProps(stateProps, dispatchProps, ownProps); if (hasRunOnce) { if (!areMergedPropsEqual(nextMergedProps, mergedProps)) mergedProps = nextMergedProps; } else { hasRunOnce = true; mergedProps = nextMergedProps; verifyPlainObject(mergedProps, displayName, "mergeProps"); } return mergedProps; }; }; } function mergePropsFactory(mergeProps) { return !mergeProps ? () => defaultMergeProps : typeof mergeProps === "function" ? wrapMergePropsFunc(mergeProps) : createInvalidArgFactory(mergeProps, "mergeProps"); } // src/utils/batch.ts function defaultNoopBatch(callback) { callback(); } // src/utils/Subscription.ts function createListenerCollection() { let first = null; let last = null; return { clear() { first = null; last = null; }, notify() { defaultNoopBatch(() => { let listener = first; while (listener) { listener.callback(); listener = listener.next; } }); }, get() { const listeners = []; let listener = first; while (listener) { listeners.push(listener); listener = listener.next; } return listeners; }, subscribe(callback) { let isSubscribed = true; const listener = last = { callback, next: null, prev: last }; if (listener.prev) { listener.prev.next = listener; } else { first = listener; } return function unsubscribe() { if (!isSubscribed || first === null) return; isSubscribed = false; if (listener.next) { listener.next.prev = listener.prev; } else { last = listener.prev; } if (listener.prev) { listener.prev.next = listener.next; } else { first = listener.next; } }; } }; } var nullListeners = { notify() { }, get: () => [] }; function createSubscription(store, parentSub) { let unsubscribe; let listeners = nullListeners; let subscriptionsAmount = 0; let selfSubscribed = false; function addNestedSub(listener) { trySubscribe(); const cleanupListener = listeners.subscribe(listener); let removed = false; return () => { if (!removed) { removed = true; cleanupListener(); tryUnsubscribe(); } }; } function notifyNestedSubs() { listeners.notify(); } function handleChangeWrapper() { if (subscription.onStateChange) { subscription.onStateChange(); } } function isSubscribed() { return selfSubscribed; } function trySubscribe() { subscriptionsAmount++; if (!unsubscribe) { unsubscribe = parentSub ? parentSub.addNestedSub(handleChangeWrapper) : store.subscribe(handleChangeWrapper); listeners = createListenerCollection(); } } function tryUnsubscribe() { subscriptionsAmount--; if (unsubscribe && subscriptionsAmount === 0) { unsubscribe(); unsubscribe = void 0; listeners.clear(); listeners = nullListeners; } } function trySubscribeSelf() { if (!selfSubscribed) { selfSubscribed = true; trySubscribe(); } } function tryUnsubscribeSelf() { if (selfSubscribed) { selfSubscribed = false; tryUnsubscribe(); } } const subscription = { addNestedSub, notifyNestedSubs, handleChangeWrapper, isSubscribed, trySubscribe: trySubscribeSelf, tryUnsubscribe: tryUnsubscribeSelf, getListeners: () => listeners }; return subscription; } // src/utils/useIsomorphicLayoutEffect.ts var canUseDOM = () => !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"); var isDOM = /* @__PURE__ */ canUseDOM(); var isRunningInReactNative = () => typeof navigator !== "undefined" && navigator.product === "ReactNative"; var isReactNative = /* @__PURE__ */ isRunningInReactNative(); var getUseIsomorphicLayoutEffect = () => isDOM || isReactNative ? React__namespace.useLayoutEffect : React__namespace.useEffect; var useIsomorphicLayoutEffect$1 = /* @__PURE__ */ getUseIsomorphicLayoutEffect(); // src/utils/shallowEqual.ts function is(x, y) { if (x === y) { return x !== 0 || y !== 0 || 1 / x === 1 / y; } else { return x !== x && y !== y; } } function shallowEqual(objA, objB) { if (is(objA, objB)) return true; if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) { return false; } const keysA = Object.keys(objA); const keysB = Object.keys(objB); if (keysA.length !== keysB.length) return false; for (let i = 0; i < keysA.length; i++) { if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } // src/utils/hoistStatics.ts var REACT_STATICS = { childContextTypes: true, contextType: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, getDerivedStateFromError: true, getDerivedStateFromProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var FORWARD_REF_STATICS = { $$typeof: true, render: true, defaultProps: true, displayName: true, propTypes: true }; var MEMO_STATICS = { $$typeof: true, compare: true, defaultProps: true, displayName: true, propTypes: true, type: true }; var TYPE_STATICS = { [ForwardRef]: FORWARD_REF_STATICS, [Memo]: MEMO_STATICS }; function getStatics(component) { if (isMemo(component)) { return MEMO_STATICS; } return TYPE_STATICS[component["$$typeof"]] || REACT_STATICS; } var defineProperty = Object.defineProperty; var getOwnPropertyNames = Object.getOwnPropertyNames; var getOwnPropertySymbols = Object.getOwnPropertySymbols; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var getPrototypeOf = Object.getPrototypeOf; var objectPrototype = Object.prototype; function hoistNonReactStatics(targetComponent, sourceComponent) { if (typeof sourceComponent !== "string") { if (objectPrototype) { const inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent); } } let keys = getOwnPropertyNames(sourceComponent); if (getOwnPropertySymbols) { keys = keys.concat(getOwnPropertySymbols(sourceComponent)); } const targetStatics = getStatics(targetComponent); const sourceStatics = getStatics(sourceComponent); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (!KNOWN_STATICS[key] && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) { const descriptor = getOwnPropertyDescriptor(sourceComponent, key); try { defineProperty(targetComponent, key, descriptor); } catch (e) { } } } } return targetComponent; } // src/components/Context.ts var ContextKey = /* @__PURE__ */ Symbol.for(`react-redux-context`); var gT = typeof globalThis !== "undefined" ? globalThis : ( /* fall back to a per-module scope (pre-8.1 behaviour) if `globalThis` is not available */ {} ); function getContext() { if (!React__namespace.createContext) return {}; const contextMap = gT[ContextKey] ??= /* @__PURE__ */ new Map(); let realContext = contextMap.get(React__namespace.createContext); if (!realContext) { realContext = React__namespace.createContext( null ); { realContext.displayName = "ReactRedux"; } contextMap.set(React__namespace.createContext, realContext); } return realContext; } var ReactReduxContext = /* @__PURE__ */ getContext(); // src/components/connect.tsx var NO_SUBSCRIPTION_ARRAY = [null, null]; var stringifyComponent = (Comp) => { try { return JSON.stringify(Comp); } catch (err) { return String(Comp); } }; function useIsomorphicLayoutEffectWithArgs(effectFunc, effectArgs, dependencies) { useIsomorphicLayoutEffect$1(() => effectFunc(...effectArgs), dependencies); } function captureWrapperProps(lastWrapperProps, lastChildProps, renderIsScheduled, wrapperProps, childPropsFromStoreUpdate, notifyNestedSubs) { lastWrapperProps.current = wrapperProps; renderIsScheduled.current = false; if (childPropsFromStoreUpdate.current) { childPropsFromStoreUpdate.current = null; notifyNestedSubs(); } } function subscribeUpdates(shouldHandleStateChanges, store, subscription, childPropsSelector, lastWrapperProps, lastChildProps, renderIsScheduled, isMounted, childPropsFromStoreUpdate, notifyNestedSubs, additionalSubscribeListener) { if (!shouldHandleStateChanges) return () => { }; let didUnsubscribe = false; let lastThrownError = null; const checkForUpdates = () => { if (didUnsubscribe || !isMounted.current) { return; } const latestStoreState = store.getState(); let newChildProps, error; try { newChildProps = childPropsSelector( latestStoreState, lastWrapperProps.current ); } catch (e) { error = e; lastThrownError = e; } if (!error) { lastThrownError = null; } if (newChildProps === lastChildProps.current) { if (!renderIsScheduled.current) { notifyNestedSubs(); } } else { lastChildProps.current = newChildProps; childPropsFromStoreUpdate.current = newChildProps; renderIsScheduled.current = true; additionalSubscribeListener(); } }; subscription.onStateChange = checkForUpdates; subscription.trySubscribe(); checkForUpdates(); const unsubscribeWrapper = () => { didUnsubscribe = true; subscription.tryUnsubscribe(); subscription.onStateChange = null; if (lastThrownError) { throw lastThrownError; } }; return unsubscribeWrapper; } function strictEqual(a, b) { return a === b; } var hasWarnedAboutDeprecatedPureOption = false; function connect(mapStateToProps, mapDispatchToProps, mergeProps, { // The `pure` option has been removed, so TS doesn't like us destructuring this to check its existence. // @ts-ignore pure, areStatesEqual = strictEqual, areOwnPropsEqual = shallowEqual, areStatePropsEqual = shallowEqual, areMergedPropsEqual = shallowEqual, // use React's forwardRef to expose a ref of the wrapped component forwardRef = false, // the context consumer to use context = ReactReduxContext } = {}) { { if (pure !== void 0 && !hasWarnedAboutDeprecatedPureOption) { hasWarnedAboutDeprecatedPureOption = true; warning( 'The `pure` option has been removed. `connect` is now always a "pure/memoized" component' ); } } const Context = context; const initMapStateToProps = mapStateToPropsFactory(mapStateToProps); const initMapDispatchToProps = mapDispatchToPropsFactory(mapDispatchToProps); const initMergeProps = mergePropsFactory(mergeProps); const shouldHandleStateChanges = Boolean(mapStateToProps); const wrapWithConnect = (WrappedComponent) => { { const isValid = /* @__PURE__ */ isValidElementType(WrappedComponent); if (!isValid) throw new Error( `You must pass a component to the function returned by connect. Instead received ${stringifyComponent( WrappedComponent )}` ); } const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || "Component"; const displayName = `Connect(${wrappedComponentName})`; const selectorFactoryOptions = { shouldHandleStateChanges, displayName, wrappedComponentName, WrappedComponent, // @ts-ignore initMapStateToProps, initMapDispatchToProps, initMergeProps, areStatesEqual, areStatePropsEqual, areOwnPropsEqual, areMergedPropsEqual }; function ConnectFunction(props) { const [propsContext, reactReduxForwardedRef, wrapperProps] = React__namespace.useMemo(() => { const { reactReduxForwardedRef: reactReduxForwardedRef2, ...wrapperProps2 } = props; return [props.context, reactReduxForwardedRef2, wrapperProps2]; }, [props]); const ContextToUse = React__namespace.useMemo(() => { let ResultContext = Context; if (propsContext?.Consumer) { { const isValid = /* @__PURE__ */ isContextConsumer( // @ts-ignore /* @__PURE__ */ React__namespace.createElement(propsContext.Consumer, null) ); if (!isValid) { throw new Error( "You must pass a valid React context consumer as `props.context`" ); } ResultContext = propsContext; } } return ResultContext; }, [propsContext, Context]); const contextValue = React__namespace.useContext(ContextToUse); const didStoreComeFromProps = Boolean(props.store) && Boolean(props.store.getState) && Boolean(props.store.dispatch); const didStoreComeFromContext = Boolean(contextValue) && Boolean(contextValue.store); if (!didStoreComeFromProps && !didStoreComeFromContext) { throw new Error( `Could not find "store" in the context of "${displayName}". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to ${displayName} in connect options.` ); } const store = didStoreComeFromProps ? props.store : contextValue.store; const getServerState = didStoreComeFromContext ? contextValue.getServerState : store.getState; const childPropsSelector = React__namespace.useMemo(() => { return finalPropsSelectorFactory(store.dispatch, selectorFactoryOptions); }, [store]); const [subscription, notifyNestedSubs] = React__namespace.useMemo(() => { if (!shouldHandleStateChanges) return NO_SUBSCRIPTION_ARRAY; const subscription2 = createSubscription( store, didStoreComeFromProps ? void 0 : contextValue.subscription ); const notifyNestedSubs2 = subscription2.notifyNestedSubs.bind(subscription2); return [subscription2, notifyNestedSubs2]; }, [store, didStoreComeFromProps, contextValue]); const overriddenContextValue = React__namespace.useMemo(() => { if (didStoreComeFromProps) { return contextValue; } return { ...contextValue, subscription }; }, [didStoreComeFromProps, contextValue, subscription]); const lastChildProps = React__namespace.useRef(void 0); const lastWrapperProps = React__namespace.useRef(wrapperProps); const childPropsFromStoreUpdate = React__namespace.useRef(void 0); const renderIsScheduled = React__namespace.useRef(false); const isMounted = React__namespace.useRef(false); const latestSubscriptionCallbackError = React__namespace.useRef( void 0 ); useIsomorphicLayoutEffect$1(() => { isMounted.current = true; return () => { isMounted.current = false; }; }, []); const actualChildPropsSelector = React__namespace.useMemo(() => { const selector = () => { if (childPropsFromStoreUpdate.current && wrapperProps === lastWrapperProps.current) { return childPropsFromStoreUpdate.current; } return childPropsSelector(store.getState(), wrapperProps); }; return selector; }, [store, wrapperProps]); const subscribeForReact = React__namespace.useMemo(() => { const subscribe = (reactListener) => { if (!subscription) { return () => { }; } return subscribeUpdates( shouldHandleStateChanges, store, subscription, // @ts-ignore childPropsSelector, lastWrapperProps, lastChildProps, renderIs