From ee2276244a514a00d8b817d1fb1c16e3dfdd3dd3 Mon Sep 17 00:00:00 2001 From: Cory Forsyth Date: Fri, 23 Oct 2015 10:55:42 -0400 Subject: [PATCH] Delete selection before applying paste fixes #184 --- src/js/editor/editor.js | 21 ++++++++++++++++----- tests/acceptance/editor-copy-paste-test.js | 21 +++++++++++++++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/js/editor/editor.js b/src/js/editor/editor.js index 345753336..08d2d5a7a 100644 --- a/src/js/editor/editor.js +++ b/src/js/editor/editor.js @@ -211,13 +211,17 @@ class Editor { } } - handleDeletion(event) { + /** + * @param {KeyEvent} event optional + * @private + */ + handleDeletion(event=null) { const range = this.cursor.offsets; if (this.cursor.hasSelection()) { this.run(postEditor => postEditor.deleteRange(range)); this.cursor.moveToPosition(range.head); - } else { + } else if (event) { const key = Key.fromEvent(event); const nextPosition = this.run(postEditor => { return postEditor.deleteFrom(range.head, key.direction); @@ -633,24 +637,31 @@ class Editor { } handleCut(event) { + event.preventDefault(); + this.handleCopy(event); - this.handleDeletion(event); + this.handleDeletion(); } handleCopy(event) { event.preventDefault(); + setClipboardCopyData(event, this); } handlePaste(event) { event.preventDefault(); + const { head: position } = this.cursor.offsets; + if (this.cursor.hasSelection()) { + this.handleDeletion(); + } + let pastedPost = parsePostFromPaste(event, this.builder); - const range = this.cursor.offsets; let nextPosition; this.run(postEditor => { - nextPosition = postEditor.insertPost(range.head, pastedPost); + nextPosition = postEditor.insertPost(position, pastedPost); }); this.cursor.moveToPosition(nextPosition); diff --git a/tests/acceptance/editor-copy-paste-test.js b/tests/acceptance/editor-copy-paste-test.js index ce8485764..9c76881d4 100644 --- a/tests/acceptance/editor-copy-paste-test.js +++ b/tests/acceptance/editor-copy-paste-test.js @@ -58,6 +58,27 @@ test('can cut and then paste content', (assert) => { assert.hasElement('#editor p:contains(abc)', 'pastes the text'); }); +test('paste when text is selected replaces that text', (assert) => { + const mobiledoc = Helpers.mobiledoc.build( + ({post, markupSection, marker}) => { + return post([markupSection('p', [marker('abc')])]); + }); + editor = new Editor({mobiledoc}); + editor.render(editorElement); + + assert.hasElement('#editor p:contains(abc)', 'precond - has p'); + + Helpers.dom.selectText('bc', editorElement); + Helpers.dom.triggerCopyEvent(editor); + + Helpers.dom.selectText('a', editorElement); + + Helpers.dom.triggerPasteEvent(editor); + + assert.hasElement('#editor p:contains(bcbc)', + 'pastes, replacing the selection'); +}); + test('simple copy-paste with markup at end of section works', (assert) => { const mobiledoc = Helpers.mobiledoc.build( ({post, markupSection, marker, markup}) => {