-
chris authored120405d6
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
CommentPlugin.js 1.98 KiB
/* eslint-disable consistent-return */
import { inRange, last, sortBy } from 'lodash';
import { Plugin, PluginKey } from 'prosemirror-state';
import { Decoration, DecorationSet } from 'prosemirror-view';
import { CommentDecorationPluginKey } from './CommentDecorationPlugin';
const commentPlugin = new PluginKey('commentPlugin');
const getComment = state => {
const commentsMap = CommentDecorationPluginKey.getState(state).getMap();
if (commentsMap.size === 0) return;
let commentData = [];
commentsMap.forEach(comment => {
if (inRange(state.selection.from, comment.data.pmFrom, comment.data.pmTo)) {
commentData.push(comment);
}
});
commentData = sortBy(commentData, ['data.pmFrom']);
if (commentData.length > 0) {
if (
(state.selection.from !== state.selection.to &&
last(commentData).data.conversation.length === 0) ||
(state.selection.from === state.selection.to &&
last(commentData).data.conversation.length !== 0)
) {
return last(commentData);
}
return undefined;
}
return undefined;
};
export default (key, context) => {
return new Plugin({
key: commentPlugin,
state: {
init: (_, state) => {
return { comment: getComment(state) };
},
apply(tr, prev, _, newState) {
const comment = getComment(newState);
let createDecoration;
if (comment) {
context.setOption({ activeComment: comment });
createDecoration = DecorationSet.create(newState.doc, [
Decoration.inline(comment.data.pmFrom, comment.data.pmTo, {
class: 'active-comment',
}),
]);
} else {
context.setOption({ activeComment: undefined });
}
return {
comment,
createDecoration,
};
},
},
props: {
decorations: state => {
const commentPluginState = state && commentPlugin.getState(state);
return commentPluginState.createDecoration;
},
},
});
};