@atlaskit/editor-plugin-highlight
Version:
Highlight plugin for @atlaskit/editor-core
59 lines (58 loc) • 1.97 kB
JavaScript
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 const 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 const createHighlightPaddingPlugin = () => {
return new SafePlugin({
key: highlightPaddingPluginKey,
state: {
init: (_, state) => {
// Initially scan the entire doc to create all highlight padding decorations
// after which updates will only apply to changed ranges
const initialDecorationSet = DecorationSet.empty;
const decorationSet = addPaddingDecorations({
decorationSet: initialDecorationSet,
state,
from: 0,
to: state.doc.content.size
});
return {
decorationSet
};
},
apply: (tr, pluginState, _oldState, state) => {
if (!tr.docChanged) {
return pluginState;
}
let decorationSet = pluginState.decorationSet.map(tr.mapping, tr.doc);
tr.mapping.maps.forEach(stepMap => {
stepMap.forEach((_oldStart, _oldEnd, start, end) => {
decorationSet = updatePaddingDecorations({
decorationSet,
state,
start,
end
});
});
});
return {
decorationSet
};
}
},
props: {
decorations: state => {
return highlightPaddingPluginKey.getState(state).decorationSet;
}
}
});
};