@atlaskit/editor-plugin-connectivity
Version:
Connectivity plugin for @atlaskit/editor-core
75 lines • 2.15 kB
JavaScript
import { useEffect } from 'react';
import { bind } from 'bind-event-listener';
import { createPlugin, key } from './pm-plugins/main';
export const connectivityPlugin = () => {
let previousMode;
return {
name: 'connectivity',
getSharedState(editorState) {
var _ref, _pluginState$external;
if (!editorState) {
return {
mode: 'online'
};
}
const 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: mode => ({
tr
}) => {
// Leave early if the mode has not changed
if (mode === previousMode) {
return null;
}
previousMode = mode;
return tr.setMeta(key, {
externalState: mode
});
}
},
pmPlugins: () => {
return [{
name: 'connectivity',
plugin: createPlugin
}];
},
usePluginHook: ({
editorView
}) => {
useEffect(() => {
const dispatch = value => {
const {
dispatch,
state: {
tr
}
} = editorView;
dispatch(tr.setMeta(key, {
browserState: value
}));
};
const handleOnline = () => dispatch('online');
const handleOffline = () => dispatch('offline');
if (window.navigator.onLine === false) {
dispatch('offline');
}
const cleanupOnlineListener = bind(window, {
type: 'online',
listener: handleOnline
});
const cleanupOfflineListener = bind(window, {
type: 'offline',
listener: handleOffline
});
return () => {
cleanupOnlineListener();
cleanupOfflineListener();
};
}, [editorView]);
}
};
};