UNPKG

@atlaskit/editor-plugin-connectivity

Version:

Connectivity plugin for @atlaskit/editor-core

75 lines 2.41 kB
import { useEffect } from 'react'; import { bind } from 'bind-event-listener'; import { createPlugin, key } from './pm-plugins/main'; export var connectivityPlugin = function connectivityPlugin() { var previousMode; return { name: 'connectivity', getSharedState: function getSharedState(editorState) { var _ref, _pluginState$external; if (!editorState) { return { mode: 'online' }; } var pluginState = key.getState(editorState); return { mode: (_ref = (_pluginState$external = pluginState === null || pluginState === void 0 ? void 0 : pluginState.externalState) !== null && _pluginState$external !== void 0 ? _pluginState$external : pluginState === null || pluginState === void 0 ? void 0 : pluginState.browserState) !== null && _ref !== void 0 ? _ref : 'online' }; }, commands: { setMode: function setMode(mode) { return function (_ref2) { var tr = _ref2.tr; // Leave early if the mode has not changed if (mode === previousMode) { return null; } previousMode = mode; return tr.setMeta(key, { externalState: mode }); }; } }, pmPlugins: function pmPlugins() { return [{ name: 'connectivity', plugin: createPlugin }]; }, usePluginHook: function usePluginHook(_ref3) { var editorView = _ref3.editorView; useEffect(function () { var dispatch = function dispatch(value) { var dispatch = editorView.dispatch, tr = editorView.state.tr; dispatch(tr.setMeta(key, { browserState: value })); }; var handleOnline = function handleOnline() { return dispatch('online'); }; var handleOffline = function handleOffline() { return dispatch('offline'); }; if (window.navigator.onLine === false) { dispatch('offline'); } var cleanupOnlineListener = bind(window, { type: 'online', listener: handleOnline }); var cleanupOfflineListener = bind(window, { type: 'offline', listener: handleOffline }); return function () { cleanupOnlineListener(); cleanupOfflineListener(); }; }, [editorView]); } }; };