"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.usePluginStateEffect = usePluginStateEffect;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = require("react");
var _debounce = _interopRequireDefault(require("lodash/debounce"));
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
// Ignored via go/ees005
// eslint-disable-next-line @typescript-eslint/no-explicit-any

/**
 *
 * Directly map object values
 *
 * @param object The object to transform
 * @param mapFunction The function to map an old value to new one
 * @returns Object with the same key but transformed values
 *
 */
function mapValues(object, mapFunction) {
  return Object.entries(object).reduce(function (acc, _ref) {
    var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
      key = _ref2[0],
      value = _ref2[1];
    return _objectSpread(_objectSpread({}, acc), {}, (0, _defineProperty2.default)({}, key, mapFunction(value)));
  }, {});
}

// When we use the `useSharedPluginState` example: `useSharedPluginState(api, ['width'])`
// it will re-render every time the component re-renders as the array "['width']" is seen as an update.
// This hook is used to prevent re-renders due to this.
function useStaticPlugins(plugins) {
  // eslint-disable-next-line react-hooks/exhaustive-deps
  return (0, _react.useMemo)(function () {
    return plugins;
  }, []);
}
/**
 *
 * ⚠️⚠️⚠️ This is a debounced hook ⚠️⚠️⚠️
 * If the plugins you are listening to generate multiple shared states while the user is typing,
 * your React Component will get only the last one.
 *
 * Used to run effects on changes in editor state - similar to `useSharedPluginState` except this
 * is for reacting to state changes so does not cause re-renders. The effect callback passed will be called
 * on initialisation and when the state changes (with the latest callback we are provided).
 *
 * Example in plugin:
 *
 * ```typescript
 * function ExampleContent({ api }: Props) {
 *   const pluginStateCallback = useCallback(( { dogState, exampleState } ) => {
 *       // Use as necessary ie. fire analytics or network requests
 *       console.log(dogState, exampleState)
 *   }, [])
 *   usePluginStateEffect(
 *     api,
 *     ['dog', 'example'],
 *     pluginStateCallback
 *   )
 *   return <p>Content</p>
 * }
 *
 * const examplePlugin: NextEditorPlugin<'example', { dependencies: [typeof pluginDog] }> = ({ api }) => {
 *   return {
 *     name: 'example',
 *     contentComponent: () =>
 *       <ExampleContent
 *         api={api}
 *         />
 *   }
 * }
 * ```
 *
 * @param injectionApi Plugin injection API from `NextEditorPlugin`
 * @param plugins Plugin names to get the shared plugin state for
 * @param effect A callback, the parameter is a corresponding object, the keys are names of the plugin with `State` appended,
 * the values are the shared state exposed by that plugin. This effect fires when the state changes and runs the most recent callback passed.
 * If the callback changes the effect is not re-run - it is still recommended however to wrap your effect in `useCallback`,
 * You can return a function from your effect to call any cleanup activities which will be called on unmount and when `editorApi` changes.
 */
function usePluginStateEffect(injectionApi, plugins, effect) {
  var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  var pluginNames = useStaticPlugins(plugins);

  // Create a memoized object containing the named plugins
  var namedExternalPlugins = (0, _react.useMemo)(function () {
    return pluginNames.reduce(function (acc, pluginName) {
      return _objectSpread(_objectSpread({}, acc), {}, (0, _defineProperty2.default)({}, "".concat(String(pluginName), "State"), injectionApi === null || injectionApi === void 0 ? void 0 : injectionApi[pluginName]));
    }, {});
  }, [injectionApi, pluginNames]);
  usePluginStateEffectInternal(namedExternalPlugins, effect, options);
}
function usePluginStateEffectInternal(externalPlugins, effect) {
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var refStates = (0, _react.useRef)();
  var cleanup = (0, _react.useRef)();
  var latestEffect = (0, _react.useRef)(effect);

  // We should store the latest effect in a reference so it is more intuitive to the user
  // and we are not causing a memory leak by having references to old state.
  (0, _react.useLayoutEffect)(function () {
    if (options.disabled) {
      return;
    }
    latestEffect.current = (0, _debounce.default)(effect);
    return function () {
      latestEffect.current = undefined;
    };
  }, [effect, options.disabled]);
  (0, _react.useLayoutEffect)(function () {
    var _latestEffect$current;
    if (options.disabled) {
      return;
    }

    // Update the reference for this plugin and activate the effect
    refStates.current = mapValues(externalPlugins, function (value) {
      return value === null || value === void 0 ? void 0 : value.sharedState.currentState();
    });
    cleanup.current = (_latestEffect$current = latestEffect.current) === null || _latestEffect$current === void 0 ? void 0 : _latestEffect$current.call(latestEffect, refStates.current);
    var unsubs = Object.entries(externalPlugins).map(function (_ref3) {
      var _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
        pluginKey = _ref4[0],
        externalPlugin = _ref4[1];
      return externalPlugin === null || externalPlugin === void 0 ? void 0 : externalPlugin.sharedState.onChange(function (_ref5) {
        var nextSharedState = _ref5.nextSharedState,
          prevSharedState = _ref5.prevSharedState;
        if (prevSharedState !== nextSharedState && refStates.current) {
          var _latestEffect$current2;
          // Update the reference for this plugin and activate the effect
          refStates.current[pluginKey] = nextSharedState;
          cleanup.current = (_latestEffect$current2 = latestEffect.current) === null || _latestEffect$current2 === void 0 ? void 0 : _latestEffect$current2.call(latestEffect, refStates.current);
        }
      });
    });
    return function () {
      var _cleanup$current;
      refStates.current = undefined;
      unsubs.forEach(function (cb) {
        return cb === null || cb === void 0 ? void 0 : cb();
      });
      (_cleanup$current = cleanup.current) === null || _cleanup$current === void 0 || _cleanup$current.call(cleanup);
    };
    // Do not re-run if the `effect` changes - this is not expected with `useEffect` or similar hooks
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [externalPlugins, options.disabled]);
}