UNPKG

@atlaskit/editor-plugin-highlight

Version:

Highlight plugin for @atlaskit/editor-core

59 lines (58 loc) 2.12 kB
import { SafePlugin } from '@atlaskit/editor-common/safe-plugin'; import { PluginKey } from '@atlaskit/editor-prosemirror/state'; import { DecorationSet } from '@atlaskit/editor-prosemirror/view'; import { addPaddingDecorations } from './add-padding-decorations'; import { updatePaddingDecorations } from './update-padding-decorations'; export var highlightPaddingPluginKey = new PluginKey('highlightPaddingPluginKey'); /** * Plugin to add padding decorations around highlighted text. * * Padding is added to the left and/or right of highlighted text * only when it is at the start or end of a block, or when it is adjacent * to whitespace. */ export var createHighlightPaddingPlugin = function createHighlightPaddingPlugin() { return new SafePlugin({ key: highlightPaddingPluginKey, state: { init: function init(_, state) { // Initially scan the entire doc to create all highlight padding decorations // after which updates will only apply to changed ranges var initialDecorationSet = DecorationSet.empty; var decorationSet = addPaddingDecorations({ decorationSet: initialDecorationSet, state: state, from: 0, to: state.doc.content.size }); return { decorationSet: decorationSet }; }, apply: function apply(tr, pluginState, _oldState, state) { if (!tr.docChanged) { return pluginState; } var decorationSet = pluginState.decorationSet.map(tr.mapping, tr.doc); tr.mapping.maps.forEach(function (stepMap) { stepMap.forEach(function (_oldStart, _oldEnd, start, end) { decorationSet = updatePaddingDecorations({ decorationSet: decorationSet, state: state, start: start, end: end }); }); }); return { decorationSet: decorationSet }; } }, props: { decorations: function decorations(state) { return highlightPaddingPluginKey.getState(state).decorationSet; } } }); };