Replace Image With Text On Text Copy

Hi there, I implemented my own textBetween method and provide it as a clipboardTextSerialize myself: It checks the presence of a value attribute when a node is a leaf node and use this value as a text.

import {
  Node as ProseMirrorNode,
  DOMOutputSpec,
  NodeSpec,
  DOMSerializer,
  Slice,
  Fragment,
} from 'prosemirror-model';

  function customTextBetween(
    fragment: Fragment,
    from: number,
    to: number,
    blockSeparator: string,
    leafText?: string
  ) {
    let text = '',
      separated = true;
    fragment.nodesBetween(
      from,
      to,
      (node, pos) => {
        if (node.isText) {
          text += node.text?.slice(Math.max(from, pos) - pos, to - pos);
          separated = !blockSeparator;
        } else if (node.isLeaf && node.attrs.value != undefined) {
          console.log('LEAF NODE WITH VALUE:', node);
          text += ' '+node.attrs.value+' ';
          separated = !blockSeparator;
        } else if (node.isLeaf && leafText) {
          console.log('ORIGINAL LEAF NODE BEHAVIOUR:', node);
          text += leafText;
          separated = !blockSeparator;
        } else if (!separated && node.isBlock) {
          text += blockSeparator;
          separated = true;
        }
      },
      0
    );
    return text;
  }

...
// in the Editor props:

          clipboardTextSerializer: (slice: Slice) => {
            return customTextBetween(
              slice.content,
              0,
              slice.content.size,
              '\n\n',
              '<classic leaf replacement text>'
            );
          },

Hope it helps someone! :wink:

2 Likes