[Solved] How to access EditorState/EditorView in Plugin?

I have a Plugin with transformCopied Editor prop. I want to access PluginState from there, but to do that I need to call getState which expects EditorState. The problem is that transformCopied only returns a Slice. How do I go about it? Is there any particular reason why transformCopied (and a few others) don’t return EditorView?

what’s your use-case?

@moonrise-tk Let me reply, since @Inmate is my work buddy :slight_smile:

The whole usecase is shared here - Modify specific node on copy and paste (in clipboard) - #4 by Inmate

export const copyPastePlugin = ({ editorContext }: Args) =>
  new Plugin({
    key: new PluginKey("copyPastePlugin"),
    props: {
      transformCopied: (slice: Slice) => {
        /* Add temporary dataForCopyPaste to live in the clipboard. */
        const addCopyPasteDataToDataFields = (node: Node) => {
          if (node.type === schema.nodes.custom_field) {
            // do something with external context

            return node.type.create(
              {
                ...node.attrs,
                ...(someData && {
                  copyPasteData: { ...someData },
                }),
              },
              node.content
            );
          }

          return node.copy(node.content);
        };

        return mapSlice(slice, addCopyPasteDataToDataFields);
      },

The problem is that we want to be able to update editorContext without needing to reconfigure all plugins. So we want to actually use pluginState to keep editorContext and then apply updates using dispatch. That part works just fine, but we are not able to retrieve pluginState from within the transformCopied function, therefore we cannot access our editorContext.

Ideally, we would be able to do something like that:

    props: {
      transformCopied(slice: Slice, editorState: EditorState) {
        const { editorContext } = copyPastePlugin.getState(editorState);

Unfortunately, only Slice is being passed to transformCopied, transformPasted and clipboardTextSerializer.

Please let me know if you need some more information.

This patch adds the view as a parameter to this and similar props.

4 Likes

Thanks @marijn! :clap: This is exactly how we imagined this to be. We were almost to open the same PR but just wanted to make sure the reasoning behind not passing the view in these few particular cases. Glad it could be aligned!