Skip to content

Commit

Permalink
feat(copy-paste): wip HTML injection implementation of idempotent paste
Browse files Browse the repository at this point in the history
  • Loading branch information
thibaudcolas committed May 20, 2018
1 parent 4366190 commit 1058d5a
Showing 1 changed file with 46 additions and 6 deletions.
52 changes: 46 additions & 6 deletions src/lib/copypaste.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,37 @@
// @flow
import type { ElementRef } from "react";
import { Editor, EditorState, Modifier } from "draft-js";
import {
Editor,
EditorState,
Modifier,
convertToRaw,
convertFromRaw,
ContentState,
} from "draft-js";
import getFragmentFromSelection from "draft-js/lib/getFragmentFromSelection";

const sourceEditors = {};

export const registerCopySource = (ref: ElementRef<Editor>) => {
sourceEditors[ref.getEditorKey()] = ref;

const editorContainer = ref.editorContainer.parentNode;
editorContainer.addEventListener("copy", (e) => {
const fragment = getFragmentFromSelection(ref._latestEditorState);

if (fragment) {
const content = ContentState.createFromBlockArray(fragment.toArray());
e.target.setAttribute(
"data-draftjs-conductor-fragment",
JSON.stringify(convertToRaw(content)),
);
}
});

document.addEventListener("paste", (e) => {
console.log(e.clipboardData.getData("text/plain"));
console.log(e.clipboardData.getData("text/html"));
});
};

export const unregisterCopySource = (ref: ElementRef<Editor>) => {
Expand All @@ -18,15 +44,29 @@ export const handleDraftEditorPastedText = (
html: ?string,
editorState: EditorState,
) => {
const isEditor = html && html.includes("data-editor");
const isEditor =
html &&
html.includes("data-editor") &&
html.includes("data-draftjs-conductor-fragment");
const sourceKey = html && isEditor ? /data-editor="(\w+)"/.exec(html)[1] : "";
const editorKey = ref.getEditorKey();

if (!sourceKey || sourceKey === editorKey || !sourceEditors[sourceKey]) {
return false;
}
console.log("handlePastedText");

// if (!sourceKey || sourceKey === editorKey || !sourceEditors[sourceKey]) {
// return false;
// }

const clipboard = sourceEditors[sourceKey].getClipboard();
const fragment =
html && isEditor
? /data-draftjs-conductor-fragment="([^"]+)"/.exec(html)[1]
: "";
console.log(fragment);
const parser = new DOMParser();
const docFragment = parser.parseFromString(fragment, "text/html");
const json = docFragment.body.innerHTML;
console.log(JSON.parse(json));
const clipboard = convertFromRaw(JSON.parse(json)).getBlockMap();

// TODO Potentially layer this separately.
if (clipboard) {
Expand Down

0 comments on commit 1058d5a

Please sign in to comment.