UNPKG

@atlaskit/editor-common

Version:

A package that contains common classes and components for editor and renderer

139 lines (134 loc) 6.8 kB
import _defineProperty from "@babel/runtime/helpers/defineProperty"; import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; 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) { _defineProperty(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; } import { useEffect, useLayoutEffect, useMemo, useRef } from 'react'; import debounce from 'lodash/debounce'; // 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 = _slicedToArray(_ref, 2), key = _ref2[0], value = _ref2[1]; return _objectSpread(_objectSpread({}, acc), {}, _defineProperty({}, 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 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. */ export function usePluginStateEffect(injectionApi, plugins, effect) { var pluginNames = useStaticPlugins(plugins); // Create a memoized object containing the named plugins var namedExternalPlugins = useMemo(function () { return pluginNames.reduce(function (acc, pluginName) { return _objectSpread(_objectSpread({}, acc), {}, _defineProperty({}, "".concat(String(pluginName), "State"), injectionApi === null || injectionApi === void 0 ? void 0 : injectionApi[pluginName])); }, {}); }, [injectionApi, pluginNames]); usePluginStateEffectInternal(namedExternalPlugins, effect); } function usePluginStateEffectInternal(externalPlugins, effect) { var refStates = useRef(); var cleanup = useRef(); var latestEffect = 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. useEffect(function () { latestEffect.current = debounce(effect); return function () { latestEffect.current = undefined; }; }, [effect]); useLayoutEffect(function () { var _latestEffect$current; // 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 = _slicedToArray(_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]); }