import { Editor , EditorPlugin } from "roosterjs-editor-core" ; import { BeforePasteEvent , ExtractContentEvent , PasteOption , PluginEvent , PluginEventType } from "roosterjs-editor-types" ; import { hasPlaceholder , ImageManagerInteface , PlaceholderDataAttribute } from "../utils/ImageManager" ; const PlaceholderRegex = new RegExp ( `<img [^>]*${ PlaceholderDataAttribute }="\\d+"[^>]*>` , "gm" ) ; export default class PasteImagePlugin implements EditorPlugin { private editor : Editor ; constructor ( private imageManager , private preventImagePaste = false ) { } public getName ( ) { return 'PasteImage' ; } public initialize ( editor ) { this . editor = editor ; } public dispose ( ) { if ( this . editor ) { this . editor = null ; } } public onPluginEvent ( event ) { if ( event . eventType === PluginEventType . ExtractContent ) { const extractContentEvent = event as ExtractContentEvent ; const content = extractContentEvent . content ; const runRemove = hasPlaceholder ( content ) ; if ( runRemove ) { extractContentEvent . content = content . replace ( PlaceholderRegex , "" ) ; } return ; } if ( event . eventType !== PluginEventType . BeforePaste ) { return ; } const beforePasteEvent = event as BeforePasteEvent ; if ( beforePasteEvent . pasteOption !== PasteOption . PasteImage ) { return ; } const editor = this . getEditor ( ) ; if ( ! editor ) { return ; } if ( this . preventImagePaste ) { beforePasteEvent . pasteOption = PasteOption . PasteText ; return ; } const image = beforePasteEvent . clipboardData . image ; const placeholder = this . imageManager . upload ( editor , image , true ) ; if ( placeholder === null ) { return ; } beforePasteEvent . fragment . appendChild ( placeholder ) ; beforePasteEvent . clipboardData . html = placeholder . outerHTML ; beforePasteEvent . pasteOption = PasteOption . PasteHtml ; } public setPreventImagePaste ( enabled = true ) { this . preventImagePaste = enabled ; } public getEditor ( ) { return this . editor ; } }