Skip to content
Snippets Groups Projects
CommentPlugin.js 1.5 KiB
Newer Older
chris's avatar
chris committed
/* eslint-disable consistent-return */
import { inRange, last } from 'lodash';
chris's avatar
chris committed
import { Plugin, PluginKey } from 'prosemirror-state';
import { Decoration, DecorationSet } from 'prosemirror-view';
chris's avatar
chris committed
const commentPlugin = new PluginKey('commentPlugin');
chris's avatar
chris committed
const getComment = (state, context) => {
  const {
    options: { comments },
  } = context;
  if (!comments?.length) return;

  const commentData = comments.filter(comment =>
chris's avatar
chris committed
    inRange(state.selection.from, comment.from, comment.to),
  );

  if (commentData.length > 0) {
    if (
      state.selection.from !== state.selection.to &&
      state.selection.to < last(commentData).to
    ) {
      return {};
    }
    return last(commentData);
chris's avatar
chris committed
  }
  return {};
export default (key, context) => {
chris's avatar
chris committed
  return new Plugin({
    key: commentPlugin,
    state: {
      init: (_, state) => {
chris's avatar
chris committed
        return { comment: getComment(state, context) };
      },
      apply(tr, prev, _, newState) {
chris's avatar
chris committed
        const comment = getComment(newState, context);
        let createDecoration;
        if (comment) {
          createDecoration = DecorationSet.create(newState.doc, [
            Decoration.inline(comment.from, comment.to, {
chris's avatar
chris committed
              class: 'active-comment',
            }),
chris's avatar
chris committed
          createDecoration,
chris's avatar
chris committed
      },
chris's avatar
chris committed
    props: {
      decorations: state => {
        const commentPluginState = state && commentPlugin.getState(state);
        return commentPluginState.createDecoration;
chris's avatar
chris committed
      },
    },
chris's avatar
chris committed
  });
};