@atlaskit/editor-plugin-context-panel
Version:
Context panel plugin for @atlaskit/editor-core
73 lines (72 loc) • 2.88 kB
JavaScript
import { SafePlugin } from '@atlaskit/editor-common/safe-plugin';
import { PluginKey } from '@atlaskit/editor-prosemirror/state';
import { fg } from '@atlaskit/platform-feature-flags';
import { applyChange } from './pm-plugins/transforms';
export const pluginKey = new PluginKey('contextPanelPluginKey');
function contextPanelPluginFactory(contextPanels, dispatch) {
return new SafePlugin({
key: pluginKey,
state: {
init(_config, state) {
return {
handlers: contextPanels,
contents: contextPanels.map(panelContent => panelContent(state))
};
},
apply(tr, pluginState, _oldState, newState) {
let newPluginState = pluginState;
const meta = tr.getMeta(pluginKey);
if (tr.docChanged || tr.selectionSet || meta && meta.changed) {
const newContents = pluginState.handlers.map(panelContent => panelContent(newState));
const contentsLengthChanged = newContents.length !== newPluginState.contents.length;
const contentChanged = newContents.some((node, index) => newPluginState.contents[index] !== node);
if (contentsLengthChanged || contentChanged) {
newPluginState = {
...newPluginState,
contents: newContents
};
}
}
if (newPluginState !== pluginState) {
dispatch(pluginKey, newPluginState);
}
return newPluginState;
}
}
});
}
/**
* Context panel plugin to be added to an `EditorPresetBuilder` and used with `ComposableEditor`
* from `@atlaskit/editor-core`.
*/
export const contextPanelPlugin = ({
config
}) => ({
name: 'contextPanel',
actions: {
applyChange: applyChange,
showPanel: config !== null && config !== void 0 && config.objectSideBar.showPanel && fg('platform_editor_ai_object_sidebar_injection') ? (panel, behavior, panelWidth) => config.objectSideBar.showPanel(panel, behavior, panelWidth) : undefined,
closePanel: config !== null && config !== void 0 && config.objectSideBar.closePanel && fg('platform_editor_ai_object_sidebar_injection') ? () => config.objectSideBar.closePanel() : undefined,
closePanelById: config !== null && config !== void 0 && config.objectSideBar.closePanelById && fg('platform_editor_ai_object_sidebar_injection') ? id => config.objectSideBar.closePanelById(id) : undefined
},
getSharedState(state) {
var _pluginKey$getState;
if (!state) {
return undefined;
}
const {
contents
} = (_pluginKey$getState = pluginKey.getState(state)) !== null && _pluginKey$getState !== void 0 ? _pluginKey$getState : {};
return {
contents
};
},
pmPlugins(contextPanels = []) {
return [{
name: 'contextPanel',
plugin: ({
dispatch
}) => contextPanelPluginFactory(contextPanels.filter(Boolean), dispatch)
}];
}
});