8
0
فهرست منبع

Merge pull request #165 from ckeditor/t/1106

Fix: Handle <kbd>Backspace</kbd> on Android (by a lovely heuristic for detecting it based on DOM mutations). Closes ckeditor/ckeditor5/issues/1106. Closes ckeditor/ckeditor5/issues/1130.
Piotrek Koszuliński 7 سال پیش
والد
کامیت
bbc2409aeb

+ 4 - 0
packages/ckeditor5-typing/src/delete.js

@@ -11,6 +11,8 @@ import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
 import DeleteCommand from './deletecommand';
 import DeleteObserver from './deleteobserver';
 
+import injectAndroidBackspaceMutationsHandling from './utils/injectandroidbackspacemutationshandling';
+
 /**
  * The delete and backspace feature. Handles the <kbd>Delete</kbd> and <kbd>Backspace</kbd> keys in the editor.
  *
@@ -39,5 +41,7 @@ export default class Delete extends Plugin {
 			data.preventDefault();
 			view.scrollToTheSelection();
 		} );
+
+		injectAndroidBackspaceMutationsHandling( editor );
 	}
 }

+ 167 - 0
packages/ckeditor5-typing/src/utils/injectandroidbackspacemutationshandling.js

@@ -0,0 +1,167 @@
+/**
+ * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/**
+ * @module typing/utils/injectandroidbackspacenutationshandling
+ */
+
+import Selection from '@ckeditor/ckeditor5-engine/src/model/selection';
+import diff from '@ckeditor/ckeditor5-utils/src/diff';
+
+import { containerChildrenMutated } from './utils';
+
+/**
+ * Handles mutations triggered by <kbd>Backspace</kbd> on Android.
+ * Due to the fact that on Android `keydown` events don't have the `keyCode` set, we are not able
+ * to handle backspacing directly. We need to guess that from mutations which the IME
+ * on Android caused.
+ *
+ * @param {module:core/editor/editor~Editor} editor The editor instance.
+ */
+export default function injectAndroidBackspaceMutationsHandling( editor ) {
+	const model = editor.model;
+	const view = editor.editing.view;
+	const selectionChangeToleranceMs = 200;
+
+	let previousSelection = null;
+	let currentSelection = new Selection( model.document.selection );
+	let latestSelectionChangeMs = Date.now();
+
+	model.document.selection.on( 'change', handleSelectionChange );
+
+	view.document.on( 'mutations', handleMutations, { priority: 'highest' } );
+
+	// Saves current and previous selection when it changes. Saved selections are used
+	// to remove correct piece of content when `Backspace` mutations are detected.
+	//
+	// @param {Object} evt
+	function handleSelectionChange( evt ) {
+		const newSelection = new Selection( evt.source );
+		if ( !currentSelection.isEqual( newSelection ) ) {
+			previousSelection = currentSelection;
+			currentSelection = newSelection;
+			latestSelectionChangeMs = Date.now();
+		}
+	}
+
+	// Handles DOM mutations and checks if they should be processed as block elements removal mutations.
+	//
+	// @param {Object} evt
+	// @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
+	// module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
+	function handleMutations( evt, mutations ) {
+		if ( containerChildrenMutated( mutations ) && containsContainersRemoval( mutations ) ) {
+			handleContainerRemovalMutations();
+
+			// Stop mutations event propagation so other mutation handlers are not triggered.
+			evt.stop();
+		}
+	}
+
+	// Handles situations when mutations were generated by container removal.
+	// It happens on Android devices where every typing input has `229` key code
+	// and delete observer will not be triggered. In such cases we need to handle
+	// container removal mutations manually.
+	function handleContainerRemovalMutations() {
+		if ( shouldUsePreviousSelection() ) {
+			// If previous selection is used, update model selection in order
+			// to use `delete` command and to make `undo` work correctly.
+			model.enqueueChange( writer => {
+				writer.setSelection( previousSelection );
+			} );
+		}
+
+		editor.execute( 'delete' );
+	}
+
+	// Whether previously saved selection should be used instead of the current one to remove content.
+	//
+	// On Android devices when pressing backspace on non-collapsed selection, selection like:
+	//
+	//		`<h1>[Foo</h1><p>Bar]</p>`
+	//
+	// is changed to:
+	//
+	//		`<h1>Foo</h1><p>Bar[]</p>`
+	//
+	// even before `keypress` event, so in such cases we have to rely on previous selection to correctly process selected content.
+	//
+	// Previous selection will be used if:
+	//
+	//		* current selection is collapsed (see example above),
+	//		* previous selection exists, is non-collapsed and has same ending (last position) as the current one,
+	//		* change of the selection happened not earlier than X milliseconds ago (see `selectionChangeToleranceMs`).
+	//
+	// The last check is needed, because user can manually collapse the selection on its current end and then press `Backspace`.
+	// In such situations timing determines if the selection change was caused by the user or browser native behaviour.
+	// However, this happens only if selection was collapsed by the user on the beginning of the paragraph (so mutations
+	// still will show container removal).
+	//
+	// @returns {Boolean}
+	function shouldUsePreviousSelection() {
+		return Date.now() - latestSelectionChangeMs < selectionChangeToleranceMs &&
+			previousSelection && !previousSelection.isCollapsed && currentSelection.isCollapsed &&
+			currentSelection.getLastPosition().isEqual( previousSelection.getLastPosition() );
+	}
+}
+
+// Checks whether mutations array contains mutation generated by container/containers removal.
+// For example mutations generated on Android when pressing `backspace` on the beginning of the line:
+//
+//		<h1>Header1</h1>
+//		<p>{}Paragraph</p>
+//
+// are:
+//
+//		[
+//			{ newChildren: [], oldChildren: [ 'Paragraph' ], node: P, type: 'children' },
+//			{ newChildren: [ ContainerElement ], oldChildren: [ ContainerElement, ContainerElement ], node: Root, type: 'children' },
+//			{ newChildren: [ 'Heading 1Paragraph' ], oldChildren: [ 'Heading 1' ], node: H1, type: 'children' }
+//		]
+//
+// The 1st and 3rd mutations are just changes in a text (1st - text in `p` element was removed, 3rd - text in `h2` was changed)
+// and the 2nd one shows that one `ContainerElement` was removed. We have to recognize if mutations like 2nd one are present.
+// Based on that heuristic mutations are treated as the one removing container element.
+//
+// @private
+// @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
+// module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
+// @returns {Boolean}
+function containsContainersRemoval( mutations ) {
+	for ( const mutation of mutations ) {
+		if ( mutation.type !== 'children' ) {
+			continue;
+		}
+
+		const childrenBefore = mutation.oldChildren;
+		const childrenAfter = mutation.newChildren;
+
+		// Check if only containers were present before the mutation.
+		if ( !hasOnlyContainers( childrenBefore ) ) {
+			continue;
+		}
+
+		const diffResult = diff( childrenBefore, childrenAfter );
+
+		// Check if there was only removing in that mutation without any insertions.
+		const hasDelete = diffResult.some( item => item === 'delete' );
+		const hasInsert = diffResult.some( item => item === 'insert' );
+
+		if ( hasDelete && !hasInsert ) {
+			return true;
+		}
+	}
+
+	return false;
+}
+
+// Whether provided array contains only nodes of `containerElement` type.
+//
+// @private
+// @param {Array.<module:engine/view/node~Node>} children
+// @returns {Boolean}
+function hasOnlyContainers( children ) {
+	return children.every( child => child.is( 'containerElement' ) );
+}

+ 2 - 65
packages/ckeditor5-typing/src/utils/injecttypingmutationshandling.js

@@ -9,11 +9,11 @@
 
 import ModelRange from '@ckeditor/ckeditor5-engine/src/model/range';
 import ViewPosition from '@ckeditor/ckeditor5-engine/src/view/position';
-import ViewText from '@ckeditor/ckeditor5-engine/src/view/text';
 import diff from '@ckeditor/ckeditor5-utils/src/diff';
-import diffToChanges from '@ckeditor/ckeditor5-utils/src/difftochanges';
 import DomConverter from '@ckeditor/ckeditor5-engine/src/view/domconverter';
 
+import { getSingleTextNodeChange, containerChildrenMutated } from './utils';
+
 /**
  * Handles mutations caused by normal typing.
  *
@@ -250,45 +250,6 @@ class MutationHandler {
 	}
 }
 
-// Helper function that compares whether two given view nodes are same. It is used in `diff` when it's passed an array
-// with child nodes.
-function compareChildNodes( oldChild, newChild ) {
-	if ( oldChild instanceof ViewText && newChild instanceof ViewText ) {
-		return oldChild.data === newChild.data;
-	} else {
-		return oldChild === newChild;
-	}
-}
-
-// Returns change made to a single text node. Returns `undefined` if more than a single text node was changed.
-//
-// @private
-// @param mutation
-function getSingleTextNodeChange( mutation ) {
-	// One new node.
-	if ( mutation.newChildren.length - mutation.oldChildren.length != 1 ) {
-		return;
-	}
-
-	// Which is text.
-	const diffResult = diff( mutation.oldChildren, mutation.newChildren, compareChildNodes );
-	const changes = diffToChanges( diffResult, mutation.newChildren );
-
-	// In case of [ delete, insert, insert ] the previous check will not exit.
-	if ( changes.length > 1 ) {
-		return;
-	}
-
-	const change = changes[ 0 ];
-
-	// Which is text.
-	if ( !( change.values[ 0 ] instanceof ViewText ) ) {
-		return;
-	}
-
-	return change;
-}
-
 // Returns first common ancestor of all mutations that is either {@link module:engine/view/containerelement~ContainerElement}
 // or {@link module:engine/view/rootelement~RootElement}.
 //
@@ -313,30 +274,6 @@ function getMutationsContainer( mutations ) {
 		.find( element => element.is( 'containerElement' ) || element.is( 'rootElement' ) );
 }
 
-// Returns true if container children have mutated or more than a single text node was changed.
-//
-// Single text node child insertion is handled in {@link module:typing/input~MutationHandler#_handleTextNodeInsertion}
-// while text mutation is handled in {@link module:typing/input~MutationHandler#_handleTextMutation}.
-//
-// @private
-// @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
-// module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
-// @returns {Boolean}
-function containerChildrenMutated( mutations ) {
-	if ( mutations.length == 0 ) {
-		return false;
-	}
-
-	// Check if there is any mutation of `children` type or any mutation that changes more than one text node.
-	for ( const mutation of mutations ) {
-		if ( mutation.type === 'children' && !getSingleTextNodeChange( mutation ) ) {
-			return true;
-		}
-	}
-
-	return false;
-}
-
 // Returns true if provided array contains content that won't be problematic during diffing and text mutation handling.
 //
 // @param {Array.<module:engine/model/node~Node>} children

+ 86 - 0
packages/ckeditor5-typing/src/utils/utils.js

@@ -0,0 +1,86 @@
+/**
+ * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/**
+ * @module typing/utils/utils
+ */
+
+import ViewText from '@ckeditor/ckeditor5-engine/src/view/text';
+import diff from '@ckeditor/ckeditor5-utils/src/diff';
+import diffToChanges from '@ckeditor/ckeditor5-utils/src/difftochanges';
+
+/**
+ * Returns true if container children have mutated or more than a single text node was changed.
+ *
+ * @private
+ * @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|
+ * module:engine/view/observer/mutationobserver~MutatedChildren>} mutations
+ * @returns {Boolean}
+ */
+export function containerChildrenMutated( mutations ) {
+	if ( mutations.length == 0 ) {
+		return false;
+	}
+
+	// Check if there is any mutation of `children` type or any mutation that changes more than one text node.
+	for ( const mutation of mutations ) {
+		if ( mutation.type === 'children' && !getSingleTextNodeChange( mutation ) ) {
+			return true;
+		}
+	}
+
+	return false;
+}
+
+/**
+ * Returns change made to a single text node.
+ *
+ * @private
+ * @param {module:engine/view/observer/mutationobserver~MutatedText|
+ * module:engine/view/observer/mutationobserver~MutatedChildren} mutation
+ * @returns {Object|undefined} Change object (see {@link module:utils/difftochanges~diffToChanges} output)
+ * or undefined if more than a single text node was changed.
+ */
+export function getSingleTextNodeChange( mutation ) {
+	// One new node.
+	if ( mutation.newChildren.length - mutation.oldChildren.length != 1 ) {
+		return;
+	}
+
+	// Which is text.
+	const diffResult = diff( mutation.oldChildren, mutation.newChildren, compareChildNodes );
+	const changes = diffToChanges( diffResult, mutation.newChildren );
+
+	// In case of [ delete, insert, insert ] the previous check will not exit.
+	if ( changes.length > 1 ) {
+		return;
+	}
+
+	const change = changes[ 0 ];
+
+	// Which is text.
+	if ( !( change.values[ 0 ] instanceof ViewText ) ) {
+		return;
+	}
+
+	return change;
+}
+
+/**
+ * Checks whether two view nodes are identical, which means they are the same object
+ * or contain exactly same data (in case of text nodes).
+ *
+ * @private
+ * @param {module:engine/view/node~Node} oldChild
+ * @param {module:engine/view/node~Node} newChild
+ * @returns {Boolean}
+ */
+export function compareChildNodes( oldChild, newChild ) {
+	if ( oldChild instanceof ViewText && newChild instanceof ViewText ) {
+		return oldChild.data === newChild.data;
+	} else {
+		return oldChild === newChild;
+	}
+}

+ 374 - 0
packages/ckeditor5-typing/tests/utils/injectandroidbackspacemutationshandling.js

@@ -0,0 +1,374 @@
+/**
+ * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+import ClassicTestEditor from '@ckeditor/ckeditor5-core/tests/_utils/classictesteditor';
+import testUtils from '@ckeditor/ckeditor5-core/tests/_utils/utils';
+import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
+import Heading from '@ckeditor/ckeditor5-heading/src/heading';
+import Undo from '@ckeditor/ckeditor5-undo/src/undo';
+import Italic from '@ckeditor/ckeditor5-basic-styles/src/italic';
+import Input from '../../src/input';
+import Delete from '../../src/delete';
+
+import ModelRange from '@ckeditor/ckeditor5-engine/src/model/range';
+import ViewText from '@ckeditor/ckeditor5-engine/src/view/text';
+import ViewElement from '@ckeditor/ckeditor5-engine/src/view/element';
+
+import { getData as getModelData } from '@ckeditor/ckeditor5-engine/src/dev-utils/model';
+import { getData as getViewData } from '@ckeditor/ckeditor5-engine/src/dev-utils/view';
+
+/* global document */
+
+describe( 'injectAndroidBackspaceMutationsHandling', () => {
+	let editor, model, modelRoot, view, viewDocument, viewRoot, mutationsSpy, dateNowStub;
+
+	testUtils.createSinonSandbox();
+
+	before( () => {
+		mutationsSpy = sinon.spy();
+	} );
+
+	beforeEach( () => {
+		const domElement = document.createElement( 'div' );
+		document.body.appendChild( domElement );
+
+		return ClassicTestEditor.create( domElement, { plugins: [ Input, Delete, Paragraph, Heading, Italic, Undo ] } )
+			.then( newEditor => {
+				editor = newEditor;
+				model = editor.model;
+				modelRoot = model.document.getRoot();
+				view = editor.editing.view;
+				viewDocument = view.document;
+				viewRoot = viewDocument.getRoot();
+
+				editor.setData( '<h2>Heading 1</h2><p>Paragraph</p><h3>Heading 2</h3>' );
+			} );
+	} );
+
+	afterEach( () => {
+		if ( dateNowStub ) {
+			dateNowStub.restore();
+			dateNowStub = null;
+		}
+
+		mutationsSpy.resetHistory();
+
+		return editor.destroy();
+	} );
+
+	it( 'should handle block merging', () => {
+		// 1. Set selection to '<h2>Heading 1</h2><p>{}Paragraph</p><h3>Heading 2</h3>'.
+		model.change( writer => {
+			writer.setSelection(
+				ModelRange.createFromParentsAndOffsets( modelRoot.getChild( 1 ), 0, modelRoot.getChild( 1 ), 0 )
+			);
+		} );
+
+		const modelContent = '<heading1>Heading 1</heading1><paragraph>[]Paragraph</paragraph><heading2>Heading 2</heading2>';
+		const viewContent = '<h2>Heading 1</h2><p>{}Paragraph</p><h3>Heading 2</h3>';
+
+		expect( getModelData( model ) ).to.equal( modelContent );
+		expect( getViewData( view ) ).to.equal( viewContent );
+
+		// 2. Create mutations which are result of changing HTML to '<h2>Heading 1{}Paragraph</h2><h3>Heading 2</h3>'.
+		const mutations = [ {
+			// `heading1` new text mutation
+			type: 'children',
+			newChildren: [ viewRoot.getChild( 0 ).getChild( 0 ) ],
+			oldChildren: [ viewRoot.getChild( 0 ).getChild( 0 ) ],
+			node: viewRoot.getChild( 0 )
+		}, {
+			// `paragraph` text removal mutation
+			type: 'children',
+			newChildren: [],
+			oldChildren: [ viewRoot.getChild( 1 ).getChild( 0 ) ],
+			node: viewRoot.getChild( 1 )
+		}, {
+			// `paragraph` removal mutation
+			type: 'children',
+			newChildren: [ viewRoot.getChild( 0 ) ],
+			oldChildren: [ viewRoot.getChild( 0 ), viewRoot.getChild( 1 ) ],
+			node: viewRoot
+		} ];
+
+		// 3. Simulate 'Backspace' flow on Android.
+		simulateBackspace( mutations );
+
+		expect( mutationsSpy.callCount ).to.equal( 0 );
+		expect( getModelData( model ) ).to.equal( '<heading1>Heading 1[]Paragraph</heading1><heading2>Heading 2</heading2>' );
+		expect( getViewData( view ) ).to.equal( '<h2>Heading 1{}Paragraph</h2><h3>Heading 2</h3>' );
+
+		// Due ot `Undo` issue the selection is after paragraph after undoing changes (ckeditor5-undo/issues/64).
+		expectContentAfterUndo(
+			'<heading1>Heading 1</heading1><paragraph>Paragraph[]</paragraph><heading2>Heading 2</heading2>',
+			'<h2>Heading 1</h2><p>Paragraph{}</p><h3>Heading 2</h3>' );
+	} );
+
+	it( 'should handle two entire blocks removal', () => {
+		// 1. Set selection to '<h2>{Heading 1</h2><p>Paragraph}</p><h3>Heading 2</h3>'.
+		model.change( writer => {
+			writer.setSelection(
+				ModelRange.createFromParentsAndOffsets( modelRoot.getChild( 0 ), 0, modelRoot.getChild( 1 ), 9 )
+			);
+		} );
+
+		const modelContent = '<heading1>[Heading 1</heading1><paragraph>Paragraph]</paragraph><heading2>Heading 2</heading2>';
+		const viewContent = '<h2>{Heading 1</h2><p>Paragraph}</p><h3>Heading 2</h3>';
+
+		expect( getModelData( model ) ).to.equal( modelContent );
+		expect( getViewData( view ) ).to.equal( viewContent );
+
+		// 2. Create mutations which are result of changing HTML to '<h2>[]</h2><h3>Heading 2</h3>'.
+		const mutations = [ {
+			// `heading1` text removal mutation
+			type: 'children',
+			newChildren: [ new ViewElement( 'br' ) ],
+			oldChildren: [ viewRoot.getChild( 0 ).getChild( 0 ) ],
+			node: viewRoot.getChild( 0 )
+		}, {
+			// `paragraph` removal mutation
+			type: 'children',
+			newChildren: [ viewRoot.getChild( 0 ), viewRoot.getChild( 2 ) ],
+			oldChildren: [ viewRoot.getChild( 0 ), viewRoot.getChild( 1 ), viewRoot.getChild( 2 ) ],
+			node: viewRoot
+		} ];
+
+		// 3. Create selection which simulate Android behaviour where upon pressing `Backspace`
+		// selection is changed to `<h2>Heading 1</h2><p>Paragraph{}</p><h3>Heading 2</h3>`.
+		const newSelection = ModelRange.createFromParentsAndOffsets( modelRoot.getChild( 1 ), 9, modelRoot.getChild( 1 ), 9 );
+
+		// 4. Simulate 'Backspace' flow on Android.
+		simulateBackspace( mutations, newSelection );
+
+		expect( mutationsSpy.callCount ).to.equal( 0 );
+		expect( getModelData( model ) ).to.equal( '<heading1>[]</heading1><heading2>Heading 2</heading2>' );
+		expect( getViewData( view ) ).to.equal( '<h2>[]</h2><h3>Heading 2</h3>' );
+
+		expectContentAfterUndo(
+			'<heading1>[Heading 1</heading1><paragraph>Paragraph]</paragraph><heading2>Heading 2</heading2>',
+			'<h2>{Heading 1</h2><p>Paragraph}</p><h3>Heading 2</h3>' );
+	} );
+
+	it( 'should handle two partially selected blocks removal', () => {
+		// 1. Set selection to '<h2>Hea{ding 1</h2><p>Paragraph}</p><h3>Heading 2</h3>'.
+		model.change( writer => {
+			writer.setSelection(
+				ModelRange.createFromParentsAndOffsets( modelRoot.getChild( 0 ), 3, modelRoot.getChild( 1 ), 9 )
+			);
+		} );
+
+		const modelContent = '<heading1>Hea[ding 1</heading1><paragraph>Paragraph]</paragraph><heading2>Heading 2</heading2>';
+		const viewContent = '<h2>Hea{ding 1</h2><p>Paragraph}</p><h3>Heading 2</h3>';
+
+		expect( getModelData( model ) ).to.equal( modelContent );
+		expect( getViewData( view ) ).to.equal( viewContent );
+
+		// 2. Create mutations which are result of changing HTML to '<h2>Hea{}</h2><h3>Heading 2</h3>'.
+		const mutations = [ {
+			// `heading1` text partial removal mutation
+			type: 'text',
+			newText: 'Hea',
+			oldText: 'Heading 1',
+			node: viewRoot.getChild( 0 ).getChild( 0 )
+		}, {
+			// `paragraph` removal mutation
+			type: 'children',
+			newChildren: [ viewRoot.getChild( 0 ), viewRoot.getChild( 2 ) ],
+			oldChildren: [ viewRoot.getChild( 0 ), viewRoot.getChild( 1 ), viewRoot.getChild( 2 ) ],
+			node: viewRoot
+		} ];
+
+		// 3. Create selection which simulate Android behaviour where upon pressing `Backspace`
+		// selection is changed to `<h2>Heading 1</h2><p>Paragraph{}</p><h3>Heading 2</h3>`.
+		const newSelection = ModelRange.createFromParentsAndOffsets( modelRoot.getChild( 1 ), 9, modelRoot.getChild( 1 ), 9 );
+
+		// 4. Simulate 'Backspace' flow on Android.
+		simulateBackspace( mutations, newSelection );
+
+		expect( mutationsSpy.callCount ).to.equal( 0 );
+		expect( getModelData( model ) ).to.equal( '<heading1>Hea[]</heading1><heading2>Heading 2</heading2>' );
+		expect( getViewData( view ) ).to.equal( '<h2>Hea{}</h2><h3>Heading 2</h3>' );
+
+		expectContentAfterUndo( modelContent, viewContent );
+	} );
+
+	it( 'should handle blocks removal if selection ends on the boundary of inline element', () => {
+		editor.setData( '<h2>Heading 1</h2><p>Paragraph</p><h3><em>Heading</em> 2</h3>' );
+
+		// 1. Set selection to '<h2>{Heading 1</h2><p>Paragraph</p><h3>]<i>Heading</i> 2</h3>'.
+		model.change( writer => {
+			writer.setSelection(
+				ModelRange.createFromParentsAndOffsets( modelRoot.getChild( 0 ), 0, modelRoot.getChild( 2 ), 0 )
+			);
+		} );
+
+		const modelContent = '<heading1>[Heading 1</heading1><paragraph>Paragraph</paragraph>' +
+			'<heading2>]<$text italic="true">Heading</$text> 2</heading2>';
+		const viewContent = '<h2>{Heading 1</h2><p>Paragraph</p><h3>]<i>Heading</i> 2</h3>';
+
+		expect( getModelData( model ) ).to.equal( modelContent );
+		expect( getViewData( view ) ).to.equal( viewContent );
+
+		// 2. Create mutations which are result of changing HTML to '<h2><i>{}Heading</i> 2</h2>'.
+		const mutations = [ {
+			// `heading1` text to children mutation
+			type: 'children',
+			newChildren: Array.from( viewRoot.getChild( 2 ).getChildren() ),
+			oldChildren: [ viewRoot.getChild( 0 ).getChild( 0 ) ],
+			node: viewRoot.getChild( 0 )
+		}, {
+			// `heading2` children removal mutation
+			type: 'children',
+			newChildren: [],
+			oldChildren: Array.from( viewRoot.getChild( 2 ).getChildren() ),
+			node: viewRoot.getChild( 2 )
+		}, { // `paragrpah` and `heading2` removal mutation
+			type: 'children',
+			newChildren: [ viewRoot.getChild( 0 ) ],
+			oldChildren: Array.from( viewRoot.getChildren() ),
+			node: viewRoot
+		} ];
+
+		// 3. Create selection which simulate Android behaviour where upon pressing `Backspace`
+		// selection is changed to `<h2>Heading 1</h2><p>Paragraph</p><h3><em>{}Heading</em> 2</h3>`.
+		const newSelection = ModelRange.createFromParentsAndOffsets( modelRoot.getChild( 2 ), 0, modelRoot.getChild( 2 ), 0 );
+
+		// 4. Simulate 'Backspace' flow on Android.
+		simulateBackspace( mutations, newSelection );
+
+		expect( mutationsSpy.callCount ).to.equal( 0 );
+		expect( getModelData( model ) ).to.equal( '<heading1><$text italic="true">[]Heading</$text> 2</heading1>' );
+		expect( getViewData( view ) ).to.equal( '<h2><i>{}Heading</i> 2</h2>' );
+
+		expectContentAfterUndo( modelContent, viewContent );
+	} );
+
+	it( 'should handle selection changed by the user before `backspace` on block merging', () => {
+		// 1. Stub `Date.now` so we can simulate user selection change timing.
+		let dateNowValue = 0;
+		dateNowStub = sinon.stub( Date, 'now' ).callsFake( () => {
+			dateNowValue += 500;
+			return dateNowValue;
+		} );
+
+		editor.setData( '<h2>Heading 1</h2><p>Paragraph</p><h3><em>Heading</em> 2</h3>' );
+
+		// 2. Set selection to '<h2>{Heading 1</h2><p>Paragraph</p><h3>]<i>Heading</i> 2</h3>'.
+		model.change( writer => {
+			writer.setSelection(
+				ModelRange.createFromParentsAndOffsets( modelRoot.getChild( 0 ), 0, modelRoot.getChild( 2 ), 0 )
+			);
+		} );
+
+		const modelContent = '<heading1>[Heading 1</heading1><paragraph>Paragraph</paragraph>' +
+			'<heading2>]<$text italic="true">Heading</$text> 2</heading2>';
+		const viewContent = '<h2>{Heading 1</h2><p>Paragraph</p><h3>]<i>Heading</i> 2</h3>';
+
+		expect( getModelData( model ) ).to.equal( modelContent );
+		expect( getViewData( view ) ).to.equal( viewContent );
+
+		// 3. Create mutations which are result of changing HTML to '<h2>Heading 1</h2><p>Paragraph{}<i>Heading</i> 2</p>'.
+		// This is still a block container removal so 'injectAndroidBackspaceMutationsHandling' will get triggered.
+		const mutations = [ {
+			// `paragraph` children added mutation
+			type: 'children',
+			newChildren: [ viewRoot.getChild( 1 ).getChild( 0 ) ].concat( Array.from( viewRoot.getChild( 2 ).getChildren() ) ),
+			oldChildren: Array.from( viewRoot.getChild( 1 ).getChildren() ),
+			node: viewRoot.getChild( 1 )
+		}, {
+			// `heading2` children removal mutation
+			type: 'children',
+			newChildren: [],
+			oldChildren: Array.from( viewRoot.getChild( 2 ).getChildren() ),
+			node: viewRoot.getChild( 2 )
+		}, { // `heading2` removal mutation
+			type: 'children',
+			newChildren: [ viewRoot.getChild( 0 ), viewRoot.getChild( 1 ) ],
+			oldChildren: Array.from( viewRoot.getChildren() ),
+			node: viewRoot
+		} ];
+
+		// 4. Simulate user selection change which is identical as Android native change on 'Backspace'.
+		model.change( writer => {
+			writer.setSelection( ModelRange.createFromParentsAndOffsets( modelRoot.getChild( 2 ), 0, modelRoot.getChild( 2 ), 0 ) );
+		} );
+
+		// 5. Simulate 'Backspace' flow on Android.
+		simulateBackspace( mutations );
+
+		expect( mutationsSpy.callCount ).to.equal( 0 );
+		expect( getModelData( model ) ).to.equal( '<heading1>Heading 1</heading1><paragraph>Paragraph[]' +
+			'<$text italic="true">Heading</$text> 2</paragraph>' );
+		expect( getViewData( view ) ).to.equal( '<h2>Heading 1</h2><p>Paragraph{}<i>Heading</i> 2</p>' );
+
+		// Due ot `Undo` issue the selection is after paragraph after undoing changes (ckeditor5-undo/issues/64).
+		expectContentAfterUndo( '<heading1>Heading 1</heading1><paragraph>Paragraph</paragraph>' +
+			'<heading2><$text italic="true">Heading</$text> 2[]</heading2>',
+		'<h2>Heading 1</h2><p>Paragraph</p><h3><i>Heading</i> 2{}</h3>' );
+	} );
+
+	it( 'should not be triggered for container insertion mutations', () => {
+		// 1. Set selection to '<h2>Heading 1</h2><p>Paragraph{}</p><h3>Heading 2</h3>'.
+		model.change( writer => {
+			writer.setSelection(
+				ModelRange.createFromParentsAndOffsets( modelRoot.getChild( 1 ), 9, modelRoot.getChild( 1 ), 9 )
+			);
+		} );
+
+		const modelContent = '<heading1>Heading 1</heading1><paragraph>Paragraph[]</paragraph><heading2>Heading 2</heading2>';
+		const viewContent = '<h2>Heading 1</h2><p>Paragraph{}</p><h3>Heading 2</h3>';
+
+		expect( getModelData( model ) ).to.equal( modelContent );
+		expect( getViewData( view ) ).to.equal( viewContent );
+
+		const viewFoo = new ViewText( 'foo' );
+		const viewP = new ViewElement( 'p', null, viewFoo );
+
+		// 2. Create mutations which are result of changing HTML to '<h2>Heading 1</h2><p>Paragraph{}</p><p>Foo</p><h3>Heading 2</h3>'.
+		const mutations = [ {
+			// new paragraph insertion mutation
+			type: 'children',
+			newChildren: [ viewRoot.getChild( 0 ), viewRoot.getChild( 1 ), viewP, viewRoot.getChild( 2 ) ],
+			oldChildren: Array.from( viewRoot.getChildren() ),
+			node: viewRoot.getChild( 0 )
+		} ];
+
+		// 3. Spy mutations listener calls. It should be called ones
+		// as it was not stopped by 'injectAndroidBackspaceMutationsHandling' handler.
+		viewDocument.on( 'mutations', mutationsSpy, { priority: 'lowest' } );
+
+		// 4. Fire mutations event.
+		viewDocument.fire( 'mutations', mutations );
+
+		expect( mutationsSpy.callCount ).to.equal( 1 );
+		expect( getModelData( model ) ).to.equal( modelContent );
+		expect( getViewData( view ) ).to.equal( viewContent );
+	} );
+
+	function simulateBackspace( mutations, newSelection ) {
+		// Spy mutations listener calls. If Android handler was triggered it should prevent further calls.
+		viewDocument.on( 'mutations', mutationsSpy, { priority: 'lowest' } );
+
+		// Simulate selection change on Android devices before `keydown` event.
+		if ( newSelection ) {
+			model.change( writer => {
+				writer.setSelection( newSelection );
+			} );
+		}
+
+		// Fire `keydown` event with `229` key code so it is consistent with what happens on Android devices.
+		viewDocument.fire( 'keydown', { keyCode: 229 } );
+
+		// Fire mutations event.
+		viewDocument.fire( 'mutations', mutations );
+	}
+
+	function expectContentAfterUndo( modelContent, viewContent ) {
+		editor.execute( 'undo' );
+
+		expect( getModelData( model ) ).to.equal( modelContent );
+		expect( getViewData( view ) ).to.equal( viewContent );
+	}
+} );