From 419e496b966daad316858ee7d3e490b88bf5519d Mon Sep 17 00:00:00 2001 From: Thibaud Colas Date: Thu, 19 Apr 2018 01:03:50 +0300 Subject: [PATCH] WIP: on paste, read content from internal clipboard via paste registry --- lib/components/DraftailEditor.js | 39 +++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/lib/components/DraftailEditor.js b/lib/components/DraftailEditor.js index 8b2b0fc0..c37f76f7 100644 --- a/lib/components/DraftailEditor.js +++ b/lib/components/DraftailEditor.js @@ -1,6 +1,6 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; -import { Editor, EditorState, RichUtils } from 'draft-js'; +import { Editor, EditorState, RichUtils, Modifier } from 'draft-js'; import { ListNestingStyles } from 'draftjs-conductor'; import { @@ -48,6 +48,7 @@ class DraftailEditor extends Component { this.onTab = this.onTab.bind(this); this.handleKeyCommand = this.handleKeyCommand.bind(this); this.handleBeforeInput = this.handleBeforeInput.bind(this); + this.handlePastedText = this.handlePastedText.bind(this); this.toggleBlockType = this.toggleBlockType.bind(this); this.toggleInlineStyle = this.toggleInlineStyle.bind(this); @@ -312,6 +313,32 @@ class DraftailEditor extends Component { return NOT_HANDLED; } + handlePastedText(text, html, editorState) { + const editorKey = this.editorRef.getEditorKey(); + const isEditor = html.includes('data-editor'); + const htmlKey = isEditor ? /data-editor="(\w+)"/.exec(html)[1] : ''; + + if (!htmlKey || htmlKey === editorKey || !window.editorRefs[htmlKey]) { + return false; + } + + const clipboard = window.editorRefs[htmlKey].getClipboard(); + + if (clipboard) { + const newContent = Modifier.replaceWithFragment( + editorState.getCurrentContent(), + editorState.getSelection(), + clipboard, + ); + this.onChange( + EditorState.push(editorState, newContent, 'insert-fragment'), + ); + return true; + } + + return false; + } + toggleBlockType(blockType) { const { editorState } = this.state; this.onChange(RichUtils.toggleBlockType(editorState, blockType)); @@ -588,6 +615,15 @@ class DraftailEditor extends Component { customStyleMap={behavior.getCustomStyleMap(inlineStyles)} ref={ref => { this.editorRef = ref; + if (ref) { + window.editorRefs = Object.assign( + {}, + window.editorRefs, + { + [ref.getEditorKey()]: ref, + }, + ); + } }} editorState={editorState} onChange={this.onChange} @@ -609,6 +645,7 @@ class DraftailEditor extends Component { )} handleKeyCommand={this.handleKeyCommand} handleBeforeInput={this.handleBeforeInput} + handlePastedText={this.handlePastedText} onFocus={this.onFocus} onBlur={this.onBlur} onTab={this.onTab}